World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#11059] feat(iceberg-rest): Support overwrite on registerTable endpoint (#11809)
MaSai6ce2b611f2b7
diff --git a/iceberg/iceberg-common/src/main/java/org/apache/iceberg/MetastoreRegisterTableUtils.java b/iceberg/iceberg-common/src/main/java/org/apache/iceberg/MetastoreRegisterTableUtils.javanew file mode 100644index 0000000000..82782f8888--- /dev/null+++ b/iceberg/iceberg-common/src/main/java/org/apache/iceberg/MetastoreRegisterTableUtils.java@@ -0,0 +1,100 @@+/*+ * 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;++import com.google.common.base.Preconditions;+import org.apache.iceberg.catalog.TableIdentifier;++/**+ * Shared helpers for {@link org.apache.iceberg.catalog.Catalog#registerTable(TableIdentifier,+ * String, boolean)} on {@link BaseMetastoreCatalog} implementations where Iceberg's default+ * implementation does not support {@code overwrite=true}.+ */+public class MetastoreRegisterTableUtils {++ /** Atomically overwrites the metastore metadata location during register overwrite. */+ public interface MetadataLocationOverwrite {+ /**+ * @param identifier table identifier+ * @param oldMetadataLocation current metadata file location before overwrite+ * @param newMetadataLocation metadata file location to register+ */+ void overwrite(+ TableIdentifier identifier, String oldMetadataLocation, String newMetadataLocation);+ }++ /**+ * Registers a table from an existing metadata file, optionally overwriting an existing+ * registration by replacing the metastore metadata location.+ *+ * @param catalog metastore catalog that performs the registration+ * @param identifier table identifier to register+ * @param metadataFileLocation location of the metadata file to register+ * @param overwrite whether to overwrite an existing table registration+ * @param metadataLocationOverwrite backend-specific atomic metadata location overwrite+ * @return the registered table+ */+ public static Table registerTable(+ BaseMetastoreCatalog catalog,+ TableIdentifier identifier,+ String metadataFileLocation,+ boolean overwrite,+ MetadataLocationOverwrite metadataLocationOverwrite) {+ if (!overwrite) {+ return catalog.registerTable(identifier, metadataFileLocation);+ }++ Preconditions.checkArgument(+ identifier != null && catalog.isValidIdentifier(identifier),+ "Invalid identifier: %s",+ identifier);+ Preconditions.checkArgument(+ metadataFileLocation != null && !metadataFileLocation.isEmpty(),+ "Cannot register an empty metadata file location as a table");++ if (!catalog.tableExists(identifier)) {+ return catalog.registerTable(identifier, metadataFileLocation);+ }++ TableOperations ops = catalog.newTableOps(identifier);+ Preconditions.checkArgument(+ ops instanceof BaseMetastoreTableOperations,+ "Cannot register table %s: table operations are not metastore-backed",+ identifier);+ BaseMetastoreTableOperations metastoreOps = (BaseMetastoreTableOperations) ops;++ metastoreOps.refresh();+ TableMetadata base = metastoreOps.current();+ Preconditions.checkArgument(+ base != null, "Cannot overwrite table %s: current metadata is missing", identifier);++ TableMetadataParser.read(metastoreOps.io().newInputFile(metadataFileLocation));++ String oldMetadataLocation = base.metadataFileLocation();+ metadataLocationOverwrite.overwrite(identifier, oldMetadataLocation, metadataFileLocation);+ metastoreOps.refresh();++ return new BaseTable(+ ops,+ BaseMetastoreCatalog.fullTableName(catalog.name(), identifier),+ catalog.metricsReporter());+ }++ private MetastoreRegisterTableUtils() {}+}diff --git a/iceberg/iceberg-common/src/main/java/org/apache/iceberg/hive/HiveCatalogWithMetadataLocationSupport.java b/iceberg/iceberg-common/src/main/java/org/apache/iceberg/hive/HiveCatalogWithMetadataLocationSupport.javaindex 8a9414c4d3..d704a04be3 100644--- a/iceberg/iceberg-common/src/main/java/org/apache/iceberg/hive/HiveCatalogWithMetadataLocationSupport.java+++ b/iceberg/iceberg-common/src/main/java/org/apache/iceberg/hive/HiveCatalogWithMetadataLocationSupport.java@@ -21,14 +21,27 @@ package org.apache.iceberg.hive;import com.google.common.base.Preconditions;import java.util.Map;+import java.util.Objects;+import java.util.Set;+import java.util.stream.Collectors;import org.apache.commons.lang3.reflect.FieldUtils;import org.apache.gravitino.iceberg.common.ClosableHiveCatalog;import org.apache.gravitino.iceberg.common.cache.SupportsMetadataLocation;+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.api.Table;import org.apache.iceberg.BaseMetastoreTableOperations;import org.apache.iceberg.ClientPool;+import org.apache.iceberg.MetastoreRegisterTableUtils;+import org.apache.iceberg.Table;+import org.apache.iceberg.TableMetadata;+import org.apache.iceberg.TableMetadataParser;+import org.apache.iceberg.TableProperties;import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.exceptions.CommitFailedException;+import org.apache.iceberg.exceptions.CommitStateUnknownException;+import org.apache.iceberg.exceptions.NoSuchTableException;+import org.apache.iceberg.hadoop.ConfigProperties;import org.apache.thrift.TException;public class HiveCatalogWithMetadataLocationSupport extends ClosableHiveCatalog@@ -41,24 +54,129 @@ public class HiveCatalogWithMetadataLocationSupport extends ClosableHiveCatalogloadFields();}+ /**+ * Registers a table from an existing metadata file, optionally overwriting an existing+ * registration.+ *+ * @param identifier table identifier to register+ * @param metadataFileLocation location of the metadata file to register+ * @param overwrite whether to overwrite an existing table registration+ * @return the registered table+ */+ @Override+ public Table registerTable(+ TableIdentifier identifier, String metadataFileLocation, boolean overwrite) {+ return MetastoreRegisterTableUtils.registerTable(+ this, identifier, metadataFileLocation, overwrite, this::overwriteMetadataLocation);+ }+@Overridepublic String metadataLocation(TableIdentifier tableIdentifier) {String dbName = tableIdentifier.namespace().level(0);String tableName = tableIdentifier.name();try {- Table table = metaClients.run(client -> client.getTable(dbName, tableName));- String tableType = table.getParameters().get(BaseMetastoreTableOperations.TABLE_TYPE_PROP);+ org.apache.hadoop.hive.metastore.api.Table hiveTable =+ metaClients.run(client -> client.getTable(dbName, tableName));+ String tableType =+ hiveTable.getParameters().get(BaseMetastoreTableOperations.TABLE_TYPE_PROP);if (tableType == null|| !tableType.equalsIgnoreCase(BaseMetastoreTableOperations.ICEBERG_TABLE_TYPE_VALUE)) {return null;}- return table.getParameters().get(METADATA_LOCATION_PROP);+ return hiveTable.getParameters().get(BaseMetastoreTableOperations.METADATA_LOCATION_PROP);} catch (Exception e) {return null;}}+ private void overwriteMetadataLocation(+ TableIdentifier tableIdentifier, String oldMetadataLocation, String newMetadataLocation) {+ HiveTableOperations ops = (HiveTableOperations) newTableOps(tableIdentifier);+ HiveOperationsBase hiveOps = ops;+ Configuration conf = getConf();++ TableMetadata base = ops.current();+ TableMetadata targetMetadata =+ TableMetadataParser.read(ops.io().newInputFile(newMetadataLocation));++ boolean hiveEngineEnabled = hiveEngineEnabled(targetMetadata, conf);+ boolean keepHiveStats = conf.getBoolean(ConfigProperties.KEEP_HIVE_STATS, false);++ Set<String> removedProps =+ base.properties().keySet().stream()+ .filter(key -> !targetMetadata.properties().containsKey(key))+ .collect(Collectors.toSet());++ Preconditions.checkArgument(+ !removedProps.contains(TableProperties.ENCRYPTION_TABLE_KEY),+ "Cannot remove key ID from an encrypted table");+ Preconditions.checkArgument(+ Objects.equals(+ base.properties().get(TableProperties.ENCRYPTION_TABLE_KEY),+ targetMetadata.properties().get(TableProperties.ENCRYPTION_TABLE_KEY)),+ "Cannot modify key ID of an encrypted table");++ HiveLock lock = ops.lockObject(base);+ try {+ lock.lock();++ org.apache.hadoop.hive.metastore.api.Table tbl = hiveOps.loadHmsTable();+ if (tbl == null) {+ throw new NoSuchTableException("Table does not exist: %s", tableIdentifier);+ }++ HiveOperationsBase.validateTableIsIceberg(tbl, tableIdentifier.toString());++ tbl.setSd(+ HiveOperationsBase.storageDescriptor(+ targetMetadata.schema(), targetMetadata.location(), hiveEngineEnabled));++ String hmsMetadataLocation =+ tbl.getParameters().get(BaseMetastoreTableOperations.METADATA_LOCATION_PROP);+ if (!Objects.equals(oldMetadataLocation, hmsMetadataLocation)) {+ throw new CommitFailedException(+ "Cannot overwrite table %s: metadata location %s has changed from %s",+ tableIdentifier, hmsMetadataLocation, oldMetadataLocation);+ }++ HMSTablePropertyHelper.updateHmsTableForIcebergTable(+ newMetadataLocation,+ tbl,+ targetMetadata,+ removedProps,+ hiveEngineEnabled,+ hiveOps.maxHiveTablePropertySize(),+ oldMetadataLocation);++ if (!keepHiveStats) {+ tbl.getParameters().remove(StatsSetupConst.COLUMN_STATS_ACCURATE);+ tbl.getParameters().put(StatsSetupConst.DO_NOT_UPDATE_STATS, StatsSetupConst.TRUE);+ }++ lock.ensureActive();+ hiveOps.persistTable(tbl, true, hiveLockEnabled(base, conf) ? null : oldMetadataLocation);+ lock.ensureActive();+ } catch (LockException e) {+ throw new CommitStateUnknownException(+ String.format(+ "Failed to heartbeat for hive lock while overwriting table registration for %s",+ tableIdentifier),+ e);+ } catch (TException e) {+ throw new RuntimeException(+ String.format(+ "Metastore operation failed while overwriting table registration for %s",+ tableIdentifier),+ e);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw new RuntimeException("Interrupted while overwriting table registration", e);+ } finally {+ lock.unlock();+ }+ }+private void loadFields() {try {this.metaClients =@@ -69,4 +187,22 @@ public class HiveCatalogWithMetadataLocationSupport extends ClosableHiveCatalogthrow new RuntimeException(e);}}++ private static boolean hiveEngineEnabled(TableMetadata metadata, Configuration conf) {+ if (metadata.properties().get(TableProperties.ENGINE_HIVE_ENABLED) != null) {+ return metadata.propertyAsBoolean(TableProperties.ENGINE_HIVE_ENABLED, false);+ }++ return conf.getBoolean(+ ConfigProperties.ENGINE_HIVE_ENABLED, TableProperties.ENGINE_HIVE_ENABLED_DEFAULT);+ }++ private static boolean hiveLockEnabled(TableMetadata metadata, Configuration conf) {+ if (metadata != null && metadata.properties().get(TableProperties.HIVE_LOCK_ENABLED) != null) {+ return metadata.propertyAsBoolean(TableProperties.HIVE_LOCK_ENABLED, false);+ }++ return conf.getBoolean(+ ConfigProperties.LOCK_HIVE_ENABLED, TableProperties.HIVE_LOCK_ENABLED_DEFAULT);+ }}diff --git a/iceberg/iceberg-common/src/main/java/org/apache/iceberg/jdbc/JdbcCatalogWithMetadataLocationSupport.java b/iceberg/iceberg-common/src/main/java/org/apache/iceberg/jdbc/JdbcCatalogWithMetadataLocationSupport.javaindex e4a65a9d2c..e3f51ef5c1 100644--- a/iceberg/iceberg-common/src/main/java/org/apache/iceberg/jdbc/JdbcCatalogWithMetadataLocationSupport.java+++ b/iceberg/iceberg-common/src/main/java/org/apache/iceberg/jdbc/JdbcCatalogWithMetadataLocationSupport.java@@ -20,15 +20,24 @@package org.apache.iceberg.jdbc;import com.google.common.base.Preconditions;+import java.sql.SQLException;import java.util.Map;import org.apache.commons.lang3.reflect.FieldUtils;import org.apache.gravitino.iceberg.common.cache.SupportsMetadataLocation;+import org.apache.iceberg.MetastoreRegisterTableUtils;+import org.apache.iceberg.Table;import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.exceptions.CommitFailedException;import org.apache.iceberg.jdbc.JdbcUtil.SchemaVersion;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;// Use Iceberg package to reuse JdbcUtil related classes.public class JdbcCatalogWithMetadataLocationSupport extends JdbcCatalogimplements SupportsMetadataLocation {+ private static final Logger LOG =+ LoggerFactory.getLogger(JdbcCatalogWithMetadataLocationSupport.class);+private String jdbcCatalogName;private JdbcClientPool jdbcConnections;private SchemaVersion jdbcSchemaVersion;@@ -68,6 +77,48 @@ public class JdbcCatalogWithMetadataLocationSupport extends JdbcCatalogreturn jdbcSchemaVersion != null && jdbcSchemaVersion != SchemaVersion.V0;}+ /**+ * Registers a table from an existing metadata file, optionally overwriting an existing+ * registration.+ *+ * @param identifier table identifier to register+ * @param metadataFileLocation location of the metadata file to register+ * @param overwrite whether to overwrite an existing table registration+ * @return the registered table+ */+ @Override+ public Table registerTable(+ TableIdentifier identifier, String metadataFileLocation, boolean overwrite) {+ return MetastoreRegisterTableUtils.registerTable(+ this, identifier, metadataFileLocation, overwrite, this::overwriteMetadataLocation);+ }++ private void overwriteMetadataLocation(+ TableIdentifier tableIdentifier, String oldMetadataLocation, String newMetadataLocation) {+ try {+ int updatedRecords =+ JdbcUtil.updateTable(+ jdbcSchemaVersion,+ jdbcConnections,+ jdbcCatalogName,+ tableIdentifier,+ newMetadataLocation,+ oldMetadataLocation);++ if (updatedRecords == 1) {+ LOG.debug("Successfully committed to existing table: {}", tableIdentifier);+ } else {+ throw new CommitFailedException(+ "Failed to update table %s from catalog %s", tableIdentifier, jdbcCatalogName);+ }+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw new UncheckedInterruptedException(e, "Interrupted during commit");+ } catch (SQLException e) {+ throw new UncheckedSQLException(e, "Unknown failure");+ }+ }+private void loadFields() {try {this.jdbcCatalogName = (String) FieldUtils.readField(this, "catalogName", true);diff --git a/iceberg/iceberg-common/src/main/java/org/apache/iceberg/memory/MemoryCatalogWithMetadataLocationSupport.java b/iceberg/iceberg-common/src/main/java/org/apache/iceberg/memory/MemoryCatalogWithMetadataLocationSupport.javaindex e209d91b3e..710ba35e0c 100644--- a/iceberg/iceberg-common/src/main/java/org/apache/iceberg/memory/MemoryCatalogWithMetadataLocationSupport.java+++ b/iceberg/iceberg-common/src/main/java/org/apache/iceberg/memory/MemoryCatalogWithMetadataLocationSupport.java@@ -24,7 +24,10 @@ import java.util.Map;import java.util.concurrent.ConcurrentMap;import org.apache.commons.lang3.reflect.FieldUtils;import org.apache.gravitino.iceberg.common.cache.SupportsMetadataLocation;+import org.apache.iceberg.MetastoreRegisterTableUtils;+import org.apache.iceberg.Table;import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.exceptions.CommitFailedException;import org.apache.iceberg.inmemory.InMemoryCatalog;public class MemoryCatalogWithMetadataLocationSupport extends InMemoryCatalog@@ -38,11 +41,36 @@ public class MemoryCatalogWithMetadataLocationSupport extends InMemoryCatalogloadFields();}+ /**+ * Registers a table from an existing metadata file, optionally overwriting an existing+ * registration.+ *+ * @param identifier table identifier to register+ * @param metadataFileLocation location of the metadata file to register+ * @param overwrite whether to overwrite an existing table registration+ * @return the registered table+ */+ @Override+ public Table registerTable(+ TableIdentifier identifier, String metadataFileLocation, boolean overwrite) {+ return MetastoreRegisterTableUtils.registerTable(+ this, identifier, metadataFileLocation, overwrite, this::overwriteMetadataLocation);+ }+@Overridepublic String metadataLocation(TableIdentifier tableIdentifier) {return tableStore.get(tableIdentifier);}+ private void overwriteMetadataLocation(+ TableIdentifier tableIdentifier, String oldMetadataLocation, String newMetadataLocation) {+ if (!tableStore.replace(tableIdentifier, oldMetadataLocation, newMetadataLocation)) {+ throw new CommitFailedException(+ "Cannot overwrite table %s metadata location from %s to %s",+ tableIdentifier, oldMetadataLocation, newMetadataLocation);+ }+ }+private void loadFields() {try {this.tableStore =diff --git a/iceberg/iceberg-common/src/test/java/org/apache/iceberg/TestMetastoreRegisterTableUtils.java b/iceberg/iceberg-common/src/test/java/org/apache/iceberg/TestMetastoreRegisterTableUtils.javanew file mode 100644index 0000000000..e5d8122d4d--- /dev/null+++ b/iceberg/iceberg-common/src/test/java/org/apache/iceberg/TestMetastoreRegisterTableUtils.java@@ -0,0 +1,67 @@+/*+ * 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;++import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import org.apache.iceberg.catalog.TableIdentifier;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestMetastoreRegisterTableUtils {++ @Test+ void testRegisterWithoutOverwrite() {+ BaseMetastoreCatalog catalog = mock(BaseMetastoreCatalog.class);+ MetastoreRegisterTableUtils.MetadataLocationOverwrite metadataLocationOverwrite =+ mock(MetastoreRegisterTableUtils.MetadataLocationOverwrite.class);+ TableIdentifier identifier = TableIdentifier.of("ns", "t");+ String metadataLocation = "s3://bucket/ns/t/metadata/v1.metadata.json";+ Table table = mock(Table.class);++ when(catalog.registerTable(identifier, metadataLocation)).thenReturn(table);++ Table result =+ MetastoreRegisterTableUtils.registerTable(+ catalog, identifier, metadataLocation, false, metadataLocationOverwrite);++ Assertions.assertSame(table, result);+ verify(catalog).registerTable(identifier, metadataLocation);+ verifyNoInteractions(metadataLocationOverwrite);+ }++ @Test+ void testOverwriteRejectsEmptyLocation() {+ BaseMetastoreCatalog catalog = mock(BaseMetastoreCatalog.class);+ MetastoreRegisterTableUtils.MetadataLocationOverwrite metadataLocationOverwrite =+ mock(MetastoreRegisterTableUtils.MetadataLocationOverwrite.class);+ TableIdentifier identifier = TableIdentifier.of("ns", "t");++ when(catalog.isValidIdentifier(identifier)).thenReturn(true);++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ MetastoreRegisterTableUtils.registerTable(+ catalog, identifier, "", true, metadataLocationOverwrite));+ }+}diff --git a/iceberg/iceberg-common/src/test/java/org/apache/iceberg/jdbc/TestJdbcCatalogWithMetadataLocationSupport.java b/iceberg/iceberg-common/src/test/java/org/apache/iceberg/jdbc/TestJdbcCatalogWithMetadataLocationSupport.javaindex d6443ca15f..cb1d92cc2a 100644--- a/iceberg/iceberg-common/src/test/java/org/apache/iceberg/jdbc/TestJdbcCatalogWithMetadataLocationSupport.java+++ b/iceberg/iceberg-common/src/test/java/org/apache/iceberg/jdbc/TestJdbcCatalogWithMetadataLocationSupport.java@@ -20,9 +20,16 @@package org.apache.iceberg.jdbc;import com.google.common.collect.ImmutableMap;+import java.nio.file.Files;import java.util.HashMap;import java.util.Map;+import org.apache.iceberg.BaseTable;import org.apache.iceberg.CatalogProperties;+import org.apache.iceberg.Schema;+import org.apache.iceberg.catalog.Namespace;+import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.exceptions.AlreadyExistsException;+import org.apache.iceberg.types.Types;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;import org.junit.jupiter.params.ParameterizedTest;@@ -30,6 +37,9 @@ import org.junit.jupiter.params.provider.CsvSource;public class TestJdbcCatalogWithMetadataLocationSupport {+ private static final Schema SCHEMA =+ new Schema(Types.NestedField.required(1, "id", Types.IntegerType.get()));+@Testvoid testLoadFields() {JdbcCatalogWithMetadataLocationSupport catalog =@@ -64,4 +74,41 @@ public class TestJdbcCatalogWithMetadataLocationSupport {Assertions.assertEquals(expectedSupportsViews, catalog.supportsViewsWithSchemaVersion(), message);}++ @Test+ void testRegisterTableOverwrite() throws Exception {+ String warehouse = Files.createTempDirectory("jdbc-register-overwrite").toString();+ JdbcCatalogWithMetadataLocationSupport catalog =+ new JdbcCatalogWithMetadataLocationSupport(true);+ catalog.initialize(+ "jdbc_overwrite",+ ImmutableMap.of(+ CatalogProperties.URI,+ "jdbc:h2:mem:register_overwrite;DB_CLOSE_DELAY=-1",+ CatalogProperties.WAREHOUSE_LOCATION,+ warehouse));++ Namespace namespace = Namespace.of("ns");+ catalog.createNamespace(namespace);+ TableIdentifier ident = TableIdentifier.of(namespace, "t");++ BaseTable table = (BaseTable) catalog.createTable(ident, SCHEMA);+ String metadataV1 = table.operations().current().metadataFileLocation();++ table.updateProperties().set("version", "v2").commit();+ String metadataV2 = table.operations().current().metadataFileLocation();++ catalog.registerTable(ident, metadataV1, true);+ Assertions.assertEquals(metadataV1, catalog.metadataLocation(ident));+ Assertions.assertFalse(+ ((BaseTable) catalog.loadTable(ident)).properties().containsKey("version"));++ catalog.registerTable(ident, metadataV2, true);+ Assertions.assertEquals(metadataV2, catalog.metadataLocation(ident));+ Assertions.assertEquals(+ "v2", ((BaseTable) catalog.loadTable(ident)).properties().get("version"));++ Assertions.assertThrows(+ AlreadyExistsException.class, () -> catalog.registerTable(ident, metadataV2, false));+ }}diff --git a/iceberg/iceberg-common/src/test/java/org/apache/iceberg/memory/TestMemoryCatalogWithMetadataLocationSupport.java b/iceberg/iceberg-common/src/test/java/org/apache/iceberg/memory/TestMemoryCatalogWithMetadataLocationSupport.javaindex cbfbd7b22f..e6d917046d 100644--- a/iceberg/iceberg-common/src/test/java/org/apache/iceberg/memory/TestMemoryCatalogWithMetadataLocationSupport.java+++ b/iceberg/iceberg-common/src/test/java/org/apache/iceberg/memory/TestMemoryCatalogWithMetadataLocationSupport.java@@ -24,6 +24,7 @@ import org.apache.iceberg.BaseTable;import org.apache.iceberg.Schema;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.exceptions.AlreadyExistsException;import org.apache.iceberg.types.Types;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;@@ -53,4 +54,32 @@ public class TestMemoryCatalogWithMetadataLocationSupport {catalog.dropTable(tableIdentifier);Assertions.assertNull(catalog.metadataLocation(tableIdentifier));}++ @Test+ void testRegisterTableOverwrite() {+ MemoryCatalogWithMetadataLocationSupport catalog =+ new MemoryCatalogWithMetadataLocationSupport();+ catalog.initialize("memory", Collections.emptyMap());+ catalog.createNamespace(Namespace.of("ns"));+ TableIdentifier ident = TableIdentifier.of("ns", "t");++ BaseTable table = (BaseTable) catalog.createTable(ident, SCHEMA);+ String metadataV1 = table.operations().current().metadataFileLocation();++ table.updateProperties().set("version", "v2").commit();+ String metadataV2 = table.operations().current().metadataFileLocation();++ catalog.registerTable(ident, metadataV1, true);+ Assertions.assertEquals(metadataV1, catalog.metadataLocation(ident));+ Assertions.assertFalse(+ ((BaseTable) catalog.loadTable(ident)).properties().containsKey("version"));++ catalog.registerTable(ident, metadataV2, true);+ Assertions.assertEquals(metadataV2, catalog.metadataLocation(ident));+ Assertions.assertEquals(+ "v2", ((BaseTable) catalog.loadTable(ident)).properties().get("version"));++ Assertions.assertThrows(+ AlreadyExistsException.class, () -> catalog.registerTable(ident, metadataV2, false));+ }}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/FederatedCatalogWrapper.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/FederatedCatalogWrapper.javaindex cbe5724921..d11da80c98 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/FederatedCatalogWrapper.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/FederatedCatalogWrapper.java@@ -296,13 +296,15 @@ public class FederatedCatalogWrapper extends CatalogWrapperForREST {/*** Federation-aware {@code registerTable}: registers the existing table metadata on the underlying- * (remote) catalog and extracts client-facing FileIO/credential properties from {@code- * table.io()}, mirroring {@link #loadTableInternal(TableIdentifier)}.+ * (remote) catalog via {@link CatalogHandlers#registerTable} and extracts client-facing FileIO+ * and credential properties from {@code table.io()}, mirroring {@link+ * #loadTableInternal(TableIdentifier)}.*/private LoadTableResponse registerTableInternal(Namespace namespace, RegisterTableRequest request) {+ CatalogHandlers.registerTable(getCatalog(), namespace, request);TableIdentifier ident = TableIdentifier.of(namespace, request.name());- Table table = getCatalog().registerTable(ident, request.metadataLocation());+ Table table = getCatalog().loadTable(ident);if (table instanceof BaseTable) {return buildLoadTableResponseFromFileIo(ident, (BaseTable) table);diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceHookDispatcher.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceHookDispatcher.javaindex 635f766256..440ac71b1a 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergNamespaceHookDispatcher.java@@ -18,9 +18,12 @@*/package org.apache.gravitino.iceberg.service.dispatcher;+import java.io.IOException;import java.util.ArrayList;import java.util.Collections;import java.util.List;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.catalog.SchemaDispatcher;@@ -183,6 +186,12 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperationRegisterTableRequest registerTableRequest) {LoadTableResponse response = dispatcher.registerTable(context, namespace, registerTableRequest);+ if (hasTableEntityInStore(context, namespace, registerTableRequest.name())) {+ // Gravitino already tracks this table: preserve table_id and existing role/owner/tag/policy+ // bindings after the backend registerTable completes.+ return response;+ }+// Import is intentionally NOT wrapped in try-catch: if it fails the table exists in Iceberg// but not in Gravitino, and silently swallowing that would mislead callers into thinking the// entity is registered. Surface the failure so the caller can react.@@ -199,6 +208,25 @@ public class IcebergNamespaceHookDispatcher implements IcebergNamespaceOperationreturn response;}+ private boolean hasTableEntityInStore(+ IcebergRequestContext context, Namespace namespace, String tableName) {+ EntityStore entityStore = GravitinoEnv.getInstance().entityStore();+ if (entityStore == null) {+ return false;+ }+ try {+ return entityStore.exists(+ IcebergIdentifierUtils.toGravitinoTableIdentifier(+ metalake,+ context.catalogName(),+ TableIdentifier.of(namespace, tableName),+ HierarchicalSchemaUtil.schemaSeparator()),+ Entity.EntityType.TABLE);+ } catch (IOException ioe) {+ throw new RuntimeException("io exception when checking table entity existence", ioe);+ }+ }+private void importTable(String catalogName, Namespace namespace, String tableName) {TableDispatcher tableDispatcher = GravitinoEnv.getInstance().internalTableDispatcher();if (tableDispatcher != null) {diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergRESTHiveCatalogIT.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergRESTHiveCatalogIT.javaindex 9c39a58a81..8e899ef89f 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergRESTHiveCatalogIT.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/integration/test/IcebergRESTHiveCatalogIT.java@@ -18,14 +18,24 @@*/package org.apache.gravitino.iceberg.integration.test;+import com.google.common.collect.ImmutableMap;import java.util.HashMap;+import java.util.List;import java.util.Map;import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergCatalogBackend;import org.apache.gravitino.iceberg.common.IcebergConfig;import org.apache.gravitino.integration.test.container.ContainerSuite;import org.apache.gravitino.integration.test.container.HiveContainer;import org.apache.gravitino.integration.test.util.GravitinoITUtils;+import org.apache.iceberg.CatalogProperties;+import org.apache.iceberg.Table;+import org.apache.iceberg.catalog.Namespace;+import org.apache.iceberg.catalog.TableIdentifier;+import org.apache.iceberg.exceptions.AlreadyExistsException;+import org.apache.iceberg.rest.RESTCatalog;+import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Tag;+import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestInstance;import org.junit.jupiter.api.TestInstance.Lifecycle;@@ -71,4 +81,41 @@ public class IcebergRESTHiveCatalogIT extends IcebergRESTServiceIT {HiveContainer.HDFS_DEFAULTFS_PORT)));return configMap;}++ @Test+ void testRegisterTableOverwrite() throws Exception {+ String namespace = getTestNamespace();+ sql(+ "CREATE TABLE %s.register_overwrite_t (id bigint COMMENT 'unique id', data string) USING iceberg",+ namespace);+ sql("ALTER TABLE %s.register_overwrite_t SET TBLPROPERTIES ('version' = 'v2')", namespace);++ List<String> metadataLocations =+ convertToStringList(+ sql("SELECT file FROM %s.register_overwrite_t.metadata_log_entries", namespace), 0);+ Assertions.assertTrue(metadataLocations.size() >= 2);+ String metadataV1 = metadataLocations.get(0);+ String metadataV2 = metadataLocations.get(metadataLocations.size() - 1);++ Namespace icebergNamespace = Namespace.of(namespace);+ TableIdentifier tableIdent = TableIdentifier.of(icebergNamespace, "register_overwrite_t");++ try (RESTCatalog catalog = new RESTCatalog()) {+ catalog.initialize(+ "rest",+ ImmutableMap.of(+ CatalogProperties.URI,+ String.format("http://127.0.0.1:%d/iceberg/", getServerPort())));+ catalog.registerTable(tableIdent, metadataV1, true);+ Table table = catalog.loadTable(tableIdent);+ Assertions.assertFalse(table.properties().containsKey("version"));++ catalog.registerTable(tableIdent, metadataV2, true);+ table = catalog.loadTable(tableIdent);+ Assertions.assertEquals("v2", table.properties().get("version"));++ Assertions.assertThrows(+ AlreadyExistsException.class, () -> catalog.registerTable(tableIdent, metadataV2, false));+ }+ }}diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestCatalogWrapperForREST.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestCatalogWrapperForREST.javaindex e372170585..2607eae063 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestCatalogWrapperForREST.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestCatalogWrapperForREST.java@@ -20,6 +20,7 @@package org.apache.gravitino.iceberg.service;import static org.mockito.Mockito.any;+import static org.mockito.Mockito.anyBoolean;import static org.mockito.Mockito.anyMap;import static org.mockito.Mockito.anyString;import static org.mockito.Mockito.doAnswer;@@ -627,7 +628,10 @@ public class TestCatalogWrapperForREST {BaseTable table = mock(BaseTable.class);TableOperations ops = mock(TableOperations.class);FileIO fileIO = mock(FileIO.class);- when(catalog.registerTable(any(TableIdentifier.class), anyString())).thenReturn(table);+ TableIdentifier ident = TableIdentifier.of("db", "tbl");+ when(catalog.registerTable(any(TableIdentifier.class), anyString(), anyBoolean()))+ .thenReturn(table);+ when(catalog.loadTable(ident)).thenReturn(table);when(table.operations()).thenReturn(ops);when(ops.current()).thenReturn(minimalTableMetadataForStagedCreateTest());when(table.io()).thenReturn(fileIO);@@ -656,12 +660,51 @@ public class TestCatalogWrapperForREST {LoadTableResponse response = wrapper.registerTable(Namespace.of("db"), request, false);+ verify(catalog).registerTable(ident, request.metadataLocation(), false);+ verify(catalog).loadTable(ident);Assertions.assertEquals("org.apache.iceberg.aws.s3.S3FileIO", response.config().get(IcebergConstants.IO_IMPL));Assertions.assertEquals("http://localhost:9000", response.config().get(IcebergConstants.ICEBERG_S3_ENDPOINT));}+ @Test+ void testFederatedRegisterTableOverwrite() {+ RESTCatalog catalog = mock(RESTCatalog.class);+ BaseTable table = mock(BaseTable.class);+ TableOperations ops = mock(TableOperations.class);+ FileIO fileIO = mock(FileIO.class);+ TableIdentifier ident = TableIdentifier.of("db", "tbl");+ when(catalog.registerTable(any(TableIdentifier.class), anyString(), anyBoolean()))+ .thenReturn(table);+ when(catalog.loadTable(ident)).thenReturn(table);+ when(table.operations()).thenReturn(ops);+ when(ops.current()).thenReturn(minimalTableMetadataForStagedCreateTest());+ when(table.io()).thenReturn(fileIO);+ when(fileIO.properties()).thenReturn(ImmutableMap.of());++ IcebergConfig config =+ new IcebergConfig(+ ImmutableMap.of(+ IcebergConstants.CATALOG_BACKEND,+ "memory",+ IcebergConstants.WAREHOUSE,+ "/tmp/warehouse"));+ CatalogWrapperForREST wrapper = new StaticCatalogWrapperForREST("test", config, catalog);++ RegisterTableRequest request =+ ImmutableRegisterTableRequest.builder()+ .name("tbl")+ .metadataLocation("s3://bucket/warehouse/tbl/metadata/v2.metadata.json")+ .overwrite(true)+ .build();++ wrapper.registerTable(Namespace.of("db"), request, false);++ verify(catalog).registerTable(ident, request.metadataLocation(), true);+ verify(catalog).loadTable(ident);+ }+@Testvoid testWrapperLazyLoadsCatalog() {IcebergConfig config =diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceHookDispatcher.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceHookDispatcher.javaindex 7d5e76922b..cad6a8d595 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceHookDispatcher.java@@ -20,6 +20,7 @@ package org.apache.gravitino.iceberg.service.dispatcher;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doReturn;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;@@ -250,6 +251,45 @@ public class TestIcebergNamespaceHookDispatcher {verify(mockSchemaDispatcher, never()).loadSchema(any());}+ @Test+ public void testRegisterTableSkipsWhenGravitinoExists() throws Exception {+ Namespace namespace = Namespace.of("test_schema");+ RegisterTableRequest mockRequest = mock(RegisterTableRequest.class);+ when(mockRequest.name()).thenReturn("test_table");+ doReturn(true).when(mockEntityStore).exists(any(), eq(Entity.EntityType.TABLE));++ LoadTableResponse mockResponse = mock(LoadTableResponse.class);+ when(mockDispatcher.registerTable(mockContext, namespace, mockRequest))+ .thenReturn(mockResponse);++ LoadTableResponse response = hookDispatcher.registerTable(mockContext, namespace, mockRequest);++ Assertions.assertSame(mockResponse, response);+ verify(mockInternalTableDispatcher, never()).loadTable(any());+ verify(mockInternalOwnerDispatcher, never()).setOwner(any(), any(), any(), any());+ verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());+ }++ @Test+ public void testRegisterTableImportsWhenGravitinoMissing() throws Exception {+ Namespace namespace = Namespace.of("test_schema");+ RegisterTableRequest mockRequest = mock(RegisterTableRequest.class);+ when(mockRequest.name()).thenReturn("test_table");+ doReturn(false).when(mockEntityStore).exists(any(), eq(Entity.EntityType.TABLE));++ LoadTableResponse mockResponse = mock(LoadTableResponse.class);+ when(mockDispatcher.registerTable(mockContext, namespace, mockRequest))+ .thenReturn(mockResponse);++ LoadTableResponse response = hookDispatcher.registerTable(mockContext, namespace, mockRequest);++ Assertions.assertSame(mockResponse, response);+ verify(mockDispatcher).registerTable(mockContext, namespace, mockRequest);+ verify(mockInternalTableDispatcher).loadTable(any());+ verify(mockInternalOwnerDispatcher).setOwner(any(), any(), any(), any());+ verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());+ }+@Testpublic void testRegisterTablePropagatesImportFailure() {Namespace namespace = Namespace.of("test_schema");