talatuyarer commented on code in PR #12808:
URL: https://github.com/apache/iceberg/pull/12808#discussion_r2074077072


##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetastoreCatalog.java:
##########
@@ -0,0 +1,366 @@
+/*
+ * 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.io.UncheckedIOException;
+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.NoSuchNamespaceException;
+import org.apache.iceberg.exceptions.NoSuchTableException;
+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 class BigQueryMetastoreCatalog extends BaseMetastoreCatalog
+    implements SupportsNamespaces, Configurable {
+
+  // User provided properties.
+  public static final String PROJECT_ID = "gcp.bigquery.project-id";
+  public static final String GCP_LOCATION = "gcp.bigquery.location";
+  public static final String LIST_ALL_TABLES = "gcp.bigquery.list-all-tables";
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(BigQueryMetastoreCatalog.class);
+
+  private static final String DEFAULT_GCP_LOCATION = "us";
+
+  private String catalogName;
+  private Map<String, String> catalogProperties;
+  private FileIO fileIO;
+  private Configuration conf;
+  private String projectId;
+  private String projectLocation;
+  private BigQueryMetastoreClient client;
+  private boolean listAllTables;
+  private String warehouseLocation;
+
+  public BigQueryMetastoreCatalog() {}
+
+  @Override
+  public void initialize(String name, Map<String, String> properties) {
+    Preconditions.checkArgument(
+        properties.containsKey(PROJECT_ID),
+        "Invalid GCP project: %s must be specified",
+        PROJECT_ID);
+
+    this.projectId = properties.get(PROJECT_ID);
+    this.projectLocation = properties.getOrDefault(GCP_LOCATION, 
DEFAULT_GCP_LOCATION);
+
+    BigQueryOptions options =
+        BigQueryOptions.newBuilder()
+            .setProjectId(projectId)
+            .setLocation(projectLocation)
+            .setRetrySettings(ServiceOptions.getDefaultRetrySettings())
+            .build();
+
+    try {
+      client = new BigQueryMetastoreClientImpl(options);
+    } catch (IOException e) {
+      throw new UncheckedIOException("Creating BigQuery client failed", e);
+    } catch (GeneralSecurityException e) {
+      throw new RuntimeException("Creating BigQuery client failed due to a 
security issue", e);
+    }
+
+    initialize(name, properties, projectId, projectLocation, client);
+  }
+
+  @VisibleForTesting
+  void initialize(
+      String name,
+      Map<String, String> properties,
+      String initialProjectId,
+      String initialLocation,
+      BigQueryMetastoreClient bigQueryMetaStoreClient) {
+    Preconditions.checkArgument(bigQueryMetaStoreClient != null, "Invalid 
BigQuery client: null");
+    this.catalogName = name;
+    this.catalogProperties = ImmutableMap.copyOf(properties);
+    this.projectId = initialProjectId;
+    this.projectLocation = initialLocation;
+    this.client = bigQueryMetaStoreClient;
+
+    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: {}", name);
+
+    if (properties.containsKey(CatalogProperties.WAREHOUSE_LOCATION)) {
+      this.warehouseLocation =
+          
LocationUtil.stripTrailingSlash(properties.get(CatalogProperties.WAREHOUSE_LOCATION));
+    }
+
+    this.fileIO =
+        CatalogUtil.loadFileIO(
+            properties.getOrDefault(
+                CatalogProperties.FILE_IO_IMPL, 
"org.apache.iceberg.io.ResolvingFileIO"),
+            properties,
+            conf);
+
+    this.listAllTables = 
Boolean.parseBoolean(properties.getOrDefault(LIST_ALL_TABLES, "true"));
+  }
+
+  @Override
+  protected TableOperations newTableOps(TableIdentifier identifier) {
+    return new BigQueryTableOperations(client, fileIO, 
toTableReference(identifier), conf);
+  }
+
+  @Override
+  protected String defaultWarehouseLocation(TableIdentifier identifier) {
+    String locationUri = null;
+    DatasetReference datasetReference = 
toDatasetReference(identifier.namespace());
+    Dataset dataset = client.load(datasetReference);
+    if (dataset != null && dataset.getExternalCatalogDatasetOptions() != null) 
{
+      locationUri = 
dataset.getExternalCatalogDatasetOptions().getDefaultStorageLocationUri();
+    }
+
+    return String.format(
+        "%s/%s",
+        Strings.isNullOrEmpty(locationUri)
+            ? createDefaultStorageLocationUri(datasetReference.getDatasetId())
+            : LocationUtil.stripTrailingSlash(locationUri),
+        identifier.name());
+  }
+
+  @Override
+  public List<TableIdentifier> listTables(Namespace namespace) {
+    validateNamespace(namespace);
+
+    return client.list(toDatasetReference(namespace), listAllTables).stream()
+        .map(
+            table -> TableIdentifier.of(namespace.level(0), 
table.getTableReference().getTableId()))
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  @Override
+  public boolean dropTable(TableIdentifier identifier, boolean purge) {
+    try {
+      TableOperations ops = newTableOps(identifier);
+      TableMetadata lastMetadata = ops.current();
+
+      client.delete(toTableReference(identifier));
+
+      if (purge && lastMetadata != null) {
+        CatalogUtil.dropTableData(ops.io(), lastMetadata);
+      }
+    } catch (NoSuchTableException e) {
+      return false;
+    }
+
+    return true;
+  }
+
+  @Override
+  public void renameTable(TableIdentifier from, TableIdentifier to) {
+    // TODO: Enable once supported by BigQuery API.
+    throw new UnsupportedOperationException("Table rename operation is 
unsupported.");
+  }
+
+  @Override
+  public void createNamespace(Namespace namespace, Map<String, String> 
metadata) {
+    Dataset builder = new Dataset();
+    DatasetReference datasetReference = toDatasetReference(namespace);
+    builder.setLocation(this.projectLocation);
+    builder.setDatasetReference(datasetReference);
+    builder.setExternalCatalogDatasetOptions(
+        BigQueryMetastoreUtils.createExternalCatalogDatasetOptions(
+            createDefaultStorageLocationUri(datasetReference.getDatasetId()), 
metadata));
+
+    client.create(builder);
+  }
+
+  @Override
+  public List<Namespace> listNamespaces() {
+    try {
+      return listNamespaces(Namespace.empty());
+    } catch (NoSuchNamespaceException e) {
+      return ImmutableList.of();
+    }
+  }
+
+  /**
+   * Since this catalog only supports one-level namespaces, it always returns 
an empty list unless
+   * passed an empty namespace to list all namespaces within the catalog.
+   */
+  @Override
+  public List<Namespace> listNamespaces(Namespace namespace) {
+    List<Datasets> allDatasets = client.list(projectId);
+
+    ImmutableList<Namespace> namespaces =
+        
allDatasets.stream().map(this::toNamespace).collect(ImmutableList.toImmutableList());
+    if (namespaces.isEmpty()) {
+      throw new NoSuchNamespaceException("Namespace does not exist: %s", 
namespace);
+    }
+
+    return namespaces;
+  }
+
+  @Override
+  public boolean dropNamespace(Namespace namespace) {
+    try {
+      client.delete(toDatasetReference(namespace));
+      // We don't delete the data folder for safety, which aligns with Hive 
Metastore's default
+      // behavior.
+      // We can support database or catalog level config controlling file 
deletion in the future.
+      return true;
+    } catch (NoSuchNamespaceException e) {
+      return false;
+    }
+  }
+
+  @Override
+  public boolean setProperties(Namespace namespace, Map<String, String> 
properties) {
+    Dataset dataset = client.load(toDatasetReference(namespace));
+
+    ExternalCatalogDatasetOptions existingOptions = 
dataset.getExternalCatalogDatasetOptions();
+    Map<String, String> existingParameters =
+        existingOptions != null ? existingOptions.getParameters() : null;
+
+    Map<String, String> newParameters = Maps.newHashMap();
+    if (existingParameters != null) {
+      newParameters.putAll(existingParameters);
+    }
+
+    newParameters.putAll(properties);
+
+    if (Objects.equals(existingParameters, newParameters)) {
+      // No change in parameters detected
+      return false;
+    }
+
+    client.setParameters(toDatasetReference(namespace), properties);
+    return true;
+  }
+
+  @Override
+  public boolean removeProperties(Namespace namespace, Set<String> properties) 
{
+    client.removeParameters(toDatasetReference(namespace), properties);
+    return true;
+  }
+
+  @Override
+  public Map<String, String> loadNamespaceMetadata(Namespace namespace) {
+    try {
+      return toMetadata(client.load(toDatasetReference(namespace)));
+    } catch (IllegalArgumentException e) {

Review Comment:
   if namespace name is not correct we can reach IAE via validateNamespace 
function



##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetastoreCatalog.java:
##########
@@ -0,0 +1,366 @@
+/*
+ * 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.io.UncheckedIOException;
+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.NoSuchNamespaceException;
+import org.apache.iceberg.exceptions.NoSuchTableException;
+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 class BigQueryMetastoreCatalog extends BaseMetastoreCatalog
+    implements SupportsNamespaces, Configurable {
+
+  // User provided properties.
+  public static final String PROJECT_ID = "gcp.bigquery.project-id";
+  public static final String GCP_LOCATION = "gcp.bigquery.location";
+  public static final String LIST_ALL_TABLES = "gcp.bigquery.list-all-tables";
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(BigQueryMetastoreCatalog.class);
+
+  private static final String DEFAULT_GCP_LOCATION = "us";
+
+  private String catalogName;
+  private Map<String, String> catalogProperties;
+  private FileIO fileIO;
+  private Configuration conf;
+  private String projectId;
+  private String projectLocation;
+  private BigQueryMetastoreClient client;
+  private boolean listAllTables;
+  private String warehouseLocation;
+
+  public BigQueryMetastoreCatalog() {}
+
+  @Override
+  public void initialize(String name, Map<String, String> properties) {
+    Preconditions.checkArgument(
+        properties.containsKey(PROJECT_ID),
+        "Invalid GCP project: %s must be specified",
+        PROJECT_ID);
+
+    this.projectId = properties.get(PROJECT_ID);
+    this.projectLocation = properties.getOrDefault(GCP_LOCATION, 
DEFAULT_GCP_LOCATION);
+
+    BigQueryOptions options =
+        BigQueryOptions.newBuilder()
+            .setProjectId(projectId)
+            .setLocation(projectLocation)
+            .setRetrySettings(ServiceOptions.getDefaultRetrySettings())
+            .build();
+
+    try {
+      client = new BigQueryMetastoreClientImpl(options);
+    } catch (IOException e) {
+      throw new UncheckedIOException("Creating BigQuery client failed", e);
+    } catch (GeneralSecurityException e) {
+      throw new RuntimeException("Creating BigQuery client failed due to a 
security issue", e);
+    }
+
+    initialize(name, properties, projectId, projectLocation, client);
+  }
+
+  @VisibleForTesting
+  void initialize(
+      String name,
+      Map<String, String> properties,
+      String initialProjectId,
+      String initialLocation,
+      BigQueryMetastoreClient bigQueryMetaStoreClient) {
+    Preconditions.checkArgument(bigQueryMetaStoreClient != null, "Invalid 
BigQuery client: null");
+    this.catalogName = name;
+    this.catalogProperties = ImmutableMap.copyOf(properties);
+    this.projectId = initialProjectId;
+    this.projectLocation = initialLocation;
+    this.client = bigQueryMetaStoreClient;
+
+    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: {}", name);
+
+    if (properties.containsKey(CatalogProperties.WAREHOUSE_LOCATION)) {
+      this.warehouseLocation =
+          
LocationUtil.stripTrailingSlash(properties.get(CatalogProperties.WAREHOUSE_LOCATION));
+    }
+
+    this.fileIO =
+        CatalogUtil.loadFileIO(
+            properties.getOrDefault(
+                CatalogProperties.FILE_IO_IMPL, 
"org.apache.iceberg.io.ResolvingFileIO"),
+            properties,
+            conf);
+
+    this.listAllTables = 
Boolean.parseBoolean(properties.getOrDefault(LIST_ALL_TABLES, "true"));
+  }
+
+  @Override
+  protected TableOperations newTableOps(TableIdentifier identifier) {
+    return new BigQueryTableOperations(client, fileIO, 
toTableReference(identifier), conf);
+  }
+
+  @Override
+  protected String defaultWarehouseLocation(TableIdentifier identifier) {
+    String locationUri = null;
+    DatasetReference datasetReference = 
toDatasetReference(identifier.namespace());
+    Dataset dataset = client.load(datasetReference);
+    if (dataset != null && dataset.getExternalCatalogDatasetOptions() != null) 
{
+      locationUri = 
dataset.getExternalCatalogDatasetOptions().getDefaultStorageLocationUri();
+    }
+
+    return String.format(
+        "%s/%s",
+        Strings.isNullOrEmpty(locationUri)
+            ? createDefaultStorageLocationUri(datasetReference.getDatasetId())
+            : LocationUtil.stripTrailingSlash(locationUri),
+        identifier.name());
+  }
+
+  @Override
+  public List<TableIdentifier> listTables(Namespace namespace) {
+    validateNamespace(namespace);
+
+    return client.list(toDatasetReference(namespace), listAllTables).stream()
+        .map(
+            table -> TableIdentifier.of(namespace.level(0), 
table.getTableReference().getTableId()))
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  @Override
+  public boolean dropTable(TableIdentifier identifier, boolean purge) {
+    try {
+      TableOperations ops = newTableOps(identifier);
+      TableMetadata lastMetadata = ops.current();
+
+      client.delete(toTableReference(identifier));
+
+      if (purge && lastMetadata != null) {
+        CatalogUtil.dropTableData(ops.io(), lastMetadata);
+      }
+    } catch (NoSuchTableException e) {
+      return false;
+    }
+
+    return true;
+  }
+
+  @Override
+  public void renameTable(TableIdentifier from, TableIdentifier to) {
+    // TODO: Enable once supported by BigQuery API.
+    throw new UnsupportedOperationException("Table rename operation is 
unsupported.");
+  }
+
+  @Override
+  public void createNamespace(Namespace namespace, Map<String, String> 
metadata) {
+    Dataset builder = new Dataset();
+    DatasetReference datasetReference = toDatasetReference(namespace);
+    builder.setLocation(this.projectLocation);
+    builder.setDatasetReference(datasetReference);
+    builder.setExternalCatalogDatasetOptions(
+        BigQueryMetastoreUtils.createExternalCatalogDatasetOptions(
+            createDefaultStorageLocationUri(datasetReference.getDatasetId()), 
metadata));
+
+    client.create(builder);
+  }
+
+  @Override
+  public List<Namespace> listNamespaces() {
+    try {
+      return listNamespaces(Namespace.empty());
+    } catch (NoSuchNamespaceException e) {
+      return ImmutableList.of();
+    }
+  }
+
+  /**
+   * Since this catalog only supports one-level namespaces, it always returns 
an empty list unless
+   * passed an empty namespace to list all namespaces within the catalog.
+   */
+  @Override
+  public List<Namespace> listNamespaces(Namespace namespace) {
+    List<Datasets> allDatasets = client.list(projectId);
+
+    ImmutableList<Namespace> namespaces =
+        
allDatasets.stream().map(this::toNamespace).collect(ImmutableList.toImmutableList());
+    if (namespaces.isEmpty()) {
+      throw new NoSuchNamespaceException("Namespace does not exist: %s", 
namespace);
+    }
+
+    return namespaces;
+  }
+
+  @Override
+  public boolean dropNamespace(Namespace namespace) {
+    try {
+      client.delete(toDatasetReference(namespace));
+      // We don't delete the data folder for safety, which aligns with Hive 
Metastore's default
+      // behavior.
+      // We can support database or catalog level config controlling file 
deletion in the future.
+      return true;
+    } catch (NoSuchNamespaceException e) {
+      return false;
+    }
+  }
+
+  @Override
+  public boolean setProperties(Namespace namespace, Map<String, String> 
properties) {
+    Dataset dataset = client.load(toDatasetReference(namespace));
+
+    ExternalCatalogDatasetOptions existingOptions = 
dataset.getExternalCatalogDatasetOptions();
+    Map<String, String> existingParameters =
+        existingOptions != null ? existingOptions.getParameters() : null;
+
+    Map<String, String> newParameters = Maps.newHashMap();
+    if (existingParameters != null) {
+      newParameters.putAll(existingParameters);
+    }
+
+    newParameters.putAll(properties);
+
+    if (Objects.equals(existingParameters, newParameters)) {
+      // No change in parameters detected
+      return false;
+    }
+
+    client.setParameters(toDatasetReference(namespace), properties);
+    return true;
+  }
+
+  @Override
+  public boolean removeProperties(Namespace namespace, Set<String> properties) 
{
+    client.removeParameters(toDatasetReference(namespace), properties);
+    return true;
+  }
+
+  @Override
+  public Map<String, String> loadNamespaceMetadata(Namespace namespace) {
+    try {
+      return toMetadata(client.load(toDatasetReference(namespace)));
+    } catch (IllegalArgumentException e) {
+      throw new NoSuchNamespaceException("%s", e.getMessage());
+    }
+  }
+
+  @Override
+  public String name() {
+    return catalogName;
+  }
+
+  @Override
+  protected Map<String, String> properties() {
+    return catalogProperties == null ? ImmutableMap.of() : catalogProperties;
+  }
+
+  @Override
+  public void setConf(Configuration conf) {
+    this.conf = new Configuration(conf);
+  }
+
+  @Override
+  public Configuration getConf() {
+    return this.conf;
+  }
+
+  private String createDefaultStorageLocationUri(String dbId) {
+    Preconditions.checkArgument(
+        this.warehouseLocation != null,

Review Comment:
   Done



##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryTableOperations.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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);
+
+  private 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,
+      TableReference tableReference,
+      Configuration conf) {
+    this.client = client;
+    this.fileIO = fileIO;
+    this.tableReference = tableReference;
+    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 =
+          loadMetadataLocationOrThrow(
+              
client.load(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 (e instanceof AlreadyExistsException) {
+        throw e;
+      }
+      commitStatus =
+          BaseMetastoreOperations.CommitStatus.valueOf(
+              checkCommitStatus(newMetadataLocation, metadata).name());
+      if (commitStatus == BaseMetastoreOperations.CommitStatus.FAILURE) {
+        throw new CommitFailedException(e, "Failed to commit");
+      }
+      if (commitStatus == BaseMetastoreOperations.CommitStatus.UNKNOWN) {
+        throw new CommitStateUnknownException(e);
+      }
+    } finally {
+      try {
+        if (commitStatus == BaseMetastoreOperations.CommitStatus.FAILURE) {
+          LOG.warn("Failed to commit updates to table {}", tableName());
+          io().deleteFile(newMetadataLocation);
+        }
+      } catch (RuntimeException e) {
+        LOG.error(
+            "Failed to cleanup metadata file at {} for table {}",
+            newMetadataLocation,
+            tableName(),
+            e);
+      }
+    }
+  }
+
+  @Override
+  public String tableName() {
+    return String.format("%s.%s", tableReference.getDatasetId(), 
tableReference.getTableId());
+  }
+
+  @Override
+  public FileIO io() {
+    return fileIO;
+  }
+
+  private void createTable(String newMetadataLocation, TableMetadata metadata) 
{
+    LOG.debug("Creating a new Iceberg table: {}", tableName());
+    Table tableBuilder = makeNewTable(metadata, newMetadataLocation);
+    tableBuilder.setTableReference(this.tableReference);
+    addConnectionIfProvided(tableBuilder, metadata.properties());
+
+    client.create(tableBuilder);

Review Comment:
   BigQuery client will throw exception if namespace does not exists. We dont 
need to check in here.



##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetastoreCatalog.java:
##########
@@ -0,0 +1,366 @@
+/*
+ * 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.io.UncheckedIOException;
+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.NoSuchNamespaceException;
+import org.apache.iceberg.exceptions.NoSuchTableException;
+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 class BigQueryMetastoreCatalog extends BaseMetastoreCatalog
+    implements SupportsNamespaces, Configurable {
+
+  // User provided properties.
+  public static final String PROJECT_ID = "gcp.bigquery.project-id";
+  public static final String GCP_LOCATION = "gcp.bigquery.location";
+  public static final String LIST_ALL_TABLES = "gcp.bigquery.list-all-tables";
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(BigQueryMetastoreCatalog.class);
+
+  private static final String DEFAULT_GCP_LOCATION = "us";
+
+  private String catalogName;
+  private Map<String, String> catalogProperties;
+  private FileIO fileIO;
+  private Configuration conf;
+  private String projectId;
+  private String projectLocation;
+  private BigQueryMetastoreClient client;
+  private boolean listAllTables;
+  private String warehouseLocation;
+
+  public BigQueryMetastoreCatalog() {}
+
+  @Override
+  public void initialize(String name, Map<String, String> properties) {
+    Preconditions.checkArgument(
+        properties.containsKey(PROJECT_ID),
+        "Invalid GCP project: %s must be specified",
+        PROJECT_ID);
+
+    this.projectId = properties.get(PROJECT_ID);
+    this.projectLocation = properties.getOrDefault(GCP_LOCATION, 
DEFAULT_GCP_LOCATION);
+
+    BigQueryOptions options =
+        BigQueryOptions.newBuilder()
+            .setProjectId(projectId)
+            .setLocation(projectLocation)
+            .setRetrySettings(ServiceOptions.getDefaultRetrySettings())
+            .build();
+
+    try {
+      client = new BigQueryMetastoreClientImpl(options);
+    } catch (IOException e) {
+      throw new UncheckedIOException("Creating BigQuery client failed", e);
+    } catch (GeneralSecurityException e) {
+      throw new RuntimeException("Creating BigQuery client failed due to a 
security issue", e);
+    }
+
+    initialize(name, properties, projectId, projectLocation, client);
+  }
+
+  @VisibleForTesting
+  void initialize(
+      String name,
+      Map<String, String> properties,
+      String initialProjectId,
+      String initialLocation,
+      BigQueryMetastoreClient bigQueryMetaStoreClient) {
+    Preconditions.checkArgument(bigQueryMetaStoreClient != null, "Invalid 
BigQuery client: null");
+    this.catalogName = name;
+    this.catalogProperties = ImmutableMap.copyOf(properties);
+    this.projectId = initialProjectId;
+    this.projectLocation = initialLocation;
+    this.client = bigQueryMetaStoreClient;
+
+    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: {}", name);
+
+    if (properties.containsKey(CatalogProperties.WAREHOUSE_LOCATION)) {
+      this.warehouseLocation =
+          
LocationUtil.stripTrailingSlash(properties.get(CatalogProperties.WAREHOUSE_LOCATION));
+    }
+
+    this.fileIO =
+        CatalogUtil.loadFileIO(
+            properties.getOrDefault(
+                CatalogProperties.FILE_IO_IMPL, 
"org.apache.iceberg.io.ResolvingFileIO"),
+            properties,
+            conf);
+
+    this.listAllTables = 
Boolean.parseBoolean(properties.getOrDefault(LIST_ALL_TABLES, "true"));
+  }
+
+  @Override
+  protected TableOperations newTableOps(TableIdentifier identifier) {
+    return new BigQueryTableOperations(client, fileIO, 
toTableReference(identifier), conf);
+  }
+
+  @Override
+  protected String defaultWarehouseLocation(TableIdentifier identifier) {
+    String locationUri = null;
+    DatasetReference datasetReference = 
toDatasetReference(identifier.namespace());
+    Dataset dataset = client.load(datasetReference);
+    if (dataset != null && dataset.getExternalCatalogDatasetOptions() != null) 
{
+      locationUri = 
dataset.getExternalCatalogDatasetOptions().getDefaultStorageLocationUri();
+    }
+
+    return String.format(
+        "%s/%s",
+        Strings.isNullOrEmpty(locationUri)
+            ? createDefaultStorageLocationUri(datasetReference.getDatasetId())
+            : LocationUtil.stripTrailingSlash(locationUri),
+        identifier.name());
+  }
+
+  @Override
+  public List<TableIdentifier> listTables(Namespace namespace) {
+    validateNamespace(namespace);
+
+    return client.list(toDatasetReference(namespace), listAllTables).stream()
+        .map(
+            table -> TableIdentifier.of(namespace.level(0), 
table.getTableReference().getTableId()))
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  @Override
+  public boolean dropTable(TableIdentifier identifier, boolean purge) {
+    try {
+      TableOperations ops = newTableOps(identifier);
+      TableMetadata lastMetadata = ops.current();
+
+      client.delete(toTableReference(identifier));
+
+      if (purge && lastMetadata != null) {
+        CatalogUtil.dropTableData(ops.io(), lastMetadata);
+      }
+    } catch (NoSuchTableException e) {
+      return false;
+    }
+
+    return true;
+  }
+
+  @Override
+  public void renameTable(TableIdentifier from, TableIdentifier to) {
+    // TODO: Enable once supported by BigQuery API.
+    throw new UnsupportedOperationException("Table rename operation is 
unsupported.");
+  }
+
+  @Override
+  public void createNamespace(Namespace namespace, Map<String, String> 
metadata) {
+    Dataset builder = new Dataset();
+    DatasetReference datasetReference = toDatasetReference(namespace);
+    builder.setLocation(this.projectLocation);
+    builder.setDatasetReference(datasetReference);
+    builder.setExternalCatalogDatasetOptions(
+        BigQueryMetastoreUtils.createExternalCatalogDatasetOptions(
+            createDefaultStorageLocationUri(datasetReference.getDatasetId()), 
metadata));
+
+    client.create(builder);
+  }
+
+  @Override
+  public List<Namespace> listNamespaces() {
+    try {
+      return listNamespaces(Namespace.empty());
+    } catch (NoSuchNamespaceException e) {
+      return ImmutableList.of();
+    }
+  }
+
+  /**
+   * Since this catalog only supports one-level namespaces, it always returns 
an empty list unless
+   * passed an empty namespace to list all namespaces within the catalog.
+   */
+  @Override
+  public List<Namespace> listNamespaces(Namespace namespace) {
+    List<Datasets> allDatasets = client.list(projectId);
+
+    ImmutableList<Namespace> namespaces =
+        
allDatasets.stream().map(this::toNamespace).collect(ImmutableList.toImmutableList());
+    if (namespaces.isEmpty()) {
+      throw new NoSuchNamespaceException("Namespace does not exist: %s", 
namespace);
+    }
+
+    return namespaces;
+  }
+
+  @Override
+  public boolean dropNamespace(Namespace namespace) {
+    try {
+      client.delete(toDatasetReference(namespace));

Review Comment:
   it is passing this test: 
https://github.com/apache/iceberg/blob/7f3f450bbddf55bb383ff1409d6d0ca4557c9ffc/core/src/test/java/org/apache/iceberg/catalog/CatalogTests.java#L392



##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetastoreUtils.java:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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.ExternalCatalogDatasetOptions;
+import com.google.api.services.bigquery.model.ExternalCatalogTableOptions;
+import com.google.api.services.bigquery.model.SerDeInfo;
+import com.google.api.services.bigquery.model.StorageDescriptor;
+import java.util.Map;
+
+/** Shared utilities for BigQuery Metastore specific functions and constants. 
*/
+public final class BigQueryMetastoreUtils {

Review Comment:
   Done



##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryTableOperations.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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);
+
+  private 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,
+      TableReference tableReference,
+      Configuration conf) {
+    this.client = client;
+    this.fileIO = fileIO;
+    this.tableReference = tableReference;
+    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 =
+          loadMetadataLocationOrThrow(
+              
client.load(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 (e instanceof AlreadyExistsException) {
+        throw e;
+      }
+      commitStatus =
+          BaseMetastoreOperations.CommitStatus.valueOf(
+              checkCommitStatus(newMetadataLocation, metadata).name());
+      if (commitStatus == BaseMetastoreOperations.CommitStatus.FAILURE) {
+        throw new CommitFailedException(e, "Failed to commit");
+      }
+      if (commitStatus == BaseMetastoreOperations.CommitStatus.UNKNOWN) {
+        throw new CommitStateUnknownException(e);
+      }
+    } finally {
+      try {
+        if (commitStatus == BaseMetastoreOperations.CommitStatus.FAILURE) {
+          LOG.warn("Failed to commit updates to table {}", tableName());
+          io().deleteFile(newMetadataLocation);
+        }
+      } catch (RuntimeException e) {
+        LOG.error(
+            "Failed to cleanup metadata file at {} for table {}",
+            newMetadataLocation,
+            tableName(),
+            e);
+      }
+    }
+  }
+
+  @Override
+  public String tableName() {
+    return String.format("%s.%s", tableReference.getDatasetId(), 
tableReference.getTableId());
+  }
+
+  @Override
+  public FileIO io() {
+    return fileIO;
+  }
+
+  private void createTable(String newMetadataLocation, TableMetadata metadata) 
{
+    LOG.debug("Creating a new Iceberg table: {}", tableName());
+    Table tableBuilder = makeNewTable(metadata, newMetadataLocation);
+    tableBuilder.setTableReference(this.tableReference);
+    addConnectionIfProvided(tableBuilder, metadata.properties());
+
+    client.create(tableBuilder);
+  }
+
+  private void addConnectionIfProvided(Table tableBuilder, Map<String, String> 
metadataProperties) {
+    if (metadataProperties.containsKey(TABLE_PROPERTIES_BQ_CONNECTION)) {
+      tableBuilder
+          .getExternalCatalogTableOptions()
+          
.setConnectionId(metadataProperties.get(TABLE_PROPERTIES_BQ_CONNECTION));
+    }
+  }
+
+  /** Update table properties with concurrent update detection using etag. */
+  private void updateTable(
+      String oldMetadataLocation, String newMetadataLocation, TableMetadata 
metadata) {
+    Table table = client.load(this.tableReference);

Review Comment:
   Done



##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryTableOperations.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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);
+
+  private 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,
+      TableReference tableReference,
+      Configuration conf) {
+    this.client = client;
+    this.fileIO = fileIO;
+    this.tableReference = tableReference;
+    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 =
+          loadMetadataLocationOrThrow(
+              
client.load(this.tableReference).getExternalCatalogTableOptions());

Review Comment:
   Done



##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryTableOperations.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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);
+
+  private 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,
+      TableReference tableReference,
+      Configuration conf) {
+    this.client = client;
+    this.fileIO = fileIO;
+    this.tableReference = tableReference;
+    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 =
+          loadMetadataLocationOrThrow(
+              
client.load(this.tableReference).getExternalCatalogTableOptions());
+    } catch (NoSuchTableException e) {
+      if (currentMetadataLocation() != null) {
+        // Re-throws the exception because the table must exist in this case.

Review Comment:
   We have a metadata location. If we receive NSTE, Someone should delete Table 
from BigQuery or stomething else. Table must exists if someone not modified 



##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryTableOperations.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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);
+
+  private 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,
+      TableReference tableReference,
+      Configuration conf) {
+    this.client = client;
+    this.fileIO = fileIO;
+    this.tableReference = tableReference;
+    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 =
+          loadMetadataLocationOrThrow(
+              
client.load(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 (e instanceof AlreadyExistsException) {
+        throw e;
+      }
+      commitStatus =
+          BaseMetastoreOperations.CommitStatus.valueOf(
+              checkCommitStatus(newMetadataLocation, metadata).name());
+      if (commitStatus == BaseMetastoreOperations.CommitStatus.FAILURE) {
+        throw new CommitFailedException(e, "Failed to commit");
+      }
+      if (commitStatus == BaseMetastoreOperations.CommitStatus.UNKNOWN) {
+        throw new CommitStateUnknownException(e);
+      }
+    } finally {
+      try {
+        if (commitStatus == BaseMetastoreOperations.CommitStatus.FAILURE) {
+          LOG.warn("Failed to commit updates to table {}", tableName());
+          io().deleteFile(newMetadataLocation);
+        }
+      } catch (RuntimeException e) {
+        LOG.error(
+            "Failed to cleanup metadata file at {} for table {}",
+            newMetadataLocation,
+            tableName(),
+            e);
+      }
+    }
+  }
+
+  @Override
+  public String tableName() {
+    return String.format("%s.%s", tableReference.getDatasetId(), 
tableReference.getTableId());
+  }
+
+  @Override
+  public FileIO io() {
+    return fileIO;
+  }
+
+  private void createTable(String newMetadataLocation, TableMetadata metadata) 
{
+    LOG.debug("Creating a new Iceberg table: {}", tableName());
+    Table tableBuilder = makeNewTable(metadata, newMetadataLocation);
+    tableBuilder.setTableReference(this.tableReference);

Review Comment:
   Done



##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetastoreCatalog.java:
##########
@@ -0,0 +1,366 @@
+/*
+ * 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.io.UncheckedIOException;
+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.NoSuchNamespaceException;
+import org.apache.iceberg.exceptions.NoSuchTableException;
+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 class BigQueryMetastoreCatalog extends BaseMetastoreCatalog
+    implements SupportsNamespaces, Configurable {
+
+  // User provided properties.
+  public static final String PROJECT_ID = "gcp.bigquery.project-id";
+  public static final String GCP_LOCATION = "gcp.bigquery.location";
+  public static final String LIST_ALL_TABLES = "gcp.bigquery.list-all-tables";
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(BigQueryMetastoreCatalog.class);
+
+  private static final String DEFAULT_GCP_LOCATION = "us";
+
+  private String catalogName;
+  private Map<String, String> catalogProperties;
+  private FileIO fileIO;
+  private Configuration conf;
+  private String projectId;
+  private String projectLocation;
+  private BigQueryMetastoreClient client;
+  private boolean listAllTables;
+  private String warehouseLocation;
+
+  public BigQueryMetastoreCatalog() {}
+
+  @Override
+  public void initialize(String name, Map<String, String> properties) {
+    Preconditions.checkArgument(
+        properties.containsKey(PROJECT_ID),
+        "Invalid GCP project: %s must be specified",
+        PROJECT_ID);
+
+    this.projectId = properties.get(PROJECT_ID);
+    this.projectLocation = properties.getOrDefault(GCP_LOCATION, 
DEFAULT_GCP_LOCATION);
+
+    BigQueryOptions options =
+        BigQueryOptions.newBuilder()
+            .setProjectId(projectId)
+            .setLocation(projectLocation)
+            .setRetrySettings(ServiceOptions.getDefaultRetrySettings())
+            .build();
+
+    try {
+      client = new BigQueryMetastoreClientImpl(options);
+    } catch (IOException e) {
+      throw new UncheckedIOException("Creating BigQuery client failed", e);
+    } catch (GeneralSecurityException e) {
+      throw new RuntimeException("Creating BigQuery client failed due to a 
security issue", e);
+    }
+
+    initialize(name, properties, projectId, projectLocation, client);
+  }
+
+  @VisibleForTesting
+  void initialize(
+      String name,
+      Map<String, String> properties,
+      String initialProjectId,
+      String initialLocation,
+      BigQueryMetastoreClient bigQueryMetaStoreClient) {
+    Preconditions.checkArgument(bigQueryMetaStoreClient != null, "Invalid 
BigQuery client: null");
+    this.catalogName = name;
+    this.catalogProperties = ImmutableMap.copyOf(properties);
+    this.projectId = initialProjectId;
+    this.projectLocation = initialLocation;
+    this.client = bigQueryMetaStoreClient;
+
+    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: {}", name);
+
+    if (properties.containsKey(CatalogProperties.WAREHOUSE_LOCATION)) {
+      this.warehouseLocation =
+          
LocationUtil.stripTrailingSlash(properties.get(CatalogProperties.WAREHOUSE_LOCATION));
+    }
+
+    this.fileIO =
+        CatalogUtil.loadFileIO(
+            properties.getOrDefault(
+                CatalogProperties.FILE_IO_IMPL, 
"org.apache.iceberg.io.ResolvingFileIO"),
+            properties,
+            conf);
+
+    this.listAllTables = 
Boolean.parseBoolean(properties.getOrDefault(LIST_ALL_TABLES, "true"));
+  }
+
+  @Override
+  protected TableOperations newTableOps(TableIdentifier identifier) {
+    return new BigQueryTableOperations(client, fileIO, 
toTableReference(identifier), conf);
+  }
+
+  @Override
+  protected String defaultWarehouseLocation(TableIdentifier identifier) {
+    String locationUri = null;
+    DatasetReference datasetReference = 
toDatasetReference(identifier.namespace());
+    Dataset dataset = client.load(datasetReference);
+    if (dataset != null && dataset.getExternalCatalogDatasetOptions() != null) 
{
+      locationUri = 
dataset.getExternalCatalogDatasetOptions().getDefaultStorageLocationUri();
+    }
+
+    return String.format(
+        "%s/%s",
+        Strings.isNullOrEmpty(locationUri)
+            ? createDefaultStorageLocationUri(datasetReference.getDatasetId())
+            : LocationUtil.stripTrailingSlash(locationUri),
+        identifier.name());
+  }
+
+  @Override
+  public List<TableIdentifier> listTables(Namespace namespace) {
+    validateNamespace(namespace);
+
+    return client.list(toDatasetReference(namespace), listAllTables).stream()
+        .map(
+            table -> TableIdentifier.of(namespace.level(0), 
table.getTableReference().getTableId()))
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  @Override
+  public boolean dropTable(TableIdentifier identifier, boolean purge) {
+    try {
+      TableOperations ops = newTableOps(identifier);
+      TableMetadata lastMetadata = ops.current();
+
+      client.delete(toTableReference(identifier));
+
+      if (purge && lastMetadata != null) {
+        CatalogUtil.dropTableData(ops.io(), lastMetadata);
+      }
+    } catch (NoSuchTableException e) {
+      return false;
+    }
+
+    return true;
+  }
+
+  @Override
+  public void renameTable(TableIdentifier from, TableIdentifier to) {
+    // TODO: Enable once supported by BigQuery API.
+    throw new UnsupportedOperationException("Table rename operation is 
unsupported.");
+  }
+
+  @Override
+  public void createNamespace(Namespace namespace, Map<String, String> 
metadata) {
+    Dataset builder = new Dataset();
+    DatasetReference datasetReference = toDatasetReference(namespace);
+    builder.setLocation(this.projectLocation);
+    builder.setDatasetReference(datasetReference);
+    builder.setExternalCatalogDatasetOptions(
+        BigQueryMetastoreUtils.createExternalCatalogDatasetOptions(
+            createDefaultStorageLocationUri(datasetReference.getDatasetId()), 
metadata));
+
+    client.create(builder);
+  }
+
+  @Override
+  public List<Namespace> listNamespaces() {
+    try {
+      return listNamespaces(Namespace.empty());
+    } catch (NoSuchNamespaceException e) {
+      return ImmutableList.of();
+    }
+  }
+
+  /**
+   * Since this catalog only supports one-level namespaces, it always returns 
an empty list unless
+   * passed an empty namespace to list all namespaces within the catalog.
+   */
+  @Override
+  public List<Namespace> listNamespaces(Namespace namespace) {
+    List<Datasets> allDatasets = client.list(projectId);
+
+    ImmutableList<Namespace> namespaces =
+        
allDatasets.stream().map(this::toNamespace).collect(ImmutableList.toImmutableList());
+    if (namespaces.isEmpty()) {
+      throw new NoSuchNamespaceException("Namespace does not exist: %s", 
namespace);
+    }
+
+    return namespaces;
+  }
+
+  @Override
+  public boolean dropNamespace(Namespace namespace) {
+    try {
+      client.delete(toDatasetReference(namespace));
+      // We don't delete the data folder for safety, which aligns with Hive 
Metastore's default
+      // behavior.
+      // We can support database or catalog level config controlling file 
deletion in the future.
+      return true;
+    } catch (NoSuchNamespaceException e) {
+      return false;
+    }
+  }
+
+  @Override
+  public boolean setProperties(Namespace namespace, Map<String, String> 
properties) {
+    Dataset dataset = client.load(toDatasetReference(namespace));
+
+    ExternalCatalogDatasetOptions existingOptions = 
dataset.getExternalCatalogDatasetOptions();
+    Map<String, String> existingParameters =
+        existingOptions != null ? existingOptions.getParameters() : null;
+
+    Map<String, String> newParameters = Maps.newHashMap();
+    if (existingParameters != null) {
+      newParameters.putAll(existingParameters);
+    }
+
+    newParameters.putAll(properties);
+
+    if (Objects.equals(existingParameters, newParameters)) {
+      // No change in parameters detected
+      return false;
+    }
+
+    client.setParameters(toDatasetReference(namespace), properties);
+    return true;
+  }
+
+  @Override
+  public boolean removeProperties(Namespace namespace, Set<String> properties) 
{
+    client.removeParameters(toDatasetReference(namespace), properties);
+    return true;
+  }
+
+  @Override
+  public Map<String, String> loadNamespaceMetadata(Namespace namespace) {
+    try {
+      return toMetadata(client.load(toDatasetReference(namespace)));
+    } catch (IllegalArgumentException e) {
+      throw new NoSuchNamespaceException("%s", e.getMessage());
+    }
+  }
+
+  @Override
+  public String name() {
+    return catalogName;
+  }
+
+  @Override
+  protected Map<String, String> properties() {
+    return catalogProperties == null ? ImmutableMap.of() : catalogProperties;
+  }
+
+  @Override
+  public void setConf(Configuration conf) {
+    this.conf = new Configuration(conf);
+  }
+
+  @Override
+  public Configuration getConf() {
+    return this.conf;

Review Comment:
   Done



##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryTableOperations.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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 {

Review Comment:
   Done



##########
bigquery/src/main/java/org/apache/iceberg/gcp/bigquery/BigQueryMetastoreCatalog.java:
##########
@@ -0,0 +1,366 @@
+/*
+ * 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.io.UncheckedIOException;
+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.NoSuchNamespaceException;
+import org.apache.iceberg.exceptions.NoSuchTableException;
+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 class BigQueryMetastoreCatalog extends BaseMetastoreCatalog
+    implements SupportsNamespaces, Configurable {
+
+  // User provided properties.
+  public static final String PROJECT_ID = "gcp.bigquery.project-id";
+  public static final String GCP_LOCATION = "gcp.bigquery.location";
+  public static final String LIST_ALL_TABLES = "gcp.bigquery.list-all-tables";
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(BigQueryMetastoreCatalog.class);
+
+  private static final String DEFAULT_GCP_LOCATION = "us";
+
+  private String catalogName;
+  private Map<String, String> catalogProperties;
+  private FileIO fileIO;
+  private Configuration conf;
+  private String projectId;
+  private String projectLocation;
+  private BigQueryMetastoreClient client;
+  private boolean listAllTables;
+  private String warehouseLocation;
+
+  public BigQueryMetastoreCatalog() {}
+
+  @Override
+  public void initialize(String name, Map<String, String> properties) {
+    Preconditions.checkArgument(
+        properties.containsKey(PROJECT_ID),
+        "Invalid GCP project: %s must be specified",
+        PROJECT_ID);
+
+    this.projectId = properties.get(PROJECT_ID);
+    this.projectLocation = properties.getOrDefault(GCP_LOCATION, 
DEFAULT_GCP_LOCATION);
+
+    BigQueryOptions options =
+        BigQueryOptions.newBuilder()
+            .setProjectId(projectId)
+            .setLocation(projectLocation)
+            .setRetrySettings(ServiceOptions.getDefaultRetrySettings())
+            .build();
+
+    try {
+      client = new BigQueryMetastoreClientImpl(options);
+    } catch (IOException e) {
+      throw new UncheckedIOException("Creating BigQuery client failed", e);
+    } catch (GeneralSecurityException e) {
+      throw new RuntimeException("Creating BigQuery client failed due to a 
security issue", e);
+    }
+
+    initialize(name, properties, projectId, projectLocation, client);
+  }
+
+  @VisibleForTesting
+  void initialize(
+      String name,
+      Map<String, String> properties,
+      String initialProjectId,
+      String initialLocation,
+      BigQueryMetastoreClient bigQueryMetaStoreClient) {
+    Preconditions.checkArgument(bigQueryMetaStoreClient != null, "Invalid 
BigQuery client: null");
+    this.catalogName = name;
+    this.catalogProperties = ImmutableMap.copyOf(properties);
+    this.projectId = initialProjectId;
+    this.projectLocation = initialLocation;
+    this.client = bigQueryMetaStoreClient;
+
+    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: {}", name);
+
+    if (properties.containsKey(CatalogProperties.WAREHOUSE_LOCATION)) {
+      this.warehouseLocation =
+          
LocationUtil.stripTrailingSlash(properties.get(CatalogProperties.WAREHOUSE_LOCATION));
+    }
+
+    this.fileIO =
+        CatalogUtil.loadFileIO(
+            properties.getOrDefault(
+                CatalogProperties.FILE_IO_IMPL, 
"org.apache.iceberg.io.ResolvingFileIO"),
+            properties,
+            conf);
+
+    this.listAllTables = 
Boolean.parseBoolean(properties.getOrDefault(LIST_ALL_TABLES, "true"));
+  }
+
+  @Override
+  protected TableOperations newTableOps(TableIdentifier identifier) {
+    return new BigQueryTableOperations(client, fileIO, 
toTableReference(identifier), conf);
+  }
+
+  @Override
+  protected String defaultWarehouseLocation(TableIdentifier identifier) {
+    String locationUri = null;
+    DatasetReference datasetReference = 
toDatasetReference(identifier.namespace());
+    Dataset dataset = client.load(datasetReference);
+    if (dataset != null && dataset.getExternalCatalogDatasetOptions() != null) 
{
+      locationUri = 
dataset.getExternalCatalogDatasetOptions().getDefaultStorageLocationUri();
+    }
+
+    return String.format(
+        "%s/%s",
+        Strings.isNullOrEmpty(locationUri)
+            ? createDefaultStorageLocationUri(datasetReference.getDatasetId())
+            : LocationUtil.stripTrailingSlash(locationUri),
+        identifier.name());
+  }
+
+  @Override
+  public List<TableIdentifier> listTables(Namespace namespace) {
+    validateNamespace(namespace);
+
+    return client.list(toDatasetReference(namespace), listAllTables).stream()
+        .map(
+            table -> TableIdentifier.of(namespace.level(0), 
table.getTableReference().getTableId()))
+        .collect(ImmutableList.toImmutableList());
+  }
+
+  @Override
+  public boolean dropTable(TableIdentifier identifier, boolean purge) {
+    try {
+      TableOperations ops = newTableOps(identifier);
+      TableMetadata lastMetadata = ops.current();
+
+      client.delete(toTableReference(identifier));
+
+      if (purge && lastMetadata != null) {
+        CatalogUtil.dropTableData(ops.io(), lastMetadata);
+      }
+    } catch (NoSuchTableException e) {
+      return false;
+    }
+
+    return true;
+  }
+
+  @Override
+  public void renameTable(TableIdentifier from, TableIdentifier to) {
+    // TODO: Enable once supported by BigQuery API.
+    throw new UnsupportedOperationException("Table rename operation is 
unsupported.");
+  }
+
+  @Override
+  public void createNamespace(Namespace namespace, Map<String, String> 
metadata) {
+    Dataset builder = new Dataset();
+    DatasetReference datasetReference = toDatasetReference(namespace);
+    builder.setLocation(this.projectLocation);
+    builder.setDatasetReference(datasetReference);
+    builder.setExternalCatalogDatasetOptions(
+        BigQueryMetastoreUtils.createExternalCatalogDatasetOptions(
+            createDefaultStorageLocationUri(datasetReference.getDatasetId()), 
metadata));
+
+    client.create(builder);
+  }
+
+  @Override
+  public List<Namespace> listNamespaces() {
+    try {
+      return listNamespaces(Namespace.empty());
+    } catch (NoSuchNamespaceException e) {
+      return ImmutableList.of();
+    }
+  }
+
+  /**
+   * Since this catalog only supports one-level namespaces, it always returns 
an empty list unless
+   * passed an empty namespace to list all namespaces within the catalog.
+   */
+  @Override
+  public List<Namespace> listNamespaces(Namespace namespace) {
+    List<Datasets> allDatasets = client.list(projectId);
+
+    ImmutableList<Namespace> namespaces =
+        
allDatasets.stream().map(this::toNamespace).collect(ImmutableList.toImmutableList());
+    if (namespaces.isEmpty()) {
+      throw new NoSuchNamespaceException("Namespace does not exist: %s", 
namespace);
+    }
+
+    return namespaces;
+  }
+
+  @Override
+  public boolean dropNamespace(Namespace namespace) {
+    try {
+      client.delete(toDatasetReference(namespace));
+      // We don't delete the data folder for safety, which aligns with Hive 
Metastore's default
+      // behavior.
+      // We can support database or catalog level config controlling file 
deletion in the future.
+      return true;
+    } catch (NoSuchNamespaceException e) {
+      return false;
+    }
+  }
+
+  @Override
+  public boolean setProperties(Namespace namespace, Map<String, String> 
properties) {
+    Dataset dataset = client.load(toDatasetReference(namespace));
+
+    ExternalCatalogDatasetOptions existingOptions = 
dataset.getExternalCatalogDatasetOptions();
+    Map<String, String> existingParameters =
+        existingOptions != null ? existingOptions.getParameters() : null;
+
+    Map<String, String> newParameters = Maps.newHashMap();
+    if (existingParameters != null) {
+      newParameters.putAll(existingParameters);
+    }
+
+    newParameters.putAll(properties);
+
+    if (Objects.equals(existingParameters, newParameters)) {
+      // No change in parameters detected
+      return false;
+    }
+
+    client.setParameters(toDatasetReference(namespace), properties);
+    return true;
+  }
+
+  @Override
+  public boolean removeProperties(Namespace namespace, Set<String> properties) 
{
+    client.removeParameters(toDatasetReference(namespace), properties);
+    return true;
+  }
+
+  @Override
+  public Map<String, String> loadNamespaceMetadata(Namespace namespace) {
+    try {
+      return toMetadata(client.load(toDatasetReference(namespace)));
+    } catch (IllegalArgumentException e) {
+      throw new NoSuchNamespaceException("%s", e.getMessage());
+    }
+  }
+
+  @Override
+  public String name() {
+    return catalogName;
+  }
+
+  @Override
+  protected Map<String, String> properties() {
+    return catalogProperties == null ? ImmutableMap.of() : catalogProperties;
+  }
+
+  @Override
+  public void setConf(Configuration conf) {
+    this.conf = new Configuration(conf);
+  }
+
+  @Override
+  public Configuration getConf() {
+    return this.conf;
+  }
+
+  private String createDefaultStorageLocationUri(String dbId) {
+    Preconditions.checkArgument(
+        this.warehouseLocation != null,
+        String.format(
+            "Invalid data warehouse location: %s not set", 
CatalogProperties.WAREHOUSE_LOCATION));
+    return String.format("%s/%s.db", 
LocationUtil.stripTrailingSlash(warehouseLocation), dbId);
+  }
+
+  private Namespace toNamespace(Datasets dataset) {
+    return Namespace.of(dataset.getDatasetReference().getDatasetId());
+  }
+
+  private DatasetReference toDatasetReference(Namespace namespace) {
+    validateNamespace(namespace);
+    return new 
DatasetReference().setProjectId(projectId).setDatasetId(namespace.level(0));
+  }
+
+  private TableReference toTableReference(TableIdentifier tableIdentifier) {
+    DatasetReference datasetReference = 
toDatasetReference(tableIdentifier.namespace());
+    return new TableReference()
+        .setProjectId(datasetReference.getProjectId())
+        .setDatasetId(datasetReference.getDatasetId())
+        .setTableId(tableIdentifier.name());
+  }
+
+  private Map<String, String> toMetadata(Dataset dataset) {
+    ExternalCatalogDatasetOptions options = 
dataset.getExternalCatalogDatasetOptions();
+    Map<String, String> metadata = Maps.newHashMap();
+    if (options != null) {
+      if (options.getParameters() != null) {
+        metadata.putAll(options.getParameters());
+      }
+
+      if (!Strings.isNullOrEmpty(options.getDefaultStorageLocationUri())) {
+        metadata.put("location", options.getDefaultStorageLocationUri());
+      }
+    }
+
+    return metadata;
+  }
+
+  private void validateNamespace(Namespace namespace) {
+    Preconditions.checkArgument(

Review Comment:
   Those check happens in BigQuery Client. We dont need to check that in here. 



-- 
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

Reply via email to