World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#15141] improvement(hive): Avoid full loads in table existence checks (#15142)
jarred0214fce4288bc389
diff --git a/api/src/main/java/org/apache/gravitino/rel/SupportsTableIdentifier.java b/api/src/main/java/org/apache/gravitino/rel/SupportsTableIdentifier.javanew file mode 100644index 0000000000..e51404e77d--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/rel/SupportsTableIdentifier.java@@ -0,0 +1,49 @@+/*+ * 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.+ */++// Referred from Apache's connector/catalog implementation+// sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/TableCatalog.java++package org.apache.gravitino.rel;++import javax.annotation.Nullable;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.annotation.Evolving;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.exceptions.NoSuchTableException;++/**+ * Optional table operations that resolve source identity without loading columns or constraints.+ */+@Evolving+public interface SupportsTableIdentifier extends TableCatalog {+ /**+ * Checks the live source table and reads its Gravitino string identifier property.+ *+ * <p>This must query the source, distinguish tables from views, and propagate source failures. A+ * missing identifier means an existing table without a Gravitino identifier, not a missing table.+ * Callers must still import unregistered tables through the ordinary load path.+ *+ * @param ident the table identifier+ * @return the source's Gravitino string identifier, or null if the existing table has none+ * @throws NoSuchTableException if the source table does not exist or is a view+ * @throws NoSuchSchemaException if the containing source schema does not exist+ */+ @Nullable+ String loadTableIdentifier(NameIdentifier ident)+ throws NoSuchTableException, NoSuchSchemaException;+}diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.javaindex 6502502278..6f8979dc2f 100644--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogOperations.java@@ -75,8 +75,8 @@ import org.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.SupportsTableIdentifier;import org.apache.gravitino.rel.Table;-import org.apache.gravitino.rel.TableCatalog;import org.apache.gravitino.rel.TableChange;import org.apache.gravitino.rel.View;import org.apache.gravitino.rel.ViewCatalog;@@ -98,7 +98,7 @@ import org.slf4j.LoggerFactory;/** Operations for interacting with an Apache Hive catalog in Apache Gravitino. */public class HiveCatalogOperations- implements CatalogOperations, SupportsSchemas, TableCatalog, ViewCatalog {+ implements CatalogOperations, SupportsSchemas, SupportsTableIdentifier, ViewCatalog {public static final Logger LOG = LoggerFactory.getLogger(HiveCatalogOperations.class);@@ -488,6 +488,18 @@ public class HiveCatalogOperationsreturn hiveTable;}+ /** {@inheritDoc} */+ @Override+ public String loadTableIdentifier(NameIdentifier tableIdent) {+ NameIdentifier schemaIdent = NameIdentifier.of(tableIdent.namespace().levels());+ try {+ return clientPool.run(+ c -> c.getTableIdentifier(catalogName, schemaIdent.name(), tableIdent.name()));+ } catch (InterruptedException e) {+ throw ExceptionMessages.wrap("Failed to check Hive table " + tableIdent.name(), e);+ }+ }+private HiveTableHandle loadHiveTable(NameIdentifier tableIdent) {NameIdentifier schemaIdent = NameIdentifier.of(tableIdent.namespace().levels());diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.javaindex d92e55d44c..f20028ccc2 100644--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java@@ -98,6 +98,26 @@ import org.junit.jupiter.api.Test;import org.mockito.ArgumentCaptor;class TestHiveCatalogOperations {+ @Test+ void testTableIdentifierProbeAvoidsFullTableLoad() throws Exception {+ HiveCatalogOperations op = new HiveCatalogOperations();+ op.initialize(Maps.newHashMap(), null, HIVE_PROPERTIES_METADATA);+ CachedClientPool pool = mock(CachedClientPool.class);+ HiveClient client = mock(HiveClient.class);+ when(pool.run(any()))+ .thenAnswer(+ invocation -> {+ ClientPool.Action<?, HiveClient, ?> action = invocation.getArgument(0);+ return action.run(client);+ });+ op.clientPool = pool;+ when(client.getTableIdentifier(anyString(), eq("db"), eq("t"))).thenReturn("source-identifier");+ NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "db", "t");+ Assertions.assertEquals("source-identifier", op.loadTableIdentifier(ident));+ verify(client).getTableIdentifier(anyString(), eq("db"), eq("t"));+ verify(client, never()).getTable(anyString(), anyString(), anyString());+ }+@Testvoid testDerivedSchemaMetadataAltersPreserveMarkerAndRejectColumnChanges() throws Exception {HiveCatalogOperations op = new HiveCatalogOperations();diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClient.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClient.javaindex ad5fe84a03..1386f45c16 100644--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClient.java+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClient.java@@ -19,6 +19,8 @@package org.apache.gravitino.hive.client;import java.util.List;+import javax.annotation.Nullable;+import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.hive.HivePartition;import org.apache.gravitino.hive.HiveSchema;import org.apache.gravitino.hive.HiveTable;@@ -51,6 +53,18 @@ public interface HiveClient extends AutoCloseable {HiveTable getTable(String catalogName, String databaseName, String tableName);+ /**+ * Reads the live table's Gravitino string identifier without loading its columns or constraints.+ *+ * @param catalogName the Hive catalog name+ * @param databaseName the database name+ * @param tableName the table name+ * @return the identifier property, or null if the existing table has no identifier+ * @throws NoSuchTableException if the object is absent or a view+ */+ @Nullable+ String getTableIdentifier(String catalogName, String databaseName, String tableName);+default void alterTable(String catalogName, String databaseName, String tableName, HiveTable alteredHiveTable) {alterTable(catalogName, databaseName, tableName, alteredHiveTable, false);diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientImpl.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientImpl.javaindex 7378ce3a79..250a8e9f07 100644--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientImpl.java+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveClientImpl.java@@ -111,6 +111,12 @@ public class HiveClientImpl implements HiveClient {return shim.getTable(catalogName, databaseName, tableName);}+ /** {@inheritDoc} */+ @Override+ public String getTableIdentifier(String catalogName, String databaseName, String tableName) {+ return shim.getTableIdentifier(catalogName, databaseName, tableName);+ }+@Overridepublic void alterTable(String catalogName,diff --git a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShim.java b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShim.javaindex 1693d8cce9..db99e04c18 100644--- a/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShim.java+++ b/catalogs/hive-metastore-common/src/main/java/org/apache/gravitino/hive/client/HiveShim.java@@ -18,6 +18,7 @@*/package org.apache.gravitino.hive.client;+import static org.apache.gravitino.StringIdentifier.ID_KEY;import static org.apache.gravitino.hive.client.Util.updateConfigurationFromProperties;import java.lang.reflect.Constructor;@@ -27,6 +28,7 @@ import java.util.Collections;import java.util.List;import java.util.Properties;import javax.annotation.Nullable;+import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.hive.HivePartition;import org.apache.gravitino.hive.HiveSchema;import org.apache.gravitino.hive.HiveTable;@@ -185,6 +187,40 @@ public abstract class HiveShim {}}+ /**+ * Reads the identifier using a single metastore table request, without resolving the schema.+ *+ * @param catalogName the Hive catalog name+ * @param databaseName the database name+ * @param tableName the table name+ * @return the identifier property, or null if the existing table has none+ */+ @Nullable+ public String getTableIdentifier(String catalogName, String databaseName, String tableName) {+ Table table;+ try {+ table = client.getTable(databaseName, tableName);+ } catch (Exception e) {+ throw HiveExceptionConverter.toGravitinoException(e, ExceptionTarget.table(tableName));+ }+ return tableIdentifier(table, tableName);+ }++ /**+ * Extracts the identifier from a table and rejects views, as the table load path does.+ *+ * @param table the live metastore table+ * @param tableName the requested table name+ * @return the identifier property, or null if absent+ */+ @Nullable+ protected String tableIdentifier(Table table, String tableName) {+ if (TableType.VIRTUAL_VIEW.name().equalsIgnoreCase(table.getTableType())) {+ throw new NoSuchTableException("Table %s is a view, not a table", tableName);+ }+ return table.getParameters() == null ? null : table.getParameters().get(ID_KEY);+ }+public void alterTable(String catalogName,String databaseName,diff --git a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveShimGetTable.java b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveShimGetTable.javaindex 4f30999cfc..87ec42fb59 100644--- a/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveShimGetTable.java+++ b/catalogs/hive-metastore-common/src/test/java/org/apache/gravitino/hive/client/TestHiveShimGetTable.java@@ -19,10 +19,13 @@package org.apache.gravitino.hive.client;+import static org.apache.gravitino.StringIdentifier.ID_KEY;import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoMoreInteractions;import static org.mockito.Mockito.when;import java.time.Instant;@@ -68,6 +71,37 @@ class TestHiveShimGetTable {}}+ @Test+ void testIdentifierProbeDoesNotResolveColumns() throws Exception {+ MockHiveShim shim = new MockHiveShim();+ IMetaStoreClient client = shim.metaStoreClient();+ Table table = new Table();+ table.setTableType("EXTERNAL_TABLE");+ table.setParameters(Map.of(ID_KEY, "source-identifier"));+ // No storage descriptor: the probe must not convert columns or initialize a SerDe.+ when(client.getTable(DB, TABLE)).thenReturn(table);+ Assertions.assertEquals("source-identifier", shim.getTableIdentifier(CATALOG, DB, TABLE));+ verify(client).getTable(DB, TABLE);+ verifyNoMoreInteractions(client);+ table.setParameters(null);+ Assertions.assertNull(shim.getTableIdentifier(CATALOG, DB, TABLE));+ table.setTableType("VIRTUAL_VIEW");+ Assertions.assertThrows(+ NoSuchTableException.class, () -> shim.getTableIdentifier(CATALOG, DB, TABLE));+ }++ @Test+ void testIdentifierProbePropagatesMetastoreFailures() throws Exception {+ MockHiveShim shim = new MockHiveShim();+ IMetaStoreClient client = shim.metaStoreClient();+ when(client.getTable(DB, TABLE)).thenThrow(new NoSuchObjectException("missing"));+ Assertions.assertThrows(+ NoSuchTableException.class, () -> shim.getTableIdentifier(CATALOG, DB, TABLE));+ doThrow(new MetaException("unavailable")).when(client).getTable(DB, TABLE);+ Assertions.assertThrows(+ GravitinoRuntimeException.class, () -> shim.getTableIdentifier(CATALOG, DB, TABLE));+ }+@Testvoid testGetTableSkipsFieldResolutionForRegularColumns() throws Exception {MockHiveShim shim = new MockHiveShim();diff --git a/catalogs/hive-metastore3-libs/src/main/java/org/apache/gravitino/hive/client/hive3/HiveShimV3.java b/catalogs/hive-metastore3-libs/src/main/java/org/apache/gravitino/hive/client/hive3/HiveShimV3.javaindex 8b45e37ba0..b974f7bc63 100644--- a/catalogs/hive-metastore3-libs/src/main/java/org/apache/gravitino/hive/client/hive3/HiveShimV3.java+++ b/catalogs/hive-metastore3-libs/src/main/java/org/apache/gravitino/hive/client/hive3/HiveShimV3.java@@ -170,6 +170,16 @@ public class HiveShimV3 extends HiveShim {return converted;}+ /** {@inheritDoc} */+ @Override+ public String getTableIdentifier(String catalogName, String databaseName, String tableName) {+ Table table =+ invoke(+ ExceptionTarget.table(tableName),+ () -> client.getTable(catalogName, databaseName, tableName));+ return tableIdentifier(table, tableName);+ }+/** {@inheritDoc} */@Overrideprotected List<FieldSchema> getFields(String catalogName, String databaseName, String tableName)diff --git a/catalogs/hive-metastore3-libs/src/test/java/org/apache/gravitino/hive/client/hive3/TestHiveShimV3.java b/catalogs/hive-metastore3-libs/src/test/java/org/apache/gravitino/hive/client/hive3/TestHiveShimV3.javaindex 03144f1538..abb9895377 100644--- a/catalogs/hive-metastore3-libs/src/test/java/org/apache/gravitino/hive/client/hive3/TestHiveShimV3.java+++ b/catalogs/hive-metastore3-libs/src/test/java/org/apache/gravitino/hive/client/hive3/TestHiveShimV3.java@@ -19,6 +19,7 @@package org.apache.gravitino.hive.client.hive3;+import static org.apache.gravitino.StringIdentifier.ID_KEY;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertThrows;@@ -31,6 +32,7 @@ import static org.mockito.Mockito.inOrder;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoMoreInteractions;import static org.mockito.Mockito.when;import java.time.Instant;@@ -41,6 +43,7 @@ import java.util.Map;import java.util.Properties;import org.apache.gravitino.catalog.hive.HiveConstants;import org.apache.gravitino.exceptions.GravitinoRuntimeException;+import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.hive.HiveTable;import org.apache.gravitino.hive.converter.HiveTableConverter;import org.apache.gravitino.meta.AuditInfo;@@ -56,6 +59,7 @@ import org.apache.hadoop.hive.metastore.api.NotNullConstraintsRequest;import org.apache.hadoop.hive.metastore.api.SQLDefaultConstraint;import org.apache.hadoop.hive.metastore.api.SQLNotNullConstraint;import org.apache.hadoop.hive.metastore.api.Table;+import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;import org.mockito.ArgumentCaptor;import org.mockito.InOrder;@@ -93,6 +97,25 @@ class TestHiveShimV3 {}}+ @Test+ void testIdentifierProbeUsesCatalogAwareGetTableOnly() throws Exception {+ MockHiveShimV3 shim = new MockHiveShimV3();+ IMetaStoreClient client = shim.metaStoreClient();+ Table table = new Table();+ table.setTableType("MANAGED_TABLE");+ table.setParameters(Map.of(ID_KEY, "source-identifier"));+ when(client.getTable(CATALOG, DB, TABLE)).thenReturn(table);+ Assertions.assertEquals("source-identifier", shim.getTableIdentifier(CATALOG, DB, TABLE));+ verify(client).getTable(CATALOG, DB, TABLE);+ // In particular, no column constraint or SerDe field RPC is allowed.+ verifyNoMoreInteractions(client);+ table.setParameters(null);+ Assertions.assertNull(shim.getTableIdentifier(CATALOG, DB, TABLE));+ table.setTableType("VIRTUAL_VIEW");+ Assertions.assertThrows(+ NoSuchTableException.class, () -> shim.getTableIdentifier(CATALOG, DB, TABLE));+ }+private HiveTable testTable(Column... columns) {Map<String, String> properties = new HashMap<>();properties.put(HiveConstants.LOCATION, "hdfs://ns/warehouse/db.db/tbl");diff --git a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.javaindex dee8cd263c..9162e9b270 100644--- a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java@@ -71,6 +71,7 @@ import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.ColumnEntity;import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.SupportsTableIdentifier;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableCatalog;import org.apache.gravitino.rel.TableChange;@@ -145,12 +146,21 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab*/@Overridepublic boolean tableExists(NameIdentifier ident) {- boolean supportsTables =- doWithCatalog(- getCatalogIdentifier(ident),- wrapper -> wrapper.doWithCatalog(catalog -> catalog.ops() instanceof TableCatalog),- RuntimeException.class);- return supportsTables && TableDispatcher.super.tableExists(ident);+ if (!supportsTables(ident)) {+ return false;+ }+ try {+ Boolean exists =+ TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> probeImportedTable(ident));+ if (exists != null) {+ return exists;+ }+ } catch (NoSuchTableException | NoSuchSchemaException e) {+ return false;+ }+ // Cold tables, changed identifiers, managed catalogs and connectors without the optional+ // probe retain the load/import path, including its identity conflict checks.+ return TableDispatcher.super.tableExists(ident);}/**@@ -183,6 +193,9 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab*/@Overridepublic Table loadTable(NameIdentifier ident) throws NoSuchTableException {+ if (!supportsTables(ident)) {+ throw new NoSuchTableException("Catalog for table %s does not support tables", ident);+ }return loadAndImportTable(ident, AuditInfo.EMPTY);}@@ -540,6 +553,13 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab});}+ private boolean supportsTables(NameIdentifier ident) {+ return doWithCatalog(+ getCatalogIdentifier(ident),+ wrapper -> wrapper.doWithCatalog(catalog -> catalog.ops() instanceof TableCatalog),+ RuntimeException.class);+ }+private Namespace getNewNamespace(NameIdentifier tableIdent, TableChange... changes) {String schemaName = tableIdent.namespace().level(2);return Arrays.stream(changes)@@ -569,6 +589,43 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab}}+ @Nullable+ private Boolean probeImportedTable(NameIdentifier ident) {+ return doWithCatalog(+ getCatalogIdentifier(ident),+ catalog -> {+ if (isManagedEntity(catalog, Capability.Scope.TABLE)) {+ return null;+ }+ return catalog.doWithTableOps(+ ops -> {+ if (!(ops instanceof SupportsTableIdentifier)) {+ return null;+ }+ TableEntity stored = getEntity(ident, TABLE, TableEntity.class);+ if (stored == null) {+ return null;+ }+ String sourceId = ((SupportsTableIdentifier) ops).loadTableIdentifier(ident);+ if (sourceId == null) {+ // Sources without a persistent identifier use the same name-based identity as+ // loadTable.+ return true;+ }+ try {+ return StringIdentifier.fromString(sourceId).id() == stored.id()+ ? Boolean.TRUE+ : null;+ } catch (IllegalArgumentException e) {+ // Let the ordinary load path handle malformed source identifiers consistently.+ return null;+ }+ });+ },+ NoSuchTableException.class,+ NoSuchSchemaException.class);+ }+private Table loadAndImportTable(NameIdentifier ident, AuditInfo importAudit)throws NoSuchTableException {EntityCombinedTable entityCombinedTable =diff --git a/core/src/main/java/org/apache/gravitino/utils/MetadataObjectUtil.java b/core/src/main/java/org/apache/gravitino/utils/MetadataObjectUtil.javaindex 0f8a3827f9..6c18b53fd9 100644--- a/core/src/main/java/org/apache/gravitino/utils/MetadataObjectUtil.java+++ b/core/src/main/java/org/apache/gravitino/utils/MetadataObjectUtil.java@@ -44,6 +44,8 @@ import org.apache.gravitino.exceptions.NoSuchJobTemplateException;import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;import org.apache.gravitino.exceptions.NoSuchPolicyException;import org.apache.gravitino.exceptions.NoSuchRoleException;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.exceptions.NoSuchTagException;public class MetadataObjectUtil {@@ -278,7 +280,13 @@ public class MetadataObjectUtil {case COLUMN:NameIdentifierUtil.checkColumn(identifier);NameIdentifier tableIdent = NameIdentifier.of(identifier.namespace().levels());- check(env.internalTableDispatcher().tableExists(tableIdent), exceptionToThrowSupplier);+ try {+ // Column IDs must reflect source schema changes even when the table identity is+ // unchanged.+ env.internalTableDispatcher().loadTable(tableIdent);+ } catch (NoSuchTableException | NoSuchSchemaException e) {+ throw exceptionToThrowSupplier.get();+ }break;case TOPIC:@@ -370,7 +378,7 @@ public class MetadataObjectUtil {}/**- * Checks metadata objects, checking each distinct table only once for tables and their columns.+ * Checks metadata objects, probing each table and refreshing its columns at most once per call.** <p>Every object's identifier is validated. Successful table checks are shared only within this* call. Like {@link #checkMetadataObject(String, MetadataObject)}, this must be called outside@@ -382,6 +390,7 @@ public class MetadataObjectUtil {*/public static void checkMetadataObjects(String metalake, List<MetadataObject> objects) {Set<NameIdentifier> checkedTables = new HashSet<>();+ Set<NameIdentifier> refreshedTables = new HashSet<>();for (MetadataObject object : objects) {Preconditions.checkArgument(object != null, "metadataObject cannot be null");if (object.type() != MetadataObject.Type.TABLE@@ -399,7 +408,12 @@ public class MetadataObjectUtil {NameIdentifierUtil.checkTable(identifier);tableIdentifier = identifier;}- if (checkedTables.add(tableIdentifier)) {+ if (object.type() == MetadataObject.Type.COLUMN) {+ if (refreshedTables.add(tableIdentifier)) {+ checkMetadataObject(metalake, object);+ checkedTables.add(tableIdentifier);+ }+ } else if (checkedTables.add(tableIdentifier)) {checkMetadataObject(metalake, object);}}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestTableExistence.java b/core/src/test/java/org/apache/gravitino/catalog/TestTableExistence.javaindex 30ca4d1885..7c0b5aec67 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestTableExistence.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestTableExistence.java@@ -29,6 +29,7 @@ import static org.mockito.Mockito.spy;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import java.util.List;import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.MetadataObject;@@ -39,6 +40,8 @@ import org.apache.gravitino.connector.CatalogOperations;import org.apache.gravitino.connector.capability.Capability;import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;import org.apache.gravitino.exceptions.NoSuchTableException;+import org.apache.gravitino.lock.LockManager;+import org.apache.gravitino.lock.TreeLock;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableCatalog;import org.apache.gravitino.secret.SecretManager;@@ -98,19 +101,34 @@ class TestTableExistence {verify(dispatcher, never()).loadTable(any());}+ @Test+ void testUnsupportedCatalogLoadReturnsNotFound() {+ when(catalog.ops()).thenReturn(mock(CatalogOperations.class));+ Assertions.assertThrows(NoSuchTableException.class, () -> dispatcher.loadTable(IDENT));+ }+@Testvoid testSupportedCatalogStillLoadsAndImportsTables() {when(catalog.ops()).thenReturn(mock(TableCatalogOperations.class));- doReturn(mock(Table.class)).when(dispatcher).loadTable(IDENT);- Assertions.assertTrue(dispatcher.tableExists(IDENT));- verify(dispatcher).loadTable(IDENT);+ GravitinoEnv env = mock(GravitinoEnv.class);+ LockManager lockManager = mock(LockManager.class);+ when(env.lockManager()).thenReturn(lockManager);+ when(lockManager.createTreeLock(IDENT)).thenReturn(mock(TreeLock.class));+ try (MockedStatic<GravitinoEnv> mocked = mockStatic(GravitinoEnv.class)) {+ mocked.when(GravitinoEnv::getInstance).thenReturn(env);+ doReturn(mock(Table.class)).when(dispatcher).loadTable(IDENT);+ Assertions.assertTrue(dispatcher.tableExists(IDENT));+ verify(dispatcher).loadTable(IDENT);- doThrow(new NoSuchTableException("missing")).when(dispatcher).loadTable(IDENT);- Assertions.assertFalse(dispatcher.tableExists(IDENT));+ doThrow(new NoSuchTableException("missing")).when(dispatcher).loadTable(IDENT);+ Assertions.assertFalse(dispatcher.tableExists(IDENT));- doThrow(new UnsupportedOperationException("backend failure")).when(dispatcher).loadTable(IDENT);- Assertions.assertThrows(- UnsupportedOperationException.class, () -> dispatcher.tableExists(IDENT));+ doThrow(new UnsupportedOperationException("backend failure"))+ .when(dispatcher)+ .loadTable(IDENT);+ Assertions.assertThrows(+ UnsupportedOperationException.class, () -> dispatcher.tableExists(IDENT));+ }}@Test@@ -131,7 +149,26 @@ class TestTableExistence {() -> MetadataObjectUtil.checkMetadataObject("ml", object));}}- verify(dispatcher, never()).loadTable(any());+ verify(dispatcher).loadTable(IDENT);+ }++ @Test+ void testNormalizedColumnBatchesForUnsupportedCatalogReturnNotFound() {+ when(catalog.ops()).thenReturn(mock(CatalogOperations.class));+ TableNormalizeDispatcher normalized = new TableNormalizeDispatcher(dispatcher, manager);+ GravitinoEnv env = mock(GravitinoEnv.class);+ when(env.internalTableDispatcher()).thenReturn(normalized);+ MetadataObject table = MetadataObjects.parse("cat.s.t", MetadataObject.Type.TABLE);+ MetadataObject column = MetadataObjects.parse("cat.s.t.c", MetadataObject.Type.COLUMN);+ try (MockedStatic<GravitinoEnv> mocked = mockStatic(GravitinoEnv.class)) {+ mocked.when(GravitinoEnv::getInstance).thenReturn(env);+ for (List<MetadataObject> objects :+ List.of(List.of(column), List.of(table, column), List.of(column, table))) {+ Assertions.assertThrows(+ NoSuchMetadataObjectException.class,+ () -> MetadataObjectUtil.checkMetadataObjects("ml", objects));+ }+ }}private interface TableCatalogOperations extends CatalogOperations, TableCatalog {}diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.javaindex a755eaa3d5..0de3ab7274 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java@@ -25,6 +25,7 @@ import static org.apache.gravitino.Entity.EntityType.SCHEMA;import static org.apache.gravitino.Entity.EntityType.TABLE;import static org.apache.gravitino.StringIdentifier.ID_KEY;import static org.apache.gravitino.TestBasePropertiesMetadata.COMMENT_KEY;+import static org.mockito.AdditionalAnswers.delegatesTo;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyBoolean;import static org.mockito.ArgumentMatchers.eq;@@ -39,6 +40,7 @@ import static org.mockito.Mockito.spy;import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.withSettings;import com.google.common.collect.ImmutableMap;import java.io.IOException;@@ -67,6 +69,8 @@ import org.apache.gravitino.Entity;import org.apache.gravitino.EntityAlreadyExistsException;import org.apache.gravitino.EntityFieldLimits;import org.apache.gravitino.GravitinoEnv;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.MetadataObjects;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.StringIdentifier;@@ -95,6 +99,7 @@ import org.apache.gravitino.meta.ColumnEntity;import org.apache.gravitino.meta.SchemaEntity;import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.SupportsTableIdentifier;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableChange;import org.apache.gravitino.rel.expressions.Expression;@@ -111,6 +116,7 @@ import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.po.ColumnPO;import org.apache.gravitino.storage.relational.po.TablePO;import org.apache.gravitino.storage.relational.utils.POConverters;+import org.apache.gravitino.utils.MetadataObjectUtil;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;@@ -123,6 +129,161 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {static TableOperationDispatcher tableOperationDispatcher;static SchemaOperationDispatcher schemaOperationDispatcher;+ /**+ * Existence checks keep live-source validation and import fallbacks without refreshing columns.+ *+ * @param scenario the source identity or failure to exercise+ */+ @ParameterizedTest+ @ValueSource(+ strings = {+ "unchanged",+ "no-id",+ "missing",+ "missing-schema",+ "malformed",+ "changed",+ "cold",+ "failure"+ })+ public void testImportedTableExistenceUsesSourceIdentifier(String scenario) throws Exception {+ NameIdentifier schema =+ NameIdentifier.of(metalake, catalog, "table_existence_probe_" + scenario);+ Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");+ schemaOperationDispatcher.createSchema(schema, "comment", props);+ NameIdentifier ident = NameIdentifier.of(metalake, catalog, schema.name(), "t");+ createTable(ident);+ TestCatalog base =+ (TestCatalog)+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();+ Object original = base.ops();+ TestCatalogOperations source =+ mock(+ TestCatalogOperations.class,+ withSettings()+ .extraInterfaces(SupportsTableIdentifier.class)+ .defaultAnswer(delegatesTo(original)));+ Table table = ((TestCatalogOperations) original).loadTable(ident);+ doReturn(table).when(source).loadTable(ident);+ doReturn(table.properties().get(ID_KEY))+ .when((SupportsTableIdentifier) source)+ .loadTableIdentifier(ident);+ SupportsTableIdentifier probe = (SupportsTableIdentifier) source;+ if ("no-id".equals(scenario)) {+ doReturn(null).when(probe).loadTableIdentifier(ident);+ } else if ("missing".equals(scenario)) {+ doThrow(new NoSuchTableException("missing")).when(probe).loadTableIdentifier(ident);+ } else if ("missing-schema".equals(scenario)) {+ doThrow(new NoSuchSchemaException("missing schema")).when(probe).loadTableIdentifier(ident);+ } else if ("malformed".equals(scenario)) {+ doReturn("malformed").when(probe).loadTableIdentifier(ident);+ } else if ("changed".equals(scenario)) {+ doReturn(StringIdentifier.fromId(Long.MAX_VALUE).toString())+ .when(probe)+ .loadTableIdentifier(ident);+ } else if ("cold".equals(scenario)) {+ entityStore.delete(ident, TABLE);+ } else if ("failure".equals(scenario)) {+ doThrow(new IllegalStateException("metastore unavailable"))+ .when(probe)+ .loadTableIdentifier(ident);+ }+ FieldUtils.writeField(base, "ops", source, true);+ try {+ if ("failure".equals(scenario)) {+ Assertions.assertThrows(+ IllegalStateException.class, () -> tableOperationDispatcher.tableExists(ident));+ } else {+ Assertions.assertEquals(+ !scenario.startsWith("missing"), tableOperationDispatcher.tableExists(ident));+ }+ boolean fullLoad = List.of("cold", "malformed", "changed").contains(scenario);+ verify(source, times(fullLoad ? 1 : 0)).loadTable(ident);+ verify(probe, times("cold".equals(scenario) ? 0 : 1)).loadTableIdentifier(ident);+ if (!scenario.startsWith("missing") && !"failure".equals(scenario)) {+ Assertions.assertNotNull(entityStore.get(ident, TABLE, TableEntity.class));+ }+ } finally {+ FieldUtils.writeField(base, "ops", original, true);+ }+ }++ /**+ * Column validation refreshes external schema changes without disabling table probes.+ *+ * @param order the order of table and column validation+ * @throws Exception if setup or validation fails+ */+ @ParameterizedTest+ @ValueSource(strings = {"single", "table-first", "column-first"})+ public void testColumnValidationRefreshesExternalChanges(String order) throws Exception {+ NameIdentifier schema = NameIdentifier.of(metalake, catalog, "column_refresh_" + order);+ schemaOperationDispatcher.createSchema(schema, "comment", Map.of("k1", "v1", "k2", "v2"));+ NameIdentifier ident = NameIdentifier.of(metalake, catalog, schema.name(), "t");+ createTable(ident);+ TestCatalog base =+ (TestCatalog)+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();+ TestCatalogOperations original = (TestCatalogOperations) base.ops();+ TestCatalogOperations source =+ mock(+ TestCatalogOperations.class,+ withSettings()+ .extraInterfaces(SupportsTableIdentifier.class)+ .defaultAnswer(delegatesTo(original)));+ doReturn(original.loadTable(ident).properties().get(ID_KEY))+ .when((SupportsTableIdentifier) source)+ .loadTableIdentifier(ident);+ MetadataObject table =+ MetadataObjects.of(catalog + "." + schema.name(), "t", MetadataObject.Type.TABLE);+ MetadataObject column =+ MetadataObjects.of(table.fullName(), "external", MetadataObject.Type.COLUMN);+ List<MetadataObject> batch =+ "table-first".equals(order)+ ? List.of(table, column, column)+ : List.of(column, column, table);+ GravitinoEnv env = GravitinoEnv.getInstance();+ Object previous = FieldUtils.readField(env, "internalTableDispatcher", true);+ FieldUtils.writeField(base, "ops", source, true);+ FieldUtils.writeField(env, "internalTableDispatcher", tableOperationDispatcher, true);+ try {+ original.alterTable(+ ident, TableChange.addColumn(new String[] {"external"}, Types.StringType.get()));+ Assertions.assertTrue(tableOperationDispatcher.tableExists(ident));+ Assertions.assertTrue(+ entityStore.get(ident, TABLE, TableEntity.class).columns().stream()+ .noneMatch(c -> c.name().equals("external")));+ verify(source, never()).loadTable(ident);+ clearInvocations(source);+ if ("single".equals(order)) {+ MetadataObjectUtil.checkMetadataObject(metalake, column);+ } else {+ MetadataObjectUtil.checkMetadataObjects(metalake, batch);+ }+ ColumnEntity added =+ entityStore.get(ident, TABLE, TableEntity.class).columns().stream()+ .filter(c -> c.name().equals("external"))+ .findFirst()+ .orElseThrow();+ Assertions.assertTrue(added.id() > 0);+ verify(source, times(1)).loadTable(ident);+ original.alterTable(ident, TableChange.deleteColumn(new String[] {"external"}, false));+ clearInvocations(source);+ if ("single".equals(order)) {+ MetadataObjectUtil.checkMetadataObject(metalake, column);+ } else {+ MetadataObjectUtil.checkMetadataObjects(metalake, batch);+ }+ Assertions.assertTrue(+ entityStore.get(ident, TABLE, TableEntity.class).columns().stream()+ .noneMatch(c -> c.name().equals("external")));+ verify(source, times(1)).loadTable(ident);+ } finally {+ FieldUtils.writeField(base, "ops", original, true);+ FieldUtils.writeField(env, "internalTableDispatcher", previous, true);+ }+ }+@BeforeAllpublic static void initialize() throws IOException, IllegalAccessException {schemaOperationDispatcher =diff --git a/core/src/test/java/org/apache/gravitino/utils/TestMetadataObjectUtil.java b/core/src/test/java/org/apache/gravitino/utils/TestMetadataObjectUtil.javaindex ae6bb9356a..9b9e03c286 100644--- a/core/src/test/java/org/apache/gravitino/utils/TestMetadataObjectUtil.java+++ b/core/src/test/java/org/apache/gravitino/utils/TestMetadataObjectUtil.java@@ -47,6 +47,8 @@ import org.apache.gravitino.catalog.TopicDispatcher;import org.apache.gravitino.catalog.ViewDispatcher;import org.apache.gravitino.exceptions.IllegalNamespaceException;import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.job.JobOperationDispatcher;import org.apache.gravitino.metalake.MetalakeDispatcher;import org.apache.gravitino.policy.PolicyDispatcher;@@ -376,7 +378,8 @@ public class TestMetadataObjectUtil {verify(catalogDispatcher).catalogExists(catalogIdent);verify(schemaDispatcher).schemaExists(schemaIdent);verify(filesetDispatcher).filesetExists(filesetIdent);- verify(tableDispatcher, times(2)).tableExists(tableIdent);+ verify(tableDispatcher).tableExists(tableIdent);+ verify(tableDispatcher).loadTable(tableIdent);verify(topicDispatcher).topicExists(topicIdent);verify(modelDispatcher).modelExists(modelIdent);verify(functionDispatcher).functionExists(functionIdent);@@ -407,9 +410,10 @@ public class TestMetadataObjectUtil {MetadataObjectUtil.checkMetadataObjects("metalake", List.of(table, first, second, table));verify(dispatcher, times(1)).tableExists(tableIdentifier);MetadataObjectUtil.checkMetadataObjects("metalake", List.of(first, second, table));- verify(dispatcher, times(2)).tableExists(tableIdentifier);+ verify(dispatcher, times(1)).tableExists(tableIdentifier);+ verify(dispatcher, times(2)).loadTable(tableIdentifier);- when(dispatcher.tableExists(tableIdentifier)).thenReturn(false);+ when(dispatcher.loadTable(tableIdentifier)).thenThrow(new NoSuchTableException("missing"));NoSuchMetadataObjectException exception =Assertions.assertThrows(NoSuchMetadataObjectException.class,@@ -417,7 +421,8 @@ public class TestMetadataObjectUtil {Assertions.assertEquals("Metadata object catalog.schema.table.first type COLUMN doesn't exist",exception.getMessage());- verify(dispatcher, times(3)).tableExists(tableIdentifier);+ verify(dispatcher, times(1)).tableExists(tableIdentifier);+ verify(dispatcher, times(3)).loadTable(tableIdentifier);}}@@ -435,12 +440,42 @@ public class TestMetadataObjectUtil {MetadataObjects.of("catalog.schema.table", "first", MetadataObject.Type.COLUMN),MetadataObjects.of("catalog.other.table", "second", MetadataObject.Type.COLUMN),MetadataObjects.of("other.schema", "table", MetadataObject.Type.TABLE)));- verify(dispatcher).tableExists(NameIdentifier.of("metalake", "catalog", "schema", "table"));- verify(dispatcher).tableExists(NameIdentifier.of("metalake", "catalog", "other", "table"));+ verify(dispatcher).loadTable(NameIdentifier.of("metalake", "catalog", "schema", "table"));+ verify(dispatcher).loadTable(NameIdentifier.of("metalake", "catalog", "other", "table"));verify(dispatcher).tableExists(NameIdentifier.of("metalake", "other", "schema", "table"));}}+ @Test+ void testColumnRefreshPreservesMissingObjectAndSourceFailureBehavior() {+ GravitinoEnv env = mock(GravitinoEnv.class);+ TableDispatcher dispatcher = mock(TableDispatcher.class);+ when(env.internalTableDispatcher()).thenReturn(dispatcher);+ NameIdentifier ident = NameIdentifier.of("metalake", "catalog", "schema", "table");+ MetadataObject column =+ MetadataObjects.of("catalog.schema.table", "column", MetadataObject.Type.COLUMN);+ when(dispatcher.loadTable(ident))+ .thenThrow(new NoSuchTableException("missing table"))+ .thenThrow(new NoSuchSchemaException("missing schema"))+ .thenThrow(new IllegalStateException("source unavailable"));+ try (MockedStatic<GravitinoEnv> mockedEnv = mockStatic(GravitinoEnv.class)) {+ mockedEnv.when(GravitinoEnv::getInstance).thenReturn(env);+ for (int i = 0; i < 2; i++) {+ NoSuchMetadataObjectException failure =+ Assertions.assertThrows(+ NoSuchMetadataObjectException.class,+ () -> MetadataObjectUtil.checkMetadataObject("metalake", column));+ Assertions.assertEquals(+ "Metadata object catalog.schema.table.column type COLUMN doesn't exist",+ failure.getMessage());+ }+ Assertions.assertThrows(+ IllegalStateException.class,+ () -> MetadataObjectUtil.checkMetadataObject("metalake", column));+ verify(dispatcher, never()).tableExists(any());+ }+ }+@Testvoid testBatchStillChecksNonTableObjects() {GravitinoEnv env = mock(GravitinoEnv.class);