ebyhr commented on code in PR #12808: URL: https://github.com/apache/iceberg/pull/12808#discussion_r2048088148
########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetaStoreClientImpl.java: ########## @@ -0,0 +1,620 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.http.HttpHeaders; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.HttpResponseException; +import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.client.util.Data; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.BigqueryScopes; +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.ExternalCatalogTableOptions; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList; +import com.google.api.services.bigquery.model.TableList.Tables; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.BaseServiceException; +import com.google.cloud.ExceptionHandler; +import com.google.cloud.bigquery.BigQueryErrorMessages; +import com.google.cloud.bigquery.BigQueryOptions; +import com.google.cloud.bigquery.BigQueryRetryConfig; +import com.google.cloud.bigquery.BigQueryRetryHelper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.BadRequestException; +import org.apache.iceberg.exceptions.ForbiddenException; +import org.apache.iceberg.exceptions.NoSuchIcebergTableException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.exceptions.NotAuthorizedException; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.exceptions.ServiceFailureException; +import org.apache.iceberg.exceptions.ServiceUnavailableException; +import org.apache.iceberg.exceptions.ValidationException; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; + +/** A client of Google Bigquery Metastore functions over the BigQuery service. */ +public final class BigQueryMetaStoreClientImpl implements BigQueryMetaStoreClient { + + public static final ExceptionHandler.Interceptor EXCEPTION_HANDLER_INTERCEPTOR = + new ExceptionHandler.Interceptor() { + + private static final long serialVersionUID = -8429573486870467828L; + + @Override + public RetryResult afterEval(Exception exception, RetryResult retryResult) { + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + + @Override + public RetryResult beforeEval(Exception exception) { + if (exception instanceof BaseServiceException) { + boolean retriable = ((BaseServiceException) exception).isRetryable(); + return retriable + ? ExceptionHandler.Interceptor.RetryResult.RETRY + : ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + }; + + private final Bigquery client; + private final BigQueryOptions bigqueryOptions; + + // Retry config with error messages and regex for rate limit exceeded errors. + private static final BigQueryRetryConfig DEFAULT_RETRY_CONFIG = + BigQueryRetryConfig.newBuilder() + .retryOnMessage(BigQueryErrorMessages.RATE_LIMIT_EXCEEDED_MSG) + .retryOnMessage(BigQueryErrorMessages.JOB_RATE_LIMIT_EXCEEDED_MSG) + .retryOnRegEx(BigQueryErrorMessages.RetryRegExPatterns.RATE_LIMIT_EXCEEDED_REGEX) + .build(); + + public static final ExceptionHandler BIGQUERY_EXCEPTION_HANDLER = + ExceptionHandler.newBuilder() + .abortOn(RuntimeException.class) + .retryOn(java.net.ConnectException.class) // retry on Connection Exception + .retryOn(java.net.UnknownHostException.class) // retry on UnknownHostException Review Comment: "retry on UnknownHostException" is obvious when reading the code. It would be nice to explain **_why_** we retry on such exceptions. ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetaStoreClient.java: ########## @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList.Tables; +import com.google.api.services.bigquery.model.TableReference; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * A client of Google BigQuery Metastore functions over the BigQuery service. Uses the Google + * BigQuery API. + */ +public interface BigQueryMetaStoreClient { Review Comment: nit: BigQueryMetaStoreClient -> BigQueryMetastoreClient? ########## bigquery/src/test/java/org/apache/iceberg/gcp/bigquery/BigQueryMetastoreTestUtils.java: ########## @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import static org.apache.iceberg.types.Types.NestedField.required; +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.api.services.bigquery.model.ExternalCatalogTableOptions; +import com.google.api.services.bigquery.model.StorageDescriptor; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableReference; +import java.io.File; +import java.io.IOException; +import java.util.Collections; +import java.util.Optional; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.filefilter.TrueFileFilter; +import org.apache.iceberg.Schema; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.types.Types; + +/** Test utility methods for BigQuery Metastore Iceberg catalog. */ +public final class BigQueryMetastoreTestUtils { + private BigQueryMetastoreTestUtils() {} + + public static final String METADATA_LOCATION_PROP = "metadata_location"; + + public static Schema getTestSchema() { + return new Schema( + required(1, "id", Types.IntegerType.get(), "unique ID"), + required(2, "data", Types.StringType.get())); + } + + public static Table createTestTable( + File tempFolder, + BigQueryMetastoreCatalog bigQueryMetastoreCatalog, + TableReference tableReference) + throws IOException { + Schema schema = getTestSchema(); + TableIdentifier tableIdentifier = + TableIdentifier.of(tableReference.getDatasetId(), tableReference.getTableId()); + String tableDir = tempFolder.toPath().resolve(tableReference.getTableId()).toString(); + + bigQueryMetastoreCatalog + .buildTable(tableIdentifier, schema) + .withLocation(tableDir) + .createTransaction() + .commitTransaction(); + + Optional<String> metadataLocation = getIcebergMetadataFilePath(tableDir); + assertThat(metadataLocation.isPresent()); Review Comment: ```suggestion assertThat(metadataLocation).isPresent(); ``` ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetaStoreClientImpl.java: ########## @@ -0,0 +1,620 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.http.HttpHeaders; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.HttpResponseException; +import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.client.util.Data; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.BigqueryScopes; +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.ExternalCatalogTableOptions; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList; +import com.google.api.services.bigquery.model.TableList.Tables; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.BaseServiceException; +import com.google.cloud.ExceptionHandler; +import com.google.cloud.bigquery.BigQueryErrorMessages; +import com.google.cloud.bigquery.BigQueryOptions; +import com.google.cloud.bigquery.BigQueryRetryConfig; +import com.google.cloud.bigquery.BigQueryRetryHelper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.BadRequestException; +import org.apache.iceberg.exceptions.ForbiddenException; +import org.apache.iceberg.exceptions.NoSuchIcebergTableException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.exceptions.NotAuthorizedException; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.exceptions.ServiceFailureException; +import org.apache.iceberg.exceptions.ServiceUnavailableException; +import org.apache.iceberg.exceptions.ValidationException; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; + +/** A client of Google Bigquery Metastore functions over the BigQuery service. */ +public final class BigQueryMetaStoreClientImpl implements BigQueryMetaStoreClient { + + public static final ExceptionHandler.Interceptor EXCEPTION_HANDLER_INTERCEPTOR = + new ExceptionHandler.Interceptor() { + + private static final long serialVersionUID = -8429573486870467828L; + + @Override + public RetryResult afterEval(Exception exception, RetryResult retryResult) { + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + + @Override + public RetryResult beforeEval(Exception exception) { + if (exception instanceof BaseServiceException) { + boolean retriable = ((BaseServiceException) exception).isRetryable(); + return retriable + ? ExceptionHandler.Interceptor.RetryResult.RETRY + : ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + }; + + private final Bigquery client; + private final BigQueryOptions bigqueryOptions; + + // Retry config with error messages and regex for rate limit exceeded errors. + private static final BigQueryRetryConfig DEFAULT_RETRY_CONFIG = + BigQueryRetryConfig.newBuilder() + .retryOnMessage(BigQueryErrorMessages.RATE_LIMIT_EXCEEDED_MSG) + .retryOnMessage(BigQueryErrorMessages.JOB_RATE_LIMIT_EXCEEDED_MSG) + .retryOnRegEx(BigQueryErrorMessages.RetryRegExPatterns.RATE_LIMIT_EXCEEDED_REGEX) + .build(); + + public static final ExceptionHandler BIGQUERY_EXCEPTION_HANDLER = + ExceptionHandler.newBuilder() + .abortOn(RuntimeException.class) + .retryOn(java.net.ConnectException.class) // retry on Connection Exception + .retryOn(java.net.UnknownHostException.class) // retry on UnknownHostException + .addInterceptors(EXCEPTION_HANDLER_INTERCEPTOR) + .build(); + + /** Constructs a client of the Google BigQuery service. */ + public BigQueryMetaStoreClientImpl(BigQueryOptions options) + throws IOException, GeneralSecurityException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests + HttpCredentialsAdapter httpCredentialsAdapter = + new HttpCredentialsAdapter( + GoogleCredentials.getApplicationDefault().createScoped(BigqueryScopes.all())); + this.client = + new Bigquery.Builder( + GoogleNetHttpTransport.newTrustedTransport(), + GsonFactory.getDefaultInstance(), + httpRequest -> { + httpCredentialsAdapter.initialize(httpRequest); + // Instead of throwing exceptions, analyze the HttpResponse object and inspect its + // status code. This will allow BigQuery API errors to be converted into Iceberg + // exceptions. + httpRequest.setThrowExceptionOnExecuteError(false); + }) + .setApplicationName("BigQuery Iceberg Catalog Plugin") + .build(); + this.bigqueryOptions = options; + } + + @Override + public Dataset createDataset(Dataset dataset) { + // TODO (b/399885863): Ensure Dataset creation is idempotent when handling retries. + Dataset response = null; + try { + response = + BigQueryRetryHelper.runWithRetries( + new Callable<Dataset>() { + @Override + public Dataset call() { + return create(dataset); + } + }, + bigqueryOptions.getRetrySettings(), + BIGQUERY_EXCEPTION_HANDLER, + bigqueryOptions.getClock(), + DEFAULT_RETRY_CONFIG); + } catch (BigQueryRetryHelper.BigQueryRetryHelperException e) { + handleBigQueryRetryException(e); + } + return response; + } + + @SuppressWarnings("FormatStringAnnotation") + private Dataset create(Dataset dataset) { + try { + HttpResponse response = + client + .datasets() + .insert(dataset.getDatasetReference().getProjectId(), dataset) + .executeUnparsed(); + return convertExceptionIfUnsuccessful(response).parseAs(Dataset.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } catch (AlreadyExistsException e) { + throw new AlreadyExistsException("Namespace already exists: " + dataset.getId()); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public Dataset getDataset(DatasetReference datasetReference) { + try { + HttpResponse response = + client + .datasets() + .get(datasetReference.getProjectId(), datasetReference.getDatasetId()) + .executeUnparsed(); + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchNamespaceException( + "Namespace does not exist: " + datasetReference.getDatasetId()); + } + return convertExceptionIfUnsuccessful(response).parseAs(Dataset.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public void deleteDataset(DatasetReference datasetReference) { + try { + HttpResponse response = + client + .datasets() + .delete(datasetReference.getProjectId(), datasetReference.getDatasetId()) + .executeUnparsed(); + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchNamespaceException( + "Namespace does not exist: " + datasetReference.getDatasetId()); + } + convertExceptionIfUnsuccessful(response); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + public Dataset setDatasetParameters( + DatasetReference datasetReference, Map<String, String> parameters) { + Dataset dataset = getDataset(datasetReference); + ExternalCatalogDatasetOptions externalCatalogDatasetOptions = + dataset.getExternalCatalogDatasetOptions() == null + ? new ExternalCatalogDatasetOptions() + : dataset.getExternalCatalogDatasetOptions(); + Map<String, String> finalParameters = + externalCatalogDatasetOptions.getParameters() == null + ? Maps.newHashMap() + : externalCatalogDatasetOptions.getParameters(); + finalParameters.putAll(parameters); + + dataset.setExternalCatalogDatasetOptions( + externalCatalogDatasetOptions.setParameters(finalParameters)); + + return updateDataset(dataset); + } + + @Override + public Dataset removeDatasetParameters( + DatasetReference datasetReference, Set<String> parameters) { + Dataset dataset = getDataset(datasetReference); + ExternalCatalogDatasetOptions externalCatalogDatasetOptions = + dataset.getExternalCatalogDatasetOptions() == null + ? new ExternalCatalogDatasetOptions() + : dataset.getExternalCatalogDatasetOptions(); + Map<String, String> finalParameters = + externalCatalogDatasetOptions.getParameters() == null + ? Maps.newHashMap() + : externalCatalogDatasetOptions.getParameters(); + parameters.forEach(finalParameters::remove); + + dataset.setExternalCatalogDatasetOptions( + externalCatalogDatasetOptions.setParameters(finalParameters)); + + return updateDataset(dataset); + } + + @Override + public List<Datasets> listDatasets(String projectId) { + try { + String nextPageToken = null; + List<Datasets> datasets = Lists.newArrayList(); + do { + HttpResponse pageResponse = + client.datasets().list(projectId).setPageToken(nextPageToken).executeUnparsed(); + DatasetList result = + convertExceptionIfUnsuccessful(pageResponse).parseAs(DatasetList.class); + nextPageToken = result.getNextPageToken(); + if (result.getDatasets() != null) { + datasets.addAll(result.getDatasets()); + } + } while (nextPageToken != null && !nextPageToken.isEmpty()); + return datasets; + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + public Table createTable(Table table) { + // Ensure it is an Iceberg table supported by the BQ metastore catalog. + validateTable(table); + // TODO (b/399885863): Ensure table creation is idempotent when handling retries. Review Comment: This repository isn't only for Google engineers :) ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetaStoreClientImpl.java: ########## @@ -0,0 +1,620 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.http.HttpHeaders; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.HttpResponseException; +import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.client.util.Data; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.BigqueryScopes; +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.ExternalCatalogTableOptions; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList; +import com.google.api.services.bigquery.model.TableList.Tables; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.BaseServiceException; +import com.google.cloud.ExceptionHandler; +import com.google.cloud.bigquery.BigQueryErrorMessages; +import com.google.cloud.bigquery.BigQueryOptions; +import com.google.cloud.bigquery.BigQueryRetryConfig; +import com.google.cloud.bigquery.BigQueryRetryHelper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.BadRequestException; +import org.apache.iceberg.exceptions.ForbiddenException; +import org.apache.iceberg.exceptions.NoSuchIcebergTableException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.exceptions.NotAuthorizedException; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.exceptions.ServiceFailureException; +import org.apache.iceberg.exceptions.ServiceUnavailableException; +import org.apache.iceberg.exceptions.ValidationException; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; + +/** A client of Google Bigquery Metastore functions over the BigQuery service. */ +public final class BigQueryMetaStoreClientImpl implements BigQueryMetaStoreClient { + + public static final ExceptionHandler.Interceptor EXCEPTION_HANDLER_INTERCEPTOR = + new ExceptionHandler.Interceptor() { + + private static final long serialVersionUID = -8429573486870467828L; + + @Override + public RetryResult afterEval(Exception exception, RetryResult retryResult) { + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + + @Override + public RetryResult beforeEval(Exception exception) { + if (exception instanceof BaseServiceException) { + boolean retriable = ((BaseServiceException) exception).isRetryable(); + return retriable + ? ExceptionHandler.Interceptor.RetryResult.RETRY + : ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + }; + + private final Bigquery client; + private final BigQueryOptions bigqueryOptions; + + // Retry config with error messages and regex for rate limit exceeded errors. + private static final BigQueryRetryConfig DEFAULT_RETRY_CONFIG = + BigQueryRetryConfig.newBuilder() + .retryOnMessage(BigQueryErrorMessages.RATE_LIMIT_EXCEEDED_MSG) + .retryOnMessage(BigQueryErrorMessages.JOB_RATE_LIMIT_EXCEEDED_MSG) + .retryOnRegEx(BigQueryErrorMessages.RetryRegExPatterns.RATE_LIMIT_EXCEEDED_REGEX) + .build(); + + public static final ExceptionHandler BIGQUERY_EXCEPTION_HANDLER = + ExceptionHandler.newBuilder() + .abortOn(RuntimeException.class) + .retryOn(java.net.ConnectException.class) // retry on Connection Exception + .retryOn(java.net.UnknownHostException.class) // retry on UnknownHostException + .addInterceptors(EXCEPTION_HANDLER_INTERCEPTOR) + .build(); + + /** Constructs a client of the Google BigQuery service. */ + public BigQueryMetaStoreClientImpl(BigQueryOptions options) + throws IOException, GeneralSecurityException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests + HttpCredentialsAdapter httpCredentialsAdapter = + new HttpCredentialsAdapter( + GoogleCredentials.getApplicationDefault().createScoped(BigqueryScopes.all())); + this.client = + new Bigquery.Builder( + GoogleNetHttpTransport.newTrustedTransport(), + GsonFactory.getDefaultInstance(), + httpRequest -> { + httpCredentialsAdapter.initialize(httpRequest); + // Instead of throwing exceptions, analyze the HttpResponse object and inspect its + // status code. This will allow BigQuery API errors to be converted into Iceberg + // exceptions. + httpRequest.setThrowExceptionOnExecuteError(false); + }) + .setApplicationName("BigQuery Metastore Iceberg Catalog Plugin") + .build(); + this.bigqueryOptions = options; + } + + @Override + public Dataset createDataset(Dataset dataset) { + // TODO (b/399885863): Ensure Dataset creation is idempotent when handling retries. + Dataset response = null; + try { + response = + BigQueryRetryHelper.runWithRetries( + new Callable<Dataset>() { + @Override + public Dataset call() { + return create(dataset); + } + }, Review Comment: We could replace these code with lambda `() -> create(dataset)` ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetaStoreClient.java: ########## @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList.Tables; +import com.google.api.services.bigquery.model.TableReference; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * A client of Google BigQuery Metastore functions over the BigQuery service. Uses the Google + * BigQuery API. + */ +public interface BigQueryMetaStoreClient { + + /** + * Creates and returns a new dataset. + * + * @param dataset the dataset to create + */ + Dataset createDataset(Dataset dataset); + + /** + * Returns a dataset. + * + * @param datasetReference full dataset reference + */ + Dataset getDataset(DatasetReference datasetReference); + + /** + * Deletes a dataset. + * + * @param datasetReference full dataset reference + */ + void deleteDataset(DatasetReference datasetReference); + + /** + * Updates parameters of a dataset or adds them if did not exist, leaving already-existing ones + * intact. + * + * @param datasetReference full dataset reference + * @param parameters metadata parameters to add + * @return dataset after patch + */ + Dataset setDatasetParameters(DatasetReference datasetReference, Map<String, String> parameters); + + /** + * Removes given set of keys of parameters of a dataset. Ignores keys that do not exist already. + * + * @param datasetReference full dataset reference + * @param parameters metadata parameter keys to remove + * @return dataset after patch + */ + Dataset removeDatasetParameters(DatasetReference datasetReference, Set<String> parameters); + + /** + * Lists datasets under a given project + * + * @param projectId the identifier of the project to list datasets under + */ + List<Datasets> listDatasets(String projectId); + + /** + * Creates and returns a new table. + * + * @param table body of the table to create + */ + Table createTable(Table table); + + /** + * Returns a table. + * + * @param tableReference full table reference + */ + Table getTable(TableReference tableReference); + + /** + * Updates the catalog table options of an Iceberg table and returns the updated table. + * + * @param tableReference full table reference + * @param table to patch + */ + Table patchTable(TableReference tableReference, Table table); + + /** + * Renames a table. + * + * @param tableToRename full table reference + * @param newTableId new table identifier + */ + Table renameTable(TableReference tableToRename, String newTableId); Review Comment: This method is unused. ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/FakeBigQueryMetaStoreClient.java: ########## @@ -0,0 +1,228 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList; +import com.google.api.services.bigquery.model.TableReference; +import com.google.cloud.bigquery.BigQueryOptions; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.CommitFailedException; +import org.apache.iceberg.exceptions.NamespaceNotEmptyException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; + +public class FakeBigQueryMetaStoreClient implements BigQueryMetaStoreClient { Review Comment: How about renaming to FakeBigQueryMetaStoreClient? ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetaStoreClientImpl.java: ########## @@ -0,0 +1,620 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.http.HttpHeaders; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.HttpResponseException; +import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.client.util.Data; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.BigqueryScopes; +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.ExternalCatalogTableOptions; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList; +import com.google.api.services.bigquery.model.TableList.Tables; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.BaseServiceException; +import com.google.cloud.ExceptionHandler; +import com.google.cloud.bigquery.BigQueryErrorMessages; +import com.google.cloud.bigquery.BigQueryOptions; +import com.google.cloud.bigquery.BigQueryRetryConfig; +import com.google.cloud.bigquery.BigQueryRetryHelper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.BadRequestException; +import org.apache.iceberg.exceptions.ForbiddenException; +import org.apache.iceberg.exceptions.NoSuchIcebergTableException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.exceptions.NotAuthorizedException; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.exceptions.ServiceFailureException; +import org.apache.iceberg.exceptions.ServiceUnavailableException; +import org.apache.iceberg.exceptions.ValidationException; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; + +/** A client of Google Bigquery Metastore functions over the BigQuery service. */ +public final class BigQueryMetaStoreClientImpl implements BigQueryMetaStoreClient { + + public static final ExceptionHandler.Interceptor EXCEPTION_HANDLER_INTERCEPTOR = + new ExceptionHandler.Interceptor() { + + private static final long serialVersionUID = -8429573486870467828L; + + @Override + public RetryResult afterEval(Exception exception, RetryResult retryResult) { + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + + @Override + public RetryResult beforeEval(Exception exception) { + if (exception instanceof BaseServiceException) { + boolean retriable = ((BaseServiceException) exception).isRetryable(); + return retriable + ? ExceptionHandler.Interceptor.RetryResult.RETRY + : ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + }; + + private final Bigquery client; + private final BigQueryOptions bigqueryOptions; + + // Retry config with error messages and regex for rate limit exceeded errors. + private static final BigQueryRetryConfig DEFAULT_RETRY_CONFIG = + BigQueryRetryConfig.newBuilder() + .retryOnMessage(BigQueryErrorMessages.RATE_LIMIT_EXCEEDED_MSG) + .retryOnMessage(BigQueryErrorMessages.JOB_RATE_LIMIT_EXCEEDED_MSG) + .retryOnRegEx(BigQueryErrorMessages.RetryRegExPatterns.RATE_LIMIT_EXCEEDED_REGEX) + .build(); + + public static final ExceptionHandler BIGQUERY_EXCEPTION_HANDLER = + ExceptionHandler.newBuilder() + .abortOn(RuntimeException.class) + .retryOn(java.net.ConnectException.class) // retry on Connection Exception + .retryOn(java.net.UnknownHostException.class) // retry on UnknownHostException + .addInterceptors(EXCEPTION_HANDLER_INTERCEPTOR) + .build(); + + /** Constructs a client of the Google BigQuery service. */ + public BigQueryMetaStoreClientImpl(BigQueryOptions options) + throws IOException, GeneralSecurityException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests + HttpCredentialsAdapter httpCredentialsAdapter = + new HttpCredentialsAdapter( + GoogleCredentials.getApplicationDefault().createScoped(BigqueryScopes.all())); + this.client = + new Bigquery.Builder( + GoogleNetHttpTransport.newTrustedTransport(), + GsonFactory.getDefaultInstance(), + httpRequest -> { + httpCredentialsAdapter.initialize(httpRequest); + // Instead of throwing exceptions, analyze the HttpResponse object and inspect its + // status code. This will allow BigQuery API errors to be converted into Iceberg + // exceptions. + httpRequest.setThrowExceptionOnExecuteError(false); + }) + .setApplicationName("BigQuery Metastore Iceberg Catalog Plugin") + .build(); + this.bigqueryOptions = options; + } + + @Override + public Dataset createDataset(Dataset dataset) { + // TODO (b/399885863): Ensure Dataset creation is idempotent when handling retries. Review Comment: What is `b/399885863`? ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetaStoreClientImpl.java: ########## @@ -0,0 +1,620 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.http.HttpHeaders; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.HttpResponseException; +import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.client.util.Data; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.BigqueryScopes; +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.ExternalCatalogTableOptions; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList; +import com.google.api.services.bigquery.model.TableList.Tables; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.BaseServiceException; +import com.google.cloud.ExceptionHandler; +import com.google.cloud.bigquery.BigQueryErrorMessages; +import com.google.cloud.bigquery.BigQueryOptions; +import com.google.cloud.bigquery.BigQueryRetryConfig; +import com.google.cloud.bigquery.BigQueryRetryHelper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.BadRequestException; +import org.apache.iceberg.exceptions.ForbiddenException; +import org.apache.iceberg.exceptions.NoSuchIcebergTableException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.exceptions.NotAuthorizedException; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.exceptions.ServiceFailureException; +import org.apache.iceberg.exceptions.ServiceUnavailableException; +import org.apache.iceberg.exceptions.ValidationException; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; + +/** A client of Google Bigquery Metastore functions over the BigQuery service. */ +public final class BigQueryMetaStoreClientImpl implements BigQueryMetaStoreClient { + + public static final ExceptionHandler.Interceptor EXCEPTION_HANDLER_INTERCEPTOR = + new ExceptionHandler.Interceptor() { + + private static final long serialVersionUID = -8429573486870467828L; + + @Override + public RetryResult afterEval(Exception exception, RetryResult retryResult) { + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + + @Override + public RetryResult beforeEval(Exception exception) { + if (exception instanceof BaseServiceException) { + boolean retriable = ((BaseServiceException) exception).isRetryable(); + return retriable + ? ExceptionHandler.Interceptor.RetryResult.RETRY + : ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + }; + + private final Bigquery client; + private final BigQueryOptions bigqueryOptions; + + // Retry config with error messages and regex for rate limit exceeded errors. + private static final BigQueryRetryConfig DEFAULT_RETRY_CONFIG = + BigQueryRetryConfig.newBuilder() + .retryOnMessage(BigQueryErrorMessages.RATE_LIMIT_EXCEEDED_MSG) + .retryOnMessage(BigQueryErrorMessages.JOB_RATE_LIMIT_EXCEEDED_MSG) + .retryOnRegEx(BigQueryErrorMessages.RetryRegExPatterns.RATE_LIMIT_EXCEEDED_REGEX) + .build(); + + public static final ExceptionHandler BIGQUERY_EXCEPTION_HANDLER = + ExceptionHandler.newBuilder() + .abortOn(RuntimeException.class) + .retryOn(java.net.ConnectException.class) // retry on Connection Exception + .retryOn(java.net.UnknownHostException.class) // retry on UnknownHostException + .addInterceptors(EXCEPTION_HANDLER_INTERCEPTOR) + .build(); + + /** Constructs a client of the Google BigQuery service. */ + public BigQueryMetaStoreClientImpl(BigQueryOptions options) + throws IOException, GeneralSecurityException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests + HttpCredentialsAdapter httpCredentialsAdapter = + new HttpCredentialsAdapter( + GoogleCredentials.getApplicationDefault().createScoped(BigqueryScopes.all())); + this.client = + new Bigquery.Builder( + GoogleNetHttpTransport.newTrustedTransport(), + GsonFactory.getDefaultInstance(), + httpRequest -> { + httpCredentialsAdapter.initialize(httpRequest); + // Instead of throwing exceptions, analyze the HttpResponse object and inspect its + // status code. This will allow BigQuery API errors to be converted into Iceberg + // exceptions. + httpRequest.setThrowExceptionOnExecuteError(false); + }) + .setApplicationName("BigQuery Metastore Iceberg Catalog Plugin") + .build(); + this.bigqueryOptions = options; + } + + @Override + public Dataset createDataset(Dataset dataset) { + // TODO (b/399885863): Ensure Dataset creation is idempotent when handling retries. + Dataset response = null; + try { + response = + BigQueryRetryHelper.runWithRetries( + new Callable<Dataset>() { + @Override + public Dataset call() { + return create(dataset); + } + }, + bigqueryOptions.getRetrySettings(), + BIGQUERY_EXCEPTION_HANDLER, + bigqueryOptions.getClock(), + DEFAULT_RETRY_CONFIG); + } catch (BigQueryRetryHelper.BigQueryRetryHelperException e) { + handleBigQueryRetryException(e); + } + return response; + } + + @SuppressWarnings("FormatStringAnnotation") + private Dataset create(Dataset dataset) { + try { + HttpResponse response = + client + .datasets() + .insert(dataset.getDatasetReference().getProjectId(), dataset) + .executeUnparsed(); + return convertExceptionIfUnsuccessful(response).parseAs(Dataset.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } catch (AlreadyExistsException e) { + throw new AlreadyExistsException("Namespace already exists: " + dataset.getId()); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public Dataset getDataset(DatasetReference datasetReference) { + try { + HttpResponse response = + client + .datasets() + .get(datasetReference.getProjectId(), datasetReference.getDatasetId()) + .executeUnparsed(); + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchNamespaceException( + "Namespace does not exist: " + datasetReference.getDatasetId()); + } + return convertExceptionIfUnsuccessful(response).parseAs(Dataset.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public void deleteDataset(DatasetReference datasetReference) { + try { + HttpResponse response = + client + .datasets() + .delete(datasetReference.getProjectId(), datasetReference.getDatasetId()) + .executeUnparsed(); + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchNamespaceException( + "Namespace does not exist: " + datasetReference.getDatasetId()); + } + convertExceptionIfUnsuccessful(response); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + public Dataset setDatasetParameters( + DatasetReference datasetReference, Map<String, String> parameters) { + Dataset dataset = getDataset(datasetReference); + ExternalCatalogDatasetOptions externalCatalogDatasetOptions = + dataset.getExternalCatalogDatasetOptions() == null + ? new ExternalCatalogDatasetOptions() + : dataset.getExternalCatalogDatasetOptions(); + Map<String, String> finalParameters = + externalCatalogDatasetOptions.getParameters() == null + ? Maps.newHashMap() + : externalCatalogDatasetOptions.getParameters(); + finalParameters.putAll(parameters); + + dataset.setExternalCatalogDatasetOptions( + externalCatalogDatasetOptions.setParameters(finalParameters)); + + return updateDataset(dataset); + } + + @Override + public Dataset removeDatasetParameters( + DatasetReference datasetReference, Set<String> parameters) { + Dataset dataset = getDataset(datasetReference); + ExternalCatalogDatasetOptions externalCatalogDatasetOptions = + dataset.getExternalCatalogDatasetOptions() == null + ? new ExternalCatalogDatasetOptions() + : dataset.getExternalCatalogDatasetOptions(); + Map<String, String> finalParameters = + externalCatalogDatasetOptions.getParameters() == null + ? Maps.newHashMap() + : externalCatalogDatasetOptions.getParameters(); + parameters.forEach(finalParameters::remove); + + dataset.setExternalCatalogDatasetOptions( + externalCatalogDatasetOptions.setParameters(finalParameters)); + + return updateDataset(dataset); + } + + @Override + public List<Datasets> listDatasets(String projectId) { + try { + String nextPageToken = null; + List<Datasets> datasets = Lists.newArrayList(); + do { + HttpResponse pageResponse = + client.datasets().list(projectId).setPageToken(nextPageToken).executeUnparsed(); + DatasetList result = + convertExceptionIfUnsuccessful(pageResponse).parseAs(DatasetList.class); + nextPageToken = result.getNextPageToken(); + if (result.getDatasets() != null) { + datasets.addAll(result.getDatasets()); + } + } while (nextPageToken != null && !nextPageToken.isEmpty()); + return datasets; + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + public Table createTable(Table table) { + // Ensure it is an Iceberg table supported by the BigQuery metastore catalog. + validateTable(table); + // TODO (b/399885863): Ensure table creation is idempotent when handling retries. + Table response = null; + try { + response = + BigQueryRetryHelper.runWithRetries( + new Callable<Table>() { + @Override + public Table call() { + return create(table); + } + }, + bigqueryOptions.getRetrySettings(), + BIGQUERY_EXCEPTION_HANDLER, + bigqueryOptions.getClock(), + DEFAULT_RETRY_CONFIG); + } catch (BigQueryRetryHelper.BigQueryRetryHelperException e) { + handleBigQueryRetryException(e); + } + return response; + } + + @SuppressWarnings("FormatStringAnnotation") + private Table create(Table table) { + try { + HttpResponse response = + client + .tables() + .insert( + Preconditions.checkNotNull(table.getTableReference()).getProjectId(), + Preconditions.checkNotNull(table.getTableReference()).getDatasetId(), + table) + .executeUnparsed(); + return convertExceptionIfUnsuccessful(response).parseAs(Table.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } catch (AlreadyExistsException e) { + throw new AlreadyExistsException("Table already exists", e); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public Table getTable(TableReference tableReference) { + try { + HttpResponse response = + client + .tables() + .get( + tableReference.getProjectId(), + tableReference.getDatasetId(), + tableReference.getTableId()) + .executeUnparsed(); + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchTableException(response.getStatusMessage()); + } + return validateTable(convertExceptionIfUnsuccessful(response).parseAs(Table.class)); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public Table patchTable(TableReference tableReference, Table table) { + // Ensure it is an Iceberg table supported by the BQ metastore catalog. + validateTable(table); + + ExternalCatalogTableOptions newExternalCatalogTableOptions = + new ExternalCatalogTableOptions() + .setStorageDescriptor(table.getExternalCatalogTableOptions().getStorageDescriptor()) + .setConnectionId(table.getExternalCatalogTableOptions().getConnectionId()) + .setParameters(table.getExternalCatalogTableOptions().getParameters()); + Table updatedTable = + new Table() + .setExternalCatalogTableOptions(newExternalCatalogTableOptions) + // Must set the schema as null for using schema auto-detect. + .setSchema(Data.nullOf(TableSchema.class)); + + Table response = null; + try { + response = + BigQueryRetryHelper.runWithRetries( + new Callable<Table>() { + @Override + public Table call() { + return patch(tableReference, updatedTable, table.getEtag()); + } + }, + bigqueryOptions.getRetrySettings(), + BIGQUERY_EXCEPTION_HANDLER, + bigqueryOptions.getClock(), + DEFAULT_RETRY_CONFIG); + } catch (BigQueryRetryHelper.BigQueryRetryHelperException e) { + handleBigQueryRetryException(e); + } + return response; + } + + @SuppressWarnings("FormatStringAnnotation") + private Table patch(TableReference tableReference, Table table, String etag) { + try { + HttpResponse response = + client + .tables() + .patch( + tableReference.getProjectId(), + tableReference.getDatasetId(), + tableReference.getTableId(), + table) + .setRequestHeaders(new HttpHeaders().setIfMatch(etag)) + .executeUnparsed(); + + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + String responseString = response.parseAsString(); + if (responseString.toLowerCase(Locale.ROOT).contains("not found: connection")) { + throw new BadRequestException(responseString); + } + throw new NoSuchTableException(response.getStatusMessage()); + } + return convertExceptionIfUnsuccessful(response).parseAs(Table.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public Table renameTable(TableReference tableToRename, String newTableId) { + Table table = getTable(tableToRename); // Verify table first + Table patch = + new Table() + .setTableReference( + new TableReference() + .setProjectId(table.getTableReference().getProjectId()) + .setDatasetId(table.getTableReference().getDatasetId()) + .setTableId(newTableId)); + + try { + HttpResponse response = + client + .tables() + .patch( + tableToRename.getProjectId(), + tableToRename.getDatasetId(), + tableToRename.getTableId(), + patch) + .setRequestHeaders(new HttpHeaders().setIfMatch(table.getEtag())) + .executeUnparsed(); + + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchTableException(response.getStatusMessage()); + } + return convertExceptionIfUnsuccessful(response).parseAs(Table.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public void deleteTable(TableReference tableReference) { + try { + getTable(tableReference); // Fetching it to validate it is a BigQuery Metastore table first + + HttpResponse response = + client + .tables() + .delete( + tableReference.getProjectId(), + tableReference.getDatasetId(), + tableReference.getTableId()) + .executeUnparsed(); + + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchTableException(response.getStatusMessage()); + } + convertExceptionIfUnsuccessful(response); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public List<Tables> listTables( + DatasetReference datasetReference, boolean filterUnsupportedTables) { + try { + String nextPageToken = null; + Stream<Tables> tablesStream = Stream.empty(); + do { + HttpResponse pageResponse = + client + .tables() + .list(datasetReference.getProjectId(), datasetReference.getDatasetId()) + .setPageToken(nextPageToken) + .executeUnparsed(); + if (pageResponse.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchNamespaceException(pageResponse.getStatusMessage()); + } + TableList result = convertExceptionIfUnsuccessful(pageResponse).parseAs(TableList.class); + nextPageToken = result.getNextPageToken(); + List<Tables> tablesPage = result.getTables(); + Stream<Tables> tablesPageStream = + tablesPage == null ? Stream.empty() : result.getTables().stream(); + tablesStream = Stream.concat(tablesStream, tablesPageStream); + } while (nextPageToken != null && !nextPageToken.isEmpty()); + + // TODO(b/345839927): The server should return more metadata here to distinguish Iceberg + // BQMS tables for us to filter out those results since invoking `getTable` on them would + // correctly raise a `NoSuchIcebergTableException` for being inoperable by this plugin. + if (filterUnsupportedTables) { + tablesStream = + tablesStream + .parallel() + .filter( + table -> { + try { + getTable(table.getTableReference()); + } catch (NoSuchTableException e) { + return false; + } + return true; + }); + } + + return tablesStream.collect(Collectors.toList()); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @SuppressWarnings("FormatStringAnnotation") + private Dataset updateDataset(Dataset dataset) { + try { + HttpResponse response = + client + .datasets() + .update( + Preconditions.checkNotNull(dataset.getDatasetReference()).getProjectId(), + Preconditions.checkNotNull(dataset.getDatasetReference().getDatasetId()), + dataset) + .setRequestHeaders(new HttpHeaders().setIfMatch(dataset.getEtag())) + .executeUnparsed(); + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchNamespaceException(response.getStatusMessage()); + } + return convertExceptionIfUnsuccessful(response).parseAs(Dataset.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + /** + * Returns true when it is a BigQuery Metastore Iceberg table, defined by having the + * ExternalCatalogTableOptions object and a parameter of METADATA_LOCATION_PROP as part of its + * parameters map. + * + * @param table to check + */ + private boolean isValidIcebergTable(Table table) { Review Comment: This method can be static. Same for convertExceptionIfUnsuccessful. ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetaStoreClient.java: ########## @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList.Tables; +import com.google.api.services.bigquery.model.TableReference; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * A client of Google BigQuery Metastore functions over the BigQuery service. Uses the Google + * BigQuery API. + */ +public interface BigQueryMetaStoreClient { + + /** + * Creates and returns a new dataset. + * + * @param dataset the dataset to create + */ + Dataset createDataset(Dataset dataset); Review Comment: Return value of createDataset, setDatasetParameters, removeDatasetParameters are never used. ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryTableOperations.java: ########## @@ -0,0 +1,300 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.services.bigquery.model.ExternalCatalogTableOptions; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableReference; +import java.util.Locale; +import java.util.Map; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hive.common.StatsSetupConst; +import org.apache.iceberg.BaseMetastoreOperations; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.SnapshotSummary; +import org.apache.iceberg.TableMetadata; +import org.apache.iceberg.TableProperties; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.CommitFailedException; +import org.apache.iceberg.exceptions.CommitStateUnknownException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.exceptions.ValidationException; +import org.apache.iceberg.hadoop.ConfigProperties; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Handles BigQuery metastore table operations. */ +public final class BigQueryTableOperations extends BaseMetastoreTableOperations { + + private static final Logger LOG = LoggerFactory.getLogger(BigQueryTableOperations.class); + + public static final String TABLE_PROPERTIES_BQ_CONNECTION = "bq_connection"; + + private final BigQueryMetaStoreClient client; + private final FileIO fileIO; + private final TableReference tableReference; + private final Configuration conf; + + BigQueryTableOperations( + BigQueryMetaStoreClient client, + FileIO fileIO, + String project, + String dataset, + String table, + Configuration conf) { + this.client = client; + this.fileIO = fileIO; + this.tableReference = + new TableReference().setProjectId(project).setDatasetId(dataset).setTableId(table); + this.conf = conf; + } + + // The doRefresh method should provide implementation on how to get the metadata location. + @Override + public void doRefresh() { + // Must default to null. + String metadataLocation = null; + try { + metadataLocation = + getMetadataLocationOrThrow( + client.getTable(this.tableReference).getExternalCatalogTableOptions()); + } catch (NoSuchTableException e) { + if (currentMetadataLocation() != null) { + // Re-throws the exception because the table must exist in this case. + throw e; + } + } + refreshFromMetadataLocation(metadataLocation); + } + + // The doCommit method should provide implementation on how to update with metadata location + // atomically + @Override + public void doCommit(TableMetadata base, TableMetadata metadata) { + String newMetadataLocation = + base == null && metadata.metadataFileLocation() != null + ? metadata.metadataFileLocation() + : writeNewMetadata(metadata, currentVersion() + 1); + BaseMetastoreOperations.CommitStatus commitStatus = + BaseMetastoreOperations.CommitStatus.FAILURE; + try { + if (base == null) { + createTable(newMetadataLocation, metadata); + } else { + updateTable(base.metadataFileLocation(), newMetadataLocation, metadata); + } + commitStatus = BaseMetastoreOperations.CommitStatus.SUCCESS; + } catch (CommitFailedException | CommitStateUnknownException e) { + throw e; + } catch (Throwable e) { + LOG.error("Exception thrown on commit: ", e); + + if (commitStatus == BaseMetastoreOperations.CommitStatus.FAILURE Review Comment: `commitStatus == BaseMetastoreOperations.CommitStatus.FAILURE` is always true in the current logic. ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetaStoreClientImpl.java: ########## @@ -0,0 +1,620 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.http.HttpHeaders; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.HttpResponseException; +import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.client.util.Data; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.BigqueryScopes; +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.ExternalCatalogTableOptions; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList; +import com.google.api.services.bigquery.model.TableList.Tables; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.BaseServiceException; +import com.google.cloud.ExceptionHandler; +import com.google.cloud.bigquery.BigQueryErrorMessages; +import com.google.cloud.bigquery.BigQueryOptions; +import com.google.cloud.bigquery.BigQueryRetryConfig; +import com.google.cloud.bigquery.BigQueryRetryHelper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.BadRequestException; +import org.apache.iceberg.exceptions.ForbiddenException; +import org.apache.iceberg.exceptions.NoSuchIcebergTableException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.exceptions.NotAuthorizedException; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.exceptions.ServiceFailureException; +import org.apache.iceberg.exceptions.ServiceUnavailableException; +import org.apache.iceberg.exceptions.ValidationException; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; + +/** A client of Google Bigquery Metastore functions over the BigQuery service. */ +public final class BigQueryMetaStoreClientImpl implements BigQueryMetaStoreClient { + + public static final ExceptionHandler.Interceptor EXCEPTION_HANDLER_INTERCEPTOR = + new ExceptionHandler.Interceptor() { + + private static final long serialVersionUID = -8429573486870467828L; + + @Override + public RetryResult afterEval(Exception exception, RetryResult retryResult) { + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + + @Override + public RetryResult beforeEval(Exception exception) { + if (exception instanceof BaseServiceException) { + boolean retriable = ((BaseServiceException) exception).isRetryable(); + return retriable + ? ExceptionHandler.Interceptor.RetryResult.RETRY + : ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + }; + + private final Bigquery client; + private final BigQueryOptions bigqueryOptions; + + // Retry config with error messages and regex for rate limit exceeded errors. + private static final BigQueryRetryConfig DEFAULT_RETRY_CONFIG = + BigQueryRetryConfig.newBuilder() + .retryOnMessage(BigQueryErrorMessages.RATE_LIMIT_EXCEEDED_MSG) + .retryOnMessage(BigQueryErrorMessages.JOB_RATE_LIMIT_EXCEEDED_MSG) + .retryOnRegEx(BigQueryErrorMessages.RetryRegExPatterns.RATE_LIMIT_EXCEEDED_REGEX) + .build(); + + public static final ExceptionHandler BIGQUERY_EXCEPTION_HANDLER = + ExceptionHandler.newBuilder() + .abortOn(RuntimeException.class) + .retryOn(java.net.ConnectException.class) // retry on Connection Exception + .retryOn(java.net.UnknownHostException.class) // retry on UnknownHostException + .addInterceptors(EXCEPTION_HANDLER_INTERCEPTOR) + .build(); + + /** Constructs a client of the Google BigQuery service. */ + public BigQueryMetaStoreClientImpl(BigQueryOptions options) + throws IOException, GeneralSecurityException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests + HttpCredentialsAdapter httpCredentialsAdapter = + new HttpCredentialsAdapter( + GoogleCredentials.getApplicationDefault().createScoped(BigqueryScopes.all())); + this.client = + new Bigquery.Builder( + GoogleNetHttpTransport.newTrustedTransport(), + GsonFactory.getDefaultInstance(), + httpRequest -> { + httpCredentialsAdapter.initialize(httpRequest); + // Instead of throwing exceptions, analyze the HttpResponse object and inspect its + // status code. This will allow BigQuery API errors to be converted into Iceberg + // exceptions. + httpRequest.setThrowExceptionOnExecuteError(false); + }) + .setApplicationName("BigQuery Metastore Iceberg Catalog Plugin") + .build(); + this.bigqueryOptions = options; + } + + @Override + public Dataset createDataset(Dataset dataset) { + // TODO (b/399885863): Ensure Dataset creation is idempotent when handling retries. + Dataset response = null; + try { + response = + BigQueryRetryHelper.runWithRetries( + new Callable<Dataset>() { + @Override + public Dataset call() { + return create(dataset); + } + }, + bigqueryOptions.getRetrySettings(), + BIGQUERY_EXCEPTION_HANDLER, + bigqueryOptions.getClock(), + DEFAULT_RETRY_CONFIG); + } catch (BigQueryRetryHelper.BigQueryRetryHelperException e) { + handleBigQueryRetryException(e); + } + return response; + } + + @SuppressWarnings("FormatStringAnnotation") + private Dataset create(Dataset dataset) { + try { + HttpResponse response = + client + .datasets() + .insert(dataset.getDatasetReference().getProjectId(), dataset) + .executeUnparsed(); + return convertExceptionIfUnsuccessful(response).parseAs(Dataset.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } catch (AlreadyExistsException e) { + throw new AlreadyExistsException("Namespace already exists: " + dataset.getId()); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public Dataset getDataset(DatasetReference datasetReference) { + try { + HttpResponse response = + client + .datasets() + .get(datasetReference.getProjectId(), datasetReference.getDatasetId()) + .executeUnparsed(); + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchNamespaceException( + "Namespace does not exist: " + datasetReference.getDatasetId()); + } + return convertExceptionIfUnsuccessful(response).parseAs(Dataset.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public void deleteDataset(DatasetReference datasetReference) { + try { + HttpResponse response = + client + .datasets() + .delete(datasetReference.getProjectId(), datasetReference.getDatasetId()) + .executeUnparsed(); + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchNamespaceException( + "Namespace does not exist: " + datasetReference.getDatasetId()); + } + convertExceptionIfUnsuccessful(response); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + public Dataset setDatasetParameters( + DatasetReference datasetReference, Map<String, String> parameters) { + Dataset dataset = getDataset(datasetReference); + ExternalCatalogDatasetOptions externalCatalogDatasetOptions = + dataset.getExternalCatalogDatasetOptions() == null + ? new ExternalCatalogDatasetOptions() + : dataset.getExternalCatalogDatasetOptions(); + Map<String, String> finalParameters = + externalCatalogDatasetOptions.getParameters() == null + ? Maps.newHashMap() + : externalCatalogDatasetOptions.getParameters(); + finalParameters.putAll(parameters); + + dataset.setExternalCatalogDatasetOptions( + externalCatalogDatasetOptions.setParameters(finalParameters)); + + return updateDataset(dataset); Review Comment: What happens if the dataset is changed between L223-237 concurrently? Same for removeDatasetParameters. ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/FakeBigQueryMetaStoreClient.java: ########## @@ -0,0 +1,228 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList; +import com.google.api.services.bigquery.model.TableReference; +import com.google.cloud.bigquery.BigQueryOptions; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.CommitFailedException; +import org.apache.iceberg.exceptions.NamespaceNotEmptyException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; + +public class FakeBigQueryMetaStoreClient implements BigQueryMetaStoreClient { + private final Map<DatasetReference, Dataset> datasets = Maps.newHashMap(); + private final Map<TableReference, Table> tables = Maps.newHashMap(); + + public FakeBigQueryMetaStoreClient(BigQueryOptions options) + throws IOException, GeneralSecurityException {} + + public Map<DatasetReference, Dataset> datasets() { + return datasets; + } + + public Map<TableReference, Table> tables() { + return tables; + } Review Comment: Unused methods. ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetaStoreClientImpl.java: ########## @@ -0,0 +1,620 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; +import com.google.api.client.http.HttpHeaders; +import com.google.api.client.http.HttpResponse; +import com.google.api.client.http.HttpResponseException; +import com.google.api.client.http.HttpStatusCodes; +import com.google.api.client.json.gson.GsonFactory; +import com.google.api.client.util.Data; +import com.google.api.services.bigquery.Bigquery; +import com.google.api.services.bigquery.BigqueryScopes; +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.ExternalCatalogTableOptions; +import com.google.api.services.bigquery.model.Table; +import com.google.api.services.bigquery.model.TableList; +import com.google.api.services.bigquery.model.TableList.Tables; +import com.google.api.services.bigquery.model.TableReference; +import com.google.api.services.bigquery.model.TableSchema; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.BaseServiceException; +import com.google.cloud.ExceptionHandler; +import com.google.cloud.bigquery.BigQueryErrorMessages; +import com.google.cloud.bigquery.BigQueryOptions; +import com.google.cloud.bigquery.BigQueryRetryConfig; +import com.google.cloud.bigquery.BigQueryRetryHelper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.BadRequestException; +import org.apache.iceberg.exceptions.ForbiddenException; +import org.apache.iceberg.exceptions.NoSuchIcebergTableException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.exceptions.NotAuthorizedException; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.exceptions.ServiceFailureException; +import org.apache.iceberg.exceptions.ServiceUnavailableException; +import org.apache.iceberg.exceptions.ValidationException; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; + +/** A client of Google Bigquery Metastore functions over the BigQuery service. */ +public final class BigQueryMetaStoreClientImpl implements BigQueryMetaStoreClient { + + public static final ExceptionHandler.Interceptor EXCEPTION_HANDLER_INTERCEPTOR = + new ExceptionHandler.Interceptor() { + + private static final long serialVersionUID = -8429573486870467828L; + + @Override + public RetryResult afterEval(Exception exception, RetryResult retryResult) { + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + + @Override + public RetryResult beforeEval(Exception exception) { + if (exception instanceof BaseServiceException) { + boolean retriable = ((BaseServiceException) exception).isRetryable(); + return retriable + ? ExceptionHandler.Interceptor.RetryResult.RETRY + : ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + return ExceptionHandler.Interceptor.RetryResult.CONTINUE_EVALUATION; + } + }; + + private final Bigquery client; + private final BigQueryOptions bigqueryOptions; + + // Retry config with error messages and regex for rate limit exceeded errors. + private static final BigQueryRetryConfig DEFAULT_RETRY_CONFIG = + BigQueryRetryConfig.newBuilder() + .retryOnMessage(BigQueryErrorMessages.RATE_LIMIT_EXCEEDED_MSG) + .retryOnMessage(BigQueryErrorMessages.JOB_RATE_LIMIT_EXCEEDED_MSG) + .retryOnRegEx(BigQueryErrorMessages.RetryRegExPatterns.RATE_LIMIT_EXCEEDED_REGEX) + .build(); + + public static final ExceptionHandler BIGQUERY_EXCEPTION_HANDLER = + ExceptionHandler.newBuilder() + .abortOn(RuntimeException.class) + .retryOn(java.net.ConnectException.class) // retry on Connection Exception + .retryOn(java.net.UnknownHostException.class) // retry on UnknownHostException + .addInterceptors(EXCEPTION_HANDLER_INTERCEPTOR) + .build(); + + /** Constructs a client of the Google BigQuery service. */ + public BigQueryMetaStoreClientImpl(BigQueryOptions options) + throws IOException, GeneralSecurityException { + // Initialize client that will be used to send requests. This client only needs to be created + // once, and can be reused for multiple requests + HttpCredentialsAdapter httpCredentialsAdapter = + new HttpCredentialsAdapter( + GoogleCredentials.getApplicationDefault().createScoped(BigqueryScopes.all())); + this.client = + new Bigquery.Builder( + GoogleNetHttpTransport.newTrustedTransport(), + GsonFactory.getDefaultInstance(), + httpRequest -> { + httpCredentialsAdapter.initialize(httpRequest); + // Instead of throwing exceptions, analyze the HttpResponse object and inspect its + // status code. This will allow BigQuery API errors to be converted into Iceberg + // exceptions. + httpRequest.setThrowExceptionOnExecuteError(false); + }) + .setApplicationName("BigQuery Metastore Iceberg Catalog Plugin") + .build(); + this.bigqueryOptions = options; + } + + @Override + public Dataset createDataset(Dataset dataset) { + // TODO (b/399885863): Ensure Dataset creation is idempotent when handling retries. + Dataset response = null; + try { + response = + BigQueryRetryHelper.runWithRetries( + new Callable<Dataset>() { + @Override + public Dataset call() { + return create(dataset); + } + }, + bigqueryOptions.getRetrySettings(), + BIGQUERY_EXCEPTION_HANDLER, + bigqueryOptions.getClock(), + DEFAULT_RETRY_CONFIG); + } catch (BigQueryRetryHelper.BigQueryRetryHelperException e) { + handleBigQueryRetryException(e); + } + return response; + } + + @SuppressWarnings("FormatStringAnnotation") + private Dataset create(Dataset dataset) { + try { + HttpResponse response = + client + .datasets() + .insert(dataset.getDatasetReference().getProjectId(), dataset) + .executeUnparsed(); + return convertExceptionIfUnsuccessful(response).parseAs(Dataset.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } catch (AlreadyExistsException e) { + throw new AlreadyExistsException("Namespace already exists: " + dataset.getId()); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public Dataset getDataset(DatasetReference datasetReference) { + try { + HttpResponse response = + client + .datasets() + .get(datasetReference.getProjectId(), datasetReference.getDatasetId()) + .executeUnparsed(); + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchNamespaceException( + "Namespace does not exist: " + datasetReference.getDatasetId()); + } + return convertExceptionIfUnsuccessful(response).parseAs(Dataset.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public void deleteDataset(DatasetReference datasetReference) { + try { + HttpResponse response = + client + .datasets() + .delete(datasetReference.getProjectId(), datasetReference.getDatasetId()) + .executeUnparsed(); + if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { + throw new NoSuchNamespaceException( + "Namespace does not exist: " + datasetReference.getDatasetId()); + } + convertExceptionIfUnsuccessful(response); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + public Dataset setDatasetParameters( + DatasetReference datasetReference, Map<String, String> parameters) { + Dataset dataset = getDataset(datasetReference); + ExternalCatalogDatasetOptions externalCatalogDatasetOptions = + dataset.getExternalCatalogDatasetOptions() == null + ? new ExternalCatalogDatasetOptions() + : dataset.getExternalCatalogDatasetOptions(); + Map<String, String> finalParameters = + externalCatalogDatasetOptions.getParameters() == null + ? Maps.newHashMap() + : externalCatalogDatasetOptions.getParameters(); + finalParameters.putAll(parameters); + + dataset.setExternalCatalogDatasetOptions( + externalCatalogDatasetOptions.setParameters(finalParameters)); + + return updateDataset(dataset); + } + + @Override + public Dataset removeDatasetParameters( + DatasetReference datasetReference, Set<String> parameters) { + Dataset dataset = getDataset(datasetReference); + ExternalCatalogDatasetOptions externalCatalogDatasetOptions = + dataset.getExternalCatalogDatasetOptions() == null + ? new ExternalCatalogDatasetOptions() + : dataset.getExternalCatalogDatasetOptions(); + Map<String, String> finalParameters = + externalCatalogDatasetOptions.getParameters() == null + ? Maps.newHashMap() + : externalCatalogDatasetOptions.getParameters(); + parameters.forEach(finalParameters::remove); + + dataset.setExternalCatalogDatasetOptions( + externalCatalogDatasetOptions.setParameters(finalParameters)); + + return updateDataset(dataset); + } + + @Override + public List<Datasets> listDatasets(String projectId) { + try { + String nextPageToken = null; + List<Datasets> datasets = Lists.newArrayList(); + do { + HttpResponse pageResponse = + client.datasets().list(projectId).setPageToken(nextPageToken).executeUnparsed(); + DatasetList result = + convertExceptionIfUnsuccessful(pageResponse).parseAs(DatasetList.class); + nextPageToken = result.getNextPageToken(); + if (result.getDatasets() != null) { + datasets.addAll(result.getDatasets()); + } + } while (nextPageToken != null && !nextPageToken.isEmpty()); + return datasets; + } catch (IOException e) { + throw new RuntimeIOException(e); + } + } + + @Override + public Table createTable(Table table) { + // Ensure it is an Iceberg table supported by the BigQuery metastore catalog. + validateTable(table); + // TODO (b/399885863): Ensure table creation is idempotent when handling retries. + Table response = null; + try { + response = + BigQueryRetryHelper.runWithRetries( + new Callable<Table>() { + @Override + public Table call() { + return create(table); + } + }, + bigqueryOptions.getRetrySettings(), + BIGQUERY_EXCEPTION_HANDLER, + bigqueryOptions.getClock(), + DEFAULT_RETRY_CONFIG); + } catch (BigQueryRetryHelper.BigQueryRetryHelperException e) { + handleBigQueryRetryException(e); + } + return response; + } + + @SuppressWarnings("FormatStringAnnotation") + private Table create(Table table) { + try { + HttpResponse response = + client + .tables() + .insert( + Preconditions.checkNotNull(table.getTableReference()).getProjectId(), + Preconditions.checkNotNull(table.getTableReference()).getDatasetId(), + table) + .executeUnparsed(); + return convertExceptionIfUnsuccessful(response).parseAs(Table.class); + } catch (IOException e) { + throw new RuntimeIOException(e); + } catch (AlreadyExistsException e) { + throw new AlreadyExistsException("Table already exists", e); Review Comment: Can we include the table name in the error message? ########## bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetastoreCatalog.java: ########## @@ -0,0 +1,403 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iceberg.gcp.bigquery; + +import com.google.api.services.bigquery.model.Dataset; +import com.google.api.services.bigquery.model.DatasetList.Datasets; +import com.google.api.services.bigquery.model.DatasetReference; +import com.google.api.services.bigquery.model.ExternalCatalogDatasetOptions; +import com.google.api.services.bigquery.model.TableReference; +import com.google.cloud.ServiceOptions; +import com.google.cloud.bigquery.BigQueryOptions; +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import org.apache.hadoop.conf.Configurable; +import org.apache.hadoop.conf.Configuration; +import org.apache.iceberg.BaseMetastoreCatalog; +import org.apache.iceberg.CatalogProperties; +import org.apache.iceberg.CatalogUtil; +import org.apache.iceberg.TableMetadata; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.catalog.Namespace; +import org.apache.iceberg.catalog.SupportsNamespaces; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.NoSuchNamespaceException; +import org.apache.iceberg.exceptions.NoSuchTableException; +import org.apache.iceberg.exceptions.ServiceFailureException; +import org.apache.iceberg.exceptions.ValidationException; +import org.apache.iceberg.io.FileIO; +import org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.base.Strings; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; +import org.apache.iceberg.util.LocationUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Iceberg Bigquery Metastore Catalog implementation. */ +public final class BigQueryMetastoreCatalog extends BaseMetastoreCatalog + implements SupportsNamespaces, Configurable { + + // User provided properties. + public static final String PROPERTIES_KEY_GCP_PROJECT = "gcp-project"; + public static final String PROPERTIES_KEY_GCP_LOCATION = "gcp-location"; + public static final String PROPERTIES_KEY_FILTER_UNSUPPORTED_TABLES = "filter-unsupported-tables"; + public static final String PROPERTIES_KEY_TESTING_ENABLED = "testing-enabled"; + + public static final String HIVE_METASTORE_WAREHOUSE_DIR = "hive.metastore.warehouse.dir"; + + private static final Logger LOG = LoggerFactory.getLogger(BigQueryMetastoreCatalog.class); + + private static final String DEFAULT_GCP_LOCATION = "us"; + + private String catalogPluginName; + private Map<String, String> catalogProperties; + private FileIO fileIO; + private Configuration conf; + private String projectId; + private String location; + private BigQueryMetaStoreClient client; + private boolean filterUnsupportedTables; + + // Must have a no-arg constructor to be dynamically loaded + // initialize(String name, Map<String, String> properties) will be called to complete + // initialization + public BigQueryMetastoreCatalog() {} + + @Override + public void initialize(String inputName, Map<String, String> properties) { + if (!properties.containsKey(PROPERTIES_KEY_GCP_PROJECT)) { + throw new ValidationException("GCP project must be specified"); + } + projectId = properties.get(PROPERTIES_KEY_GCP_PROJECT); + location = properties.getOrDefault(PROPERTIES_KEY_GCP_LOCATION, DEFAULT_GCP_LOCATION); + boolean testingEnabled = + Boolean.parseBoolean(properties.getOrDefault(PROPERTIES_KEY_TESTING_ENABLED, "false")); + + BigQueryOptions options = + BigQueryOptions.newBuilder() + .setProjectId(projectId) + .setLocation(location) + .setRetrySettings(ServiceOptions.getDefaultRetrySettings()) + .build(); + + try { + if (testingEnabled) { + client = new FakeBigQueryMetaStoreClient(options); + + } else { + client = new BigQueryMetaStoreClientImpl(options); + } + } catch (IOException e) { + throw new ServiceFailureException(e, "Creating BigQuery client failed"); + } catch (GeneralSecurityException e) { + throw new ValidationException(e, "Creating BigQuery client failed due to a security issue"); + } + initialize(inputName, properties, projectId, location, client); + } + + @VisibleForTesting + void initialize( + String inputName, + Map<String, String> properties, + String initialProjectId, + String initialLocation, + BigQueryMetaStoreClient bigQueryMetaStoreClient) { + this.catalogPluginName = inputName; + this.catalogProperties = ImmutableMap.copyOf(properties); + this.projectId = initialProjectId; + this.location = initialLocation; + this.client = + Preconditions.checkNotNull(bigQueryMetaStoreClient, "BigQuery client can not be null"); + + if (this.conf == null) { + LOG.warn("No configuration was set, using the default environment Configuration"); + this.conf = new Configuration(); + } + + LOG.info("Using BigQuery Metastore Iceberg Catalog: {}", inputName); + + if (properties.containsKey(CatalogProperties.WAREHOUSE_LOCATION)) { + // Iceberg always removes trailing slash to avoid paths like "<folder>//data" in file systems + // like s3. + this.conf.set( + HIVE_METASTORE_WAREHOUSE_DIR, + LocationUtil.stripTrailingSlash(properties.get(CatalogProperties.WAREHOUSE_LOCATION))); + } + + String fileIoImpl = + properties.getOrDefault( + CatalogProperties.FILE_IO_IMPL, "org.apache.iceberg.hadoop.HadoopFileIO"); + this.fileIO = CatalogUtil.loadFileIO(fileIoImpl, properties, conf); + + this.filterUnsupportedTables = + Boolean.parseBoolean( + properties.getOrDefault(PROPERTIES_KEY_FILTER_UNSUPPORTED_TABLES, "false")); + } + + @Override + protected TableOperations newTableOps(TableIdentifier identifier) { + return new BigQueryTableOperations( + client, + fileIO, + projectId, + // Sometimes extensions have the namespace contain the table name too, so we are forced to + // allow invalid namespace and just take the first part here like other catalog + // implementations do. + identifier.namespace().level(0), + identifier.name(), + conf); + } + + @Override + protected String defaultWarehouseLocation(TableIdentifier identifier) { + String locationUri = null; + DatasetReference datasetReference = toDatasetReference(identifier.namespace()); + Dataset dataset = client.getDataset(datasetReference); + if (dataset != null && dataset.getExternalCatalogDatasetOptions() != null) { + locationUri = dataset.getExternalCatalogDatasetOptions().getDefaultStorageLocationUri(); + } + return String.format( + "%s/%s", + Strings.isNullOrEmpty(locationUri) ? datasetReference.getDatasetId() : locationUri, Review Comment: Does `locationUri` never end with `/`? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For additional commands, e-mail: issues-h...@iceberg.apache.org