ajantha-bhat commented on code in PR #8907: URL: https://github.com/apache/iceberg/pull/8907#discussion_r1377100203
########## hive-metastore/src/main/java/org/apache/iceberg/hive/HiveCatalog.java: ########## @@ -264,6 +251,146 @@ public void renameTable(TableIdentifier from, TableIdentifier originalTo) { } } + @Override + public boolean viewExists(TableIdentifier identifier) { + return HiveCatalogUtil.isTableWithTypeExists(clients, identifier, TableType.VIRTUAL_VIEW); + } + + @Override + public boolean dropView(TableIdentifier identifier) { + if (!isValidIdentifier(identifier)) { + return false; + } + try { + String database = identifier.namespace().level(0); + String viewName = identifier.name(); + Table table = clients.run(client -> client.getTable(database, viewName)); + HiveCatalogUtil.validateTableIsIcebergView(table, fullTableName(name, identifier)); + clients.run( + client -> { + client.dropTable(database, viewName); + return null; + }); + LOG.info("Dropped View: {}", identifier); + return true; + + } catch (NoSuchViewException | NoSuchObjectException e) { + LOG.info("Skipping drop, View does not exist: {}", identifier, e); + return false; + } catch (TException e) { + throw new RuntimeException("Failed to drop " + identifier, e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted in call to dropView", e); + } + } + + @Override + public List<TableIdentifier> listViews(Namespace namespace) { + try { + return listContents(namespace, TableType.VIRTUAL_VIEW.name(), icebergPredicate()); + } catch (UnknownDBException e) { + throw new NoSuchNamespaceException("Namespace does not exist: %s", namespace); + + } catch (TException e) { + throw new RuntimeException("Failed to list all views under namespace " + namespace, e); + + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted in call to listViews", e); + } + } + + private List<TableIdentifier> listContents( + Namespace namespace, String tableType, Predicate<Table> tablePredicate) + throws TException, InterruptedException { + Preconditions.checkArgument( + isValidateNamespace(namespace), "Missing database in namespace: %s", namespace); + String database = namespace.level(0); + List<String> tableNames = + StringUtils.isNotEmpty(tableType) + ? clients.run(client -> client.getTables(database, "*", TableType.valueOf(tableType))) + : clients.run(client -> client.getAllTables(database)); + List<Table> tableObjects = + clients.run(client -> client.getTableObjectsByName(database, tableNames)); + List<TableIdentifier> tableIdentifiers = + tableObjects.stream() + .filter(tablePredicate) + .map(table -> TableIdentifier.of(namespace, table.getTableName())) + .collect(Collectors.toList()); + + LOG.debug( + "Listing of namespace: {} for table type {} resulted in the following: {}", + namespace, + tableType, + tableIdentifiers); + return tableIdentifiers; + } + + private Predicate<Table> icebergPredicate() { + return table -> + table.getParameters() != null + && BaseMetastoreTableOperations.ICEBERG_TABLE_TYPE_VALUE.equalsIgnoreCase( + table.getParameters().get(BaseMetastoreTableOperations.TABLE_TYPE_PROP)); + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public void renameView(TableIdentifier from, TableIdentifier originalTo) { + + if (!isValidIdentifier(from)) { + throw new NoSuchViewException("Invalid identifier: %s", from); + } + + if (!namespaceExists(originalTo.namespace())) { + throw new NoSuchNamespaceException( + "Cannot rename %s to %s. Namespace does not exist: %s", + from, originalTo, originalTo.namespace()); + } + + TableIdentifier to = removeCatalogName(originalTo); Review Comment: catalog name should be removed for `from` also? ########## hive-metastore/src/main/java/org/apache/iceberg/hive/HiveCatalogUtil.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.hive; + +import java.util.List; +import org.apache.hadoop.hive.metastore.IMetaStoreClient; +import org.apache.hadoop.hive.metastore.TableType; +import org.apache.hadoop.hive.metastore.api.Table; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.ClientPool; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.NoSuchIcebergTableException; +import org.apache.iceberg.exceptions.NoSuchIcebergViewException; +import org.apache.thrift.TException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** A utility class to validate Hive Iceberg Table and Views. */ +final class HiveCatalogUtil { + + private static final Logger LOG = LoggerFactory.getLogger(HiveCatalogUtil.class); + + // the max size is based on HMS backend database. For Hive versions below 2.3, the max table + // parameter size is 4000 + // characters, see https://issues.apache.org/jira/browse/HIVE-12274 + // set to 0 to not expose Iceberg metadata in HMS Table properties. + static final String HIVE_TABLE_PROPERTY_MAX_SIZE = "iceberg.hive.table-property-max-size"; + static final long HIVE_TABLE_PROPERTY_MAX_SIZE_DEFAULT = 32672; + + private HiveCatalogUtil() { + // empty constructor for utility class + } + + static boolean isTableWithTypeExists( + ClientPool<IMetaStoreClient, TException> clients, + TableIdentifier identifier, + TableType tableType) { + String database = identifier.namespace().level(0); + String tableName = identifier.name(); + try { + List<String> tables = clients.run(client -> client.getTables(database, tableName, tableType)); + return !tables.isEmpty(); + } catch (TException e) { + throw new RuntimeException( + "Failed to check table existence " + database + "." + tableName, e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted in call to listTables", e); + } + } + + static void validateTableIsIcebergView(Table table, String fullName) { + String tableType = table.getParameters().get(BaseMetastoreTableOperations.TABLE_TYPE_PROP); + NoSuchIcebergViewException.check( + table.getTableType().equalsIgnoreCase(TableType.VIRTUAL_VIEW.name()) + && tableType != null + && tableType.equalsIgnoreCase(BaseMetastoreTableOperations.ICEBERG_TABLE_TYPE_VALUE), + "Not an iceberg view: %s (type=%s) (tableType=%s)", + fullName, + tableType, + table.getTableType()); + } + + static void validateTableIsIceberg(Table table, String fullName) { + if (table.getTableType().equalsIgnoreCase(TableType.VIRTUAL_VIEW.name())) { Review Comment: check in line 82 to 85 looks odd for this function as it is not checking it as Iceberg. Should be separate method maybe or present in caller. ########## hive-metastore/src/main/java/org/apache/iceberg/hive/HiveViewOperations.java: ########## @@ -0,0 +1,346 @@ +/* + * 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.hive; + +import java.util.Collections; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hive.common.StatsSetupConst; +import org.apache.hadoop.hive.metastore.IMetaStoreClient; +import org.apache.hadoop.hive.metastore.TableType; +import org.apache.hadoop.hive.metastore.api.InvalidObjectException; +import org.apache.hadoop.hive.metastore.api.NoSuchObjectException; +import org.apache.hadoop.hive.metastore.api.SerDeInfo; +import org.apache.hadoop.hive.metastore.api.StorageDescriptor; +import org.apache.hadoop.hive.metastore.api.Table; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.ClientPool; +import org.apache.iceberg.SchemaParser; +import org.apache.iceberg.TableProperties; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.CommitFailedException; +import org.apache.iceberg.exceptions.CommitStateUnknownException; +import org.apache.iceberg.exceptions.NoSuchViewException; +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.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; +import org.apache.iceberg.view.BaseViewOperations; +import org.apache.iceberg.view.ViewMetadata; +import org.apache.thrift.TException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Hive implementation of Iceberg ViewOperations. */ +final class HiveViewOperations extends BaseViewOperations { + private static final Logger LOG = LoggerFactory.getLogger(HiveViewOperations.class); + + private final String fullName; + private final String database; + private final String tableName; + private final Configuration conf; + private final FileIO fileIO; + private final ClientPool<IMetaStoreClient, TException> metaClients; + private final long maxHiveTablePropertySize; + private final TableIdentifier identifier; + + HiveViewOperations( + Configuration conf, + ClientPool<IMetaStoreClient, TException> metaClients, + FileIO fileIO, + String catalogName, + TableIdentifier tableIdentifier) { + this.identifier = tableIdentifier; + String dbName = tableIdentifier.namespace().level(0); + this.conf = conf; + this.metaClients = metaClients; + this.fileIO = fileIO; + this.fullName = catalogName + "." + dbName + "." + tableIdentifier.name(); + this.database = dbName; + this.tableName = tableIdentifier.name(); + this.maxHiveTablePropertySize = + conf.getLong( + HiveCatalogUtil.HIVE_TABLE_PROPERTY_MAX_SIZE, + HiveCatalogUtil.HIVE_TABLE_PROPERTY_MAX_SIZE_DEFAULT); + } + + @Override + public ViewMetadata current() { + if (HiveCatalogUtil.isTableWithTypeExists(metaClients, identifier, TableType.EXTERNAL_TABLE)) { + throw new AlreadyExistsException( + "Table with same name already exists: %s.%s", database, tableName); + } + return super.current(); + } + + @Override + public void doRefresh() { + String metadataLocation = null; + try { + Table table = metaClients.run(client -> client.getTable(database, tableName)); + HiveCatalogUtil.validateTableIsIcebergView(table, fullName); + metadataLocation = + table.getParameters().get(BaseMetastoreTableOperations.METADATA_LOCATION_PROP); + } catch (NoSuchObjectException e) { + if (currentMetadataLocation() != null) { + throw new NoSuchViewException("View does not exist: %s.%s", database, tableName); + } + } catch (TException e) { + String errMsg = + String.format("Failed to get view info from metastore %s.%s", database, tableName); + throw new RuntimeException(errMsg, e); + + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted during refresh", e); + } + refreshFromMetadataLocation(metadataLocation); + } + + @SuppressWarnings("checkstyle:CyclomaticComplexity") + @Override + public void doCommit(ViewMetadata base, ViewMetadata metadata) { + boolean newTable = base == null; + String newMetadataLocation = writeNewMetadataIfRequired(metadata); + boolean keepHiveStats = conf.getBoolean(ConfigProperties.KEEP_HIVE_STATS, false); + + boolean updateHiveTable = false; + + try { + + Table tbl = loadHmsTable(); + + if (tbl != null) { + // If we try to create the view but the metadata location is already set, then we had a + // concurrent commit + if (newTable + && tbl.getParameters().get(BaseMetastoreTableOperations.METADATA_LOCATION_PROP) + != null) { + throw new AlreadyExistsException("View already exists: %s.%s", database, tableName); Review Comment: could it be concurrently created `table` also? ########## hive-metastore/src/main/java/org/apache/iceberg/hive/HiveCatalog.java: ########## @@ -264,6 +251,146 @@ public void renameTable(TableIdentifier from, TableIdentifier originalTo) { } } + @Override + public boolean viewExists(TableIdentifier identifier) { + return HiveCatalogUtil.isTableWithTypeExists(clients, identifier, TableType.VIRTUAL_VIEW); + } + + @Override + public boolean dropView(TableIdentifier identifier) { + if (!isValidIdentifier(identifier)) { + return false; + } + try { + String database = identifier.namespace().level(0); + String viewName = identifier.name(); + Table table = clients.run(client -> client.getTable(database, viewName)); + HiveCatalogUtil.validateTableIsIcebergView(table, fullTableName(name, identifier)); + clients.run( + client -> { + client.dropTable(database, viewName); + return null; + }); + LOG.info("Dropped View: {}", identifier); + return true; + + } catch (NoSuchViewException | NoSuchObjectException e) { + LOG.info("Skipping drop, View does not exist: {}", identifier, e); + return false; + } catch (TException e) { + throw new RuntimeException("Failed to drop " + identifier, e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted in call to dropView", e); + } + } + + @Override + public List<TableIdentifier> listViews(Namespace namespace) { + try { + return listContents(namespace, TableType.VIRTUAL_VIEW.name(), icebergPredicate()); + } catch (UnknownDBException e) { + throw new NoSuchNamespaceException("Namespace does not exist: %s", namespace); + + } catch (TException e) { + throw new RuntimeException("Failed to list all views under namespace " + namespace, e); + + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted in call to listViews", e); + } + } + + private List<TableIdentifier> listContents( + Namespace namespace, String tableType, Predicate<Table> tablePredicate) + throws TException, InterruptedException { + Preconditions.checkArgument( + isValidateNamespace(namespace), "Missing database in namespace: %s", namespace); + String database = namespace.level(0); + List<String> tableNames = + StringUtils.isNotEmpty(tableType) + ? clients.run(client -> client.getTables(database, "*", TableType.valueOf(tableType))) + : clients.run(client -> client.getAllTables(database)); + List<Table> tableObjects = + clients.run(client -> client.getTableObjectsByName(database, tableNames)); + List<TableIdentifier> tableIdentifiers = + tableObjects.stream() + .filter(tablePredicate) + .map(table -> TableIdentifier.of(namespace, table.getTableName())) + .collect(Collectors.toList()); + + LOG.debug( + "Listing of namespace: {} for table type {} resulted in the following: {}", + namespace, + tableType, + tableIdentifiers); + return tableIdentifiers; + } + + private Predicate<Table> icebergPredicate() { + return table -> + table.getParameters() != null + && BaseMetastoreTableOperations.ICEBERG_TABLE_TYPE_VALUE.equalsIgnoreCase( + table.getParameters().get(BaseMetastoreTableOperations.TABLE_TYPE_PROP)); + } + + @Override + @SuppressWarnings("FormatStringAnnotation") + public void renameView(TableIdentifier from, TableIdentifier originalTo) { + + if (!isValidIdentifier(from)) { + throw new NoSuchViewException("Invalid identifier: %s", from); + } + + if (!namespaceExists(originalTo.namespace())) { + throw new NoSuchNamespaceException( + "Cannot rename %s to %s. Namespace does not exist: %s", + from, originalTo, originalTo.namespace()); + } + + TableIdentifier to = removeCatalogName(originalTo); + Preconditions.checkArgument(isValidIdentifier(to), "Invalid identifier: %s", to); + + String toDatabase = to.namespace().level(0); + String fromDatabase = from.namespace().level(0); + String fromName = from.name(); + + try { + Table fromView = clients.run(client -> client.getTable(fromDatabase, fromName)); + HiveCatalogUtil.validateTableIsIcebergView(fromView, fullTableName(name, from)); + if (tableExists(to)) { + LOG.warn("Cannot rename view {} to {}. Table {} already exists.", from, to, to); Review Comment: nit: do we need to log warning when we are throwing the exception? ########## hive-metastore/src/main/java/org/apache/iceberg/hive/HiveViewOperations.java: ########## @@ -0,0 +1,346 @@ +/* + * 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.hive; + +import java.util.Collections; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hive.common.StatsSetupConst; +import org.apache.hadoop.hive.metastore.IMetaStoreClient; +import org.apache.hadoop.hive.metastore.TableType; +import org.apache.hadoop.hive.metastore.api.InvalidObjectException; +import org.apache.hadoop.hive.metastore.api.NoSuchObjectException; +import org.apache.hadoop.hive.metastore.api.SerDeInfo; +import org.apache.hadoop.hive.metastore.api.StorageDescriptor; +import org.apache.hadoop.hive.metastore.api.Table; +import org.apache.iceberg.BaseMetastoreTableOperations; +import org.apache.iceberg.ClientPool; +import org.apache.iceberg.SchemaParser; +import org.apache.iceberg.TableProperties; +import org.apache.iceberg.catalog.TableIdentifier; +import org.apache.iceberg.exceptions.AlreadyExistsException; +import org.apache.iceberg.exceptions.CommitFailedException; +import org.apache.iceberg.exceptions.CommitStateUnknownException; +import org.apache.iceberg.exceptions.NoSuchViewException; +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.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; +import org.apache.iceberg.view.BaseViewOperations; +import org.apache.iceberg.view.ViewMetadata; +import org.apache.thrift.TException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Hive implementation of Iceberg ViewOperations. */ +final class HiveViewOperations extends BaseViewOperations { + private static final Logger LOG = LoggerFactory.getLogger(HiveViewOperations.class); + + private final String fullName; + private final String database; + private final String tableName; + private final Configuration conf; + private final FileIO fileIO; + private final ClientPool<IMetaStoreClient, TException> metaClients; + private final long maxHiveTablePropertySize; + private final TableIdentifier identifier; + + HiveViewOperations( + Configuration conf, + ClientPool<IMetaStoreClient, TException> metaClients, + FileIO fileIO, + String catalogName, + TableIdentifier tableIdentifier) { + this.identifier = tableIdentifier; + String dbName = tableIdentifier.namespace().level(0); + this.conf = conf; + this.metaClients = metaClients; + this.fileIO = fileIO; + this.fullName = catalogName + "." + dbName + "." + tableIdentifier.name(); + this.database = dbName; + this.tableName = tableIdentifier.name(); + this.maxHiveTablePropertySize = + conf.getLong( + HiveCatalogUtil.HIVE_TABLE_PROPERTY_MAX_SIZE, + HiveCatalogUtil.HIVE_TABLE_PROPERTY_MAX_SIZE_DEFAULT); + } + + @Override + public ViewMetadata current() { + if (HiveCatalogUtil.isTableWithTypeExists(metaClients, identifier, TableType.EXTERNAL_TABLE)) { + throw new AlreadyExistsException( + "Table with same name already exists: %s.%s", database, tableName); + } + return super.current(); + } + + @Override + public void doRefresh() { + String metadataLocation = null; + try { + Table table = metaClients.run(client -> client.getTable(database, tableName)); + HiveCatalogUtil.validateTableIsIcebergView(table, fullName); + metadataLocation = + table.getParameters().get(BaseMetastoreTableOperations.METADATA_LOCATION_PROP); + } catch (NoSuchObjectException e) { + if (currentMetadataLocation() != null) { + throw new NoSuchViewException("View does not exist: %s.%s", database, tableName); + } + } catch (TException e) { + String errMsg = + String.format("Failed to get view info from metastore %s.%s", database, tableName); + throw new RuntimeException(errMsg, e); + + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted during refresh", e); + } + refreshFromMetadataLocation(metadataLocation); + } + + @SuppressWarnings("checkstyle:CyclomaticComplexity") + @Override + public void doCommit(ViewMetadata base, ViewMetadata metadata) { + boolean newTable = base == null; + String newMetadataLocation = writeNewMetadataIfRequired(metadata); + boolean keepHiveStats = conf.getBoolean(ConfigProperties.KEEP_HIVE_STATS, false); + + boolean updateHiveTable = false; + + try { + + Table tbl = loadHmsTable(); + + if (tbl != null) { + // If we try to create the view but the metadata location is already set, then we had a + // concurrent commit + if (newTable + && tbl.getParameters().get(BaseMetastoreTableOperations.METADATA_LOCATION_PROP) + != null) { + throw new AlreadyExistsException("View already exists: %s.%s", database, tableName); + } + + updateHiveTable = true; + LOG.debug("Committing existing view: {}", fullName); + } else { + tbl = newHmsTable(metadata); + LOG.debug("Committing new view: {}", fullName); + } + + tbl.setSd(storageDescriptor(metadata)); // set to pickup any schema changes + + String metadataLocation = + tbl.getParameters().get(BaseMetastoreTableOperations.METADATA_LOCATION_PROP); + String baseMetadataLocation = base != null ? base.metadataFileLocation() : null; + if (!Objects.equals(baseMetadataLocation, metadataLocation)) { + throw new CommitFailedException( + "Base metadata location '%s' is not same as the current table metadata location '%s' for %s.%s", + baseMetadataLocation, metadataLocation, database, tableName); + } + + setHmsTableParameters(newMetadataLocation, tbl, metadata); + + if (!keepHiveStats) { + tbl.getParameters().remove(StatsSetupConst.COLUMN_STATS_ACCURATE); + } + + try { + persistTable(tbl, updateHiveTable, baseMetadataLocation); + + } catch (LockException le) { + throw new CommitStateUnknownException( Review Comment: @nastra: what do you think about this? -- 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