Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#14499] fix(core): harden catalog metadata registration and JDBC support (#14508)

Qi Yu3f18d9dfa62f
diff --git a/api/src/main/java/org/apache/gravitino/SupportsSchemas.java b/api/src/main/java/org/apache/gravitino/SupportsSchemas.java
index 2da71814ba..333fb4c48c 100644
--- a/api/src/main/java/org/apache/gravitino/SupportsSchemas.java
+++ b/api/src/main/java/org/apache/gravitino/SupportsSchemas.java
@@ -100,6 +100,12 @@ public interface SupportsSchemas {
*
* <p>Delegates to {@link #createSchema(String, String, Map, Map, Map)} with empty secret maps.
*
+ * <p>A failure does not guarantee that the underlying catalog object was not created. In
+ * particular, source schema creation can succeed before Gravitino registration fails. Resolve the
+ * reported error, verify the source identity, and call {@link #loadSchema(String)} to import it
+ * instead of repeating creation. An existing Gravitino registration must be reconciled first;
+ * creation never proves that an older source identity was deleted.
+ *
* @param schemaName The name of the schema.
* @param comment The comment of the schema.
* @param properties The properties of the schema.
@@ -119,6 +125,12 @@ public interface SupportsSchemas {
* <p>The default implementation rejects create-time secrets. Implementations that support secrets
* must override this method.
*
+ * <p>A failure does not guarantee that the underlying catalog object was not created. In
+ * particular, source schema creation can succeed before Gravitino registration fails. Resolve the
+ * reported error, verify the source identity, and call {@link #loadSchema(String)} to import it
+ * instead of repeating creation. An existing Gravitino registration must be reconciled first;
+ * creation never proves that an older source identity was deleted.
+ *
* @param schemaName The name of the schema.
* @param comment The comment of the schema.
* @param properties The properties of the schema.
diff --git a/api/src/main/java/org/apache/gravitino/rel/TableCatalog.java b/api/src/main/java/org/apache/gravitino/rel/TableCatalog.java
index b20e1676fc..12741b58da 100644
--- a/api/src/main/java/org/apache/gravitino/rel/TableCatalog.java
+++ b/api/src/main/java/org/apache/gravitino/rel/TableCatalog.java
@@ -59,6 +59,7 @@ public interface TableCatalog {
* @param ident A table identifier.
* @return The table metadata.
* @throws NoSuchTableException If the table does not exist.
+ * @throws NoSuchSchemaException If the containing schema does not exist.
*/
Table loadTable(NameIdentifier ident) throws NoSuchTableException;
@@ -73,6 +74,7 @@ public interface TableCatalog {
* @param requiredPrivilegeNames The required privilege names to access the table.
* @return The table metadata.
* @throws NoSuchTableException If the table does not exist.
+ * @throws NoSuchSchemaException If the containing schema does not exist.
* @throws UnsupportedOperationException If the catalog does not support loading a table with
* required privileges.
*/
@@ -91,7 +93,7 @@ public interface TableCatalog {
default boolean tableExists(NameIdentifier ident) {
try {
return loadTable(ident) != null;
- } catch (NoSuchTableException e) {
+ } catch (NoSuchTableException | NoSuchSchemaException e) {
return false;
}
}
@@ -103,6 +105,11 @@ public interface TableCatalog {
* need the table with default values applied, use the {@link #loadTable(NameIdentifier)} method
* after creation.
*
+ * <p>A failure does not guarantee that the underlying catalog object was not created. In
+ * particular, source table creation can succeed before Gravitino registration fails. Resolve the
+ * reported error, verify the source identity, and call {@link #loadTable(NameIdentifier)} to
+ * import it instead of repeating creation. Creation is not automatically replayed.
+ *
* @param ident A table identifier.
* @param columns The columns of the new table.
* @param comment The table comment.
@@ -127,6 +134,11 @@ public interface TableCatalog {
/**
* Create a table in the catalog.
*
+ * <p>A failure does not guarantee that the underlying catalog object was not created. In
+ * particular, source table creation can succeed before Gravitino registration fails. Resolve the
+ * reported error, verify the source identity, and call {@link #loadTable(NameIdentifier)} to
+ * import it instead of repeating creation. Creation is not automatically replayed.
+ *
* @param ident A table identifier.
* @param columns The columns of the new table.
* @param comment The table comment.
@@ -150,6 +162,11 @@ public interface TableCatalog {
/**
* Create a table in the catalog.
*
+ * <p>A failure does not guarantee that the underlying catalog object was not created. In
+ * particular, source table creation can succeed before Gravitino registration fails. Resolve the
+ * reported error, verify the source identity, and call {@link #loadTable(NameIdentifier)} to
+ * import it instead of repeating creation. Creation is not automatically replayed.
+ *
* @param ident A table identifier.
* @param columns The columns of the new table.
* @param comment The table comment.
@@ -175,6 +192,11 @@ public interface TableCatalog {
/**
* Create a table in the catalog.
*
+ * <p>A failure does not guarantee that the underlying catalog object was not created. In
+ * particular, source table creation can succeed before Gravitino registration fails. Resolve the
+ * reported error, verify the source identity, and call {@link #loadTable(NameIdentifier)} to
+ * import it instead of repeating creation. Creation is not automatically replayed.
+ *
* @param ident A table identifier.
* @param columns The columns of the new table.
* @param comment The table comment.
@@ -198,6 +220,11 @@ public interface TableCatalog {
/**
* Create a table in the catalog.
*
+ * <p>A failure does not guarantee that the underlying catalog object was not created. In
+ * particular, source table creation can succeed before Gravitino registration fails. Resolve the
+ * reported error, verify the source identity, and call {@link #loadTable(NameIdentifier)} to
+ * import it instead of repeating creation. Creation is not automatically replayed.
+ *
* @param ident A table identifier.
* @param columns The columns of the new table.
* @param comment The table comment.
@@ -221,6 +248,11 @@ public interface TableCatalog {
/**
* Create a partitioned table in the catalog.
*
+ * <p>A failure does not guarantee that the underlying catalog object was not created. In
+ * particular, source table creation can succeed before Gravitino registration fails. Resolve the
+ * reported error, verify the source identity, and call {@link #loadTable(NameIdentifier)} to
+ * import it instead of repeating creation. Creation is not automatically replayed.
+ *
* @param ident A table identifier.
* @param columns The columns of the new table.
* @param comment The table comment.
@@ -255,6 +287,11 @@ public interface TableCatalog {
/**
* Create a table in the catalog.
*
+ * <p>A failure does not guarantee that the underlying catalog object was not created. In
+ * particular, source table creation can succeed before Gravitino registration fails. Resolve the
+ * reported error, verify the source identity, and call {@link #loadTable(NameIdentifier)} to
+ * import it instead of repeating creation. Creation is not automatically replayed.
+ *
* @param ident A table identifier.
* @param columns The columns of the new table.
* @param comment The table comment.
diff --git a/api/src/test/java/org/apache/gravitino/rel/TestTableCatalog.java b/api/src/test/java/org/apache/gravitino/rel/TestTableCatalog.java
index 50281dad13..09b94d3243 100644
--- a/api/src/test/java/org/apache/gravitino/rel/TestTableCatalog.java
+++ b/api/src/test/java/org/apache/gravitino/rel/TestTableCatalog.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.rel;
import com.google.common.collect.ImmutableSet;
import java.util.Map;
+import java.util.function.Function;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.authorization.Privilege;
@@ -35,6 +36,10 @@ import org.junit.jupiter.api.Test;
public class TestTableCatalog {
private static TableCatalog minimalCatalog() {
+ return minimalCatalog(ident -> null);
+ }
+
+ private static TableCatalog minimalCatalog(Function<NameIdentifier, Table> loader) {
return new TableCatalog() {
@Override
public NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {
@@ -43,7 +48,7 @@ public class TestTableCatalog {
@Override
public Table loadTable(NameIdentifier ident) throws NoSuchTableException {
- return null;
+ return loader.apply(ident);
}
@Override
@@ -72,6 +77,32 @@ public class TestTableCatalog {
};
}
+ @Test
+ void testTableExistsReturnsFalseForMissingSchemaOrTable() {
+ NameIdentifier ident = NameIdentifier.of("schema", "table");
+ TableCatalog missingSchema =
+ minimalCatalog(
+ ignored -> {
+ throw new NoSuchSchemaException("schema missing");
+ });
+ TableCatalog missingTable =
+ minimalCatalog(
+ ignored -> {
+ throw new NoSuchTableException("table missing");
+ });
+ Assertions.assertFalse(missingSchema.tableExists(ident));
+ Assertions.assertFalse(missingTable.tableExists(ident));
+ IllegalStateException failure = new IllegalStateException("backend unavailable");
+ TableCatalog unavailable =
+ minimalCatalog(
+ ignored -> {
+ throw failure;
+ });
+ Assertions.assertSame(
+ failure,
+ Assertions.assertThrows(IllegalStateException.class, () -> unavailable.tableExists(ident)));
+ }
+
@Test
void testLoadTableWithRequiredPrivilegesFailsClosedByDefault() {
TableCatalog catalog = minimalCatalog();
diff --git a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/operation/JdbcTableOperations.java b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/operation/JdbcTableOperations.java
index e5ea76112f..4490c3c0d9 100644
--- a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/operation/JdbcTableOperations.java
+++ b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/operation/JdbcTableOperations.java
@@ -35,9 +35,11 @@ import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
+import java.util.function.BiConsumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import javax.annotation.Nullable;
import javax.sql.DataSource;
import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.catalog.jdbc.JdbcColumn;
@@ -282,6 +284,28 @@ public abstract class JdbcTableOperations implements TableOperation {
@Override
public JdbcTable load(String databaseName, String tableName) throws NoSuchTableException {
+ return load(databaseName, tableName, null);
+ }
+
+ /**
+ * Loads JDBC metadata, optionally enriching the builder from one caller-owned metadata snapshot.
+ * The enricher runs while the JDBC connection is open and is never retained between requests. It
+ * replaces the partitioning, properties and field-correction hooks; JDBC columns, indexes and
+ * distribution are still loaded normally. It may overwrite builder fields with snapshot data. The
+ * callback must not close or retain the borrowed connection. Runtime failures propagate, and the
+ * connection is closed before they reach the caller.
+ *
+ * @param databaseName database name
+ * @param tableName table name
+ * @param metadataEnricher replacement for partitioning, properties and field correction, or null
+ * to use the standard JDBC hooks
+ * @return loaded table
+ * @throws NoSuchTableException if the table is absent
+ */
+ protected JdbcTable load(
+ String databaseName,
+ String tableName,
+ @Nullable BiConsumer<Connection, JdbcTable.Builder> metadataEnricher) {
// We should handle case sensitivity and wild card issue in some catalog tables, take MySQL
// tables, for example.
// 1. MySQL will get table 'a_b' and 'A_B' when we query 'a_b' in a case-insensitive charset
@@ -314,20 +338,17 @@ public abstract class JdbcTableOperations implements TableOperation {
List<Index> indexes = getIndexes(connection, databaseName, tableName);
jdbcTableBuilder.withIndexes(indexes.toArray(new Index[0]));
- // 4.Get partitioning
- Transform[] tablePartitioning = getTablePartitioning(connection, databaseName, tableName);
- jdbcTableBuilder.withPartitioning(tablePartitioning);
-
- // 5.Get distribution information
- Distribution distribution = getDistributionInfo(connection, databaseName, tableName);
- jdbcTableBuilder.withDistribution(distribution);
-
- // 6.Get table properties
- Map<String, String> tableProperties = getTableProperties(connection, tableName);
- jdbcTableBuilder.withProperties(tableProperties);
-
- // 7.Leave the information to the bottom layer to append the table
- correctJdbcTableFields(connection, databaseName, tableName, jdbcTableBuilder);
+ if (metadataEnricher == null) {
+ jdbcTableBuilder.withPartitioning(
+ getTablePartitioning(connection, databaseName, tableName));
+ }
+ jdbcTableBuilder.withDistribution(getDistributionInfo(connection, databaseName, tableName));
+ if (metadataEnricher == null) {
+ jdbcTableBuilder.withProperties(getTableProperties(connection, tableName));
+ correctJdbcTableFields(connection, databaseName, tableName, jdbcTableBuilder);
+ } else {
+ metadataEnricher.accept(connection, jdbcTableBuilder);
+ }
return jdbcTableBuilder.withTableOperation(this).build();
} catch (SQLException e) {
@@ -403,6 +424,7 @@ public abstract class JdbcTableOperations implements TableOperation {
LOG.info("No changes to alter table {} from database {}", tableName, databaseName);
return;
}
+ validateAlterTableTarget(databaseName, tableName);
try (Connection connection = getConnection(databaseName)) {
JdbcConnectorUtils.executeUpdate(connection, sql);
LOG.info("Alter table {} from database {}", tableName, databaseName);
@@ -411,6 +433,19 @@ public abstract class JdbcTableOperations implements TableOperation {
}
}
+ /**
+ * Validates backend-specific target capabilities after SQL validation but before executing DDL.
+ *
+ * <p>The default implementation does nothing. Overrides should throw a runtime exception to
+ * reject the operation and must not perform DDL. The hook is not called for empty generated SQL
+ * and runs before borrowing the execution connection; SQL generation itself may have borrowed
+ * connections. This check is not atomic with an out-of-band target replacement.
+ *
+ * @param databaseName database name
+ * @param tableName table name
+ */
+ protected void validateAlterTableTarget(String databaseName, String tableName) {}
+
@Override
public boolean purge(String databaseName, String tableName) {
try {
diff --git a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/operation/TestJdbcTableOperations.java b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/operation/TestJdbcTableOperations.java
index 9fa0549001..98539de4f3 100644
--- a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/operation/TestJdbcTableOperations.java
+++ b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/operation/TestJdbcTableOperations.java
@@ -22,6 +22,9 @@ import com.google.common.collect.Maps;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
+import java.sql.Connection;
+import java.sql.Statement;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@@ -54,6 +57,7 @@ import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
public class TestJdbcTableOperations {
@@ -121,6 +125,129 @@ public class TestJdbcTableOperations {
Collections.emptyMap());
}
+ @Test
+ void testRequestLocalMetadataEnrichment() throws Exception {
+ String tableName = "snapshot_hooks";
+ JdbcTableOperations operations = Mockito.spy(JDBC_TABLE_OPERATIONS);
+ try (Connection setup = DATA_SOURCE.getConnection();
+ Statement statement = setup.createStatement()) {
+ statement.executeUpdate("CREATE TABLE " + tableName + " (id INTEGER)");
+ try {
+ List<Connection> borrowed = new ArrayList<>();
+ JdbcTable first =
+ operations.load(
+ DATABASE_NAME,
+ tableName,
+ (connection, builder) -> {
+ Assertions.assertFalse(Assertions.assertDoesNotThrow(connection::isClosed));
+ borrowed.add(connection);
+ builder.withProperties(Map.of("snapshot", "first"));
+ });
+ JdbcTable second =
+ operations.load(
+ DATABASE_NAME,
+ tableName,
+ (connection, builder) -> {
+ Assertions.assertFalse(Assertions.assertDoesNotThrow(connection::isClosed));
+ borrowed.add(connection);
+ builder.withProperties(Map.of("snapshot", "second"));
+ });
+ Assertions.assertEquals("first", first.properties().get("snapshot"));
+ Assertions.assertEquals("second", second.properties().get("snapshot"));
+ Assertions.assertEquals("id", first.columns()[0].name());
+ for (Connection connection : borrowed) {
+ Assertions.assertTrue(connection.isClosed());
+ }
+ Mockito.verify(operations, Mockito.never())
+ .getTablePartitioning(Mockito.any(), Mockito.anyString(), Mockito.anyString());
+ Mockito.verify(operations, Mockito.never())
+ .getTableProperties(Mockito.any(), Mockito.anyString());
+ Mockito.verify(operations, Mockito.never())
+ .correctJdbcTableFields(
+ Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any());
+ Mockito.verify(operations, Mockito.times(2))
+ .getDistributionInfo(Mockito.any(), Mockito.eq(DATABASE_NAME), Mockito.eq(tableName));
+ JdbcTable standard = operations.load(DATABASE_NAME, tableName);
+ Assertions.assertFalse(standard.properties().containsKey("snapshot"));
+ Mockito.verify(operations)
+ .getTablePartitioning(Mockito.any(), Mockito.eq(DATABASE_NAME), Mockito.eq(tableName));
+ Mockito.verify(operations).getTableProperties(Mockito.any(), Mockito.eq(tableName));
+ Mockito.verify(operations)
+ .correctJdbcTableFields(
+ Mockito.any(), Mockito.eq(DATABASE_NAME), Mockito.eq(tableName), Mockito.any());
+ } finally {
+ statement.executeUpdate("DROP TABLE " + tableName);
+ }
+ }
+ }
+
+ @Test
+ void testEnrichmentFailureClosesConnectionAndPreservesCause() throws Exception {
+ String tableName = "snapshot_failure";
+ try (Connection setup = DATA_SOURCE.getConnection();
+ Statement statement = setup.createStatement()) {
+ statement.executeUpdate("CREATE TABLE " + tableName + " (id INTEGER)");
+ try {
+ List<Connection> borrowed = new ArrayList<>();
+ IllegalStateException failure = new IllegalStateException("snapshot failed");
+ Assertions.assertSame(
+ failure,
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () ->
+ JDBC_TABLE_OPERATIONS.load(
+ DATABASE_NAME,
+ tableName,
+ (connection, builder) -> {
+ Assertions.assertFalse(
+ Assertions.assertDoesNotThrow(connection::isClosed));
+ borrowed.add(connection);
+ throw failure;
+ })));
+ Assertions.assertEquals(1, borrowed.size());
+ Assertions.assertTrue(borrowed.get(0).isClosed());
+ } finally {
+ statement.executeUpdate("DROP TABLE " + tableName);
+ }
+ }
+ }
+
+ @Test
+ void testTargetValidationAfterSqlValidationBeforeExecutionConnection() throws Exception {
+ JdbcTableOperations operations = Mockito.spy(new SqliteTableOperations());
+ DataSource source = Mockito.mock(DataSource.class);
+ operations.initialize(
+ source, EXCEPTION_CONVERTER, TYPE_CONVERTER, COLUMN_DEFAULT_VALUE_CONVERTER, Map.of());
+ TableChange change = TableChange.deleteColumn(new String[] {"id"}, false);
+ IllegalArgumentException invalid = new IllegalArgumentException("invalid local SQL");
+ Mockito.doThrow(invalid)
+ .when(operations)
+ .generateAlterTableSql(DATABASE_NAME, "target", change);
+ Assertions.assertSame(
+ invalid,
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> operations.alterTable(DATABASE_NAME, "target", change)));
+ Mockito.verify(operations, Mockito.never())
+ .validateAlterTableTarget(Mockito.anyString(), Mockito.anyString());
+ Mockito.doReturn("").when(operations).generateAlterTableSql(DATABASE_NAME, "target", change);
+ operations.alterTable(DATABASE_NAME, "target", change);
+ Mockito.verify(operations, Mockito.never())
+ .validateAlterTableTarget(Mockito.anyString(), Mockito.anyString());
+ Mockito.doReturn("ALTER TABLE target DROP COLUMN id")
+ .when(operations)
+ .generateAlterTableSql(DATABASE_NAME, "target", change);
+ IllegalStateException forbidden = new IllegalStateException("unsupported target kind");
+ Mockito.doThrow(forbidden).when(operations).validateAlterTableTarget(DATABASE_NAME, "target");
+ Assertions.assertSame(
+ forbidden,
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> operations.alterTable(DATABASE_NAME, "target", change)));
+ Mockito.verify(operations).validateAlterTableTarget(DATABASE_NAME, "target");
+ Mockito.verifyNoInteractions(source);
+ }
+
@Test
public void testOperationTable() {
String table1 = "table1";
diff --git a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java
index 8b920576e1..1990d66122 100644
--- a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java
+++ b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/integration/test/CatalogMysqlIT.java
@@ -1947,44 +1947,51 @@ public class CatalogMysqlIT extends BaseIT {
String sql = String.format("CREATE DATABASE `%s`", testSchemaName);
mysqlService.executeQuery(sql);
- Schema schema = catalog.asSchemas().loadSchema(testSchemaName);
- Assertions.assertEquals(testSchemaName, schema.name());
+ try {
+ Schema schema = catalog.asSchemas().loadSchema(testSchemaName);
+ Assertions.assertEquals(testSchemaName, schema.name());
- String[] schemaIdents = catalog.asSchemas().listSchemas();
- Assertions.assertTrue(Arrays.asList(schemaIdents).contains(testSchemaName));
+ String[] schemaIdents = catalog.asSchemas().listSchemas();
+ Assertions.assertTrue(Arrays.asList(schemaIdents).contains(testSchemaName));
- Exception exception =
- Assertions.assertThrows(
- SchemaAlreadyExistsException.class,
- () -> catalog.asSchemas().createSchema(testSchemaName, null, Collections.emptyMap()));
- Assertions.assertTrue(
- exception.getMessage().contains("Can't create database '//'; database exists"));
-
- Assertions.assertTrue(catalog.asSchemas().dropSchema(testSchemaName, false));
- Assertions.assertFalse(catalog.asSchemas().schemaExists(testSchemaName));
+ SchemaAlreadyExistsException exception =
+ Assertions.assertThrows(
+ SchemaAlreadyExistsException.class,
+ () -> catalog.asSchemas().createSchema(testSchemaName, null, Collections.emptyMap()));
+ // The registration preflight may reject this before MySQL executes CREATE DATABASE.
+ Assertions.assertTrue(
+ exception.getMessage().contains(testSchemaName), exception.getMessage());
- // test operate illegal table name from MySQL
- mysqlService.executeQuery(sql);
- String testTableName = "//";
- sql = String.format("CREATE TABLE `%s`.`%s` (id int)", testSchemaName, testTableName);
- mysqlService.executeQuery(sql);
- NameIdentifier tableIdent = NameIdentifier.of(testSchemaName, testTableName);
+ Assertions.assertTrue(catalog.asSchemas().dropSchema(testSchemaName, false));
+ Assertions.assertFalse(catalog.asSchemas().schemaExists(testSchemaName));
- Table table = catalog.asTableCatalog().loadTable(tableIdent);
- Assertions.assertEquals(testTableName, table.name());
+ // test operate illegal table name from MySQL
+ mysqlService.executeQuery(sql);
+ String testTableName = "//";
+ sql = String.format("CREATE TABLE `%s`.`%s` (id int)", testSchemaName, testTableName);
+ mysqlService.executeQuery(sql);
+ NameIdentifier tableIdent = NameIdentifier.of(testSchemaName, testTableName);
- NameIdentifier[] tableIdents =
- catalog.asTableCatalog().listTables(Namespace.of(testSchemaName));
- Assertions.assertTrue(Arrays.stream(tableIdents).anyMatch(t -> t.name().equals(testTableName)));
+ Table table = catalog.asTableCatalog().loadTable(tableIdent);
+ Assertions.assertEquals(testTableName, table.name());
- Assertions.assertTrue(catalog.asTableCatalog().dropTable(tableIdent));
- Assertions.assertFalse(catalog.asTableCatalog().tableExists(tableIdent));
- Assertions.assertThrows(
- UnsupportedOperationException.class,
- () -> {
- catalog.asTableCatalog().purgeTable(tableIdent);
- });
- catalog.asSchemas().dropSchema(testSchemaName, true);
+ NameIdentifier[] tableIdents =
+ catalog.asTableCatalog().listTables(Namespace.of(testSchemaName));
+ Assertions.assertTrue(
+ Arrays.stream(tableIdents).anyMatch(t -> t.name().equals(testTableName)));
+
+ Assertions.assertTrue(catalog.asTableCatalog().dropTable(tableIdent));
+ Assertions.assertFalse(catalog.asTableCatalog().tableExists(tableIdent));
+ Assertions.assertThrows(
+ UnsupportedOperationException.class,
+ () -> {
+ catalog.asTableCatalog().purgeTable(tableIdent);
+ });
+ } finally {
+ // This name is shared by the inherited MySQL suites. Clean both source and registration
+ // even when an assertion fails, so later suites do not inherit a non-empty catalog.
+ catalog.asSchemas().dropSchema(testSchemaName, true);
+ }
// sql injection
String schemaName = RandomNameUtils.genRandomName("ct_db");
diff --git a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/operation/TestMysqlCatalogOperations.java b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/operation/TestMysqlCatalogOperations.java
index f428c39a8e..78b29bcce6 100644
--- a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/operation/TestMysqlCatalogOperations.java
+++ b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/operation/TestMysqlCatalogOperations.java
@@ -19,8 +19,14 @@
package org.apache.gravitino.catalog.mysql.operation;
import java.sql.SQLException;
+import java.time.Instant;
+import java.util.Map;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.Namespace;
import org.apache.gravitino.catalog.jdbc.MySQLProtocolCompatibleCatalogOperations;
import org.apache.gravitino.catalog.mysql.MysqlCatalog;
+import org.apache.gravitino.connector.CatalogInfo;
+import org.apache.gravitino.meta.AuditInfo;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@@ -29,9 +35,21 @@ public class TestMysqlCatalogOperations extends TestMysql {
@Test
public void testCheckJDBCDriver() throws SQLException {
- MySQLProtocolCompatibleCatalogOperations catalogOperations =
+ Map<String, String> properties = getMySQLCatalogProperties();
+ CatalogInfo info =
+ new CatalogInfo(
+ 1L,
+ "mysql_driver_test",
+ Catalog.Type.RELATIONAL,
+ "jdbc-mysql",
+ "test",
+ properties,
+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build(),
+ Namespace.of("metalake"));
+ try (MySQLProtocolCompatibleCatalogOperations catalogOperations =
new MySQLProtocolCompatibleCatalogOperations(
- null, null, DATABASE_OPERATIONS, TABLE_OPERATIONS, null);
- catalogOperations.initialize(getMySQLCatalogProperties(), null, new MysqlCatalog());
+ null, null, DATABASE_OPERATIONS, TABLE_OPERATIONS, null)) {
+ catalogOperations.initialize(properties, info, new MysqlCatalog());
+ }
}
}
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestRelationalCatalog.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestRelationalCatalog.java
index 7c11f94707..d91878994e 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestRelationalCatalog.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestRelationalCatalog.java
@@ -814,6 +814,17 @@ public class TestRelationalCatalog extends TestBase {
Throwable ex =
Assertions.assertThrows(NoSuchTableException.class, () -> tableCatalog.loadTable(tableId));
Assertions.assertTrue(ex.getMessage().contains("table not found"));
+ buildMockResource(Method.GET, tablePath, null, errorResp, SC_NOT_FOUND);
+ Assertions.assertFalse(tableCatalog.tableExists(tableId));
+
+ ErrorResponse missingSchema =
+ ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "schema not found");
+ buildMockResource(Method.GET, tablePath, null, missingSchema, SC_NOT_FOUND);
+ NoSuchSchemaException schemaError =
+ Assertions.assertThrows(NoSuchSchemaException.class, () -> tableCatalog.loadTable(tableId));
+ Assertions.assertTrue(schemaError.getMessage().contains("schema not found"));
+ buildMockResource(Method.GET, tablePath, null, missingSchema, SC_NOT_FOUND);
+ Assertions.assertFalse(tableCatalog.tableExists(tableId));
}
@Test
diff --git a/clients/client-python/gravitino/api/rel/table_catalog.py b/clients/client-python/gravitino/api/rel/table_catalog.py
index 09a8997a5e..357c96d9ce 100644
--- a/clients/client-python/gravitino/api/rel/table_catalog.py
+++ b/clients/client-python/gravitino/api/rel/table_catalog.py
@@ -28,6 +28,7 @@ from gravitino.api.rel.expressions.transforms.transform import Transform
from gravitino.api.rel.indexes.index import Index
from gravitino.api.rel.table import Table
from gravitino.exceptions.base import (
+ NoSuchSchemaException,
NoSuchTableException,
UnsupportedOperationException,
)
@@ -83,6 +84,7 @@ class TableCatalog(ABC):
Raises:
NoSuchTableException: If the table does not exist.
+ NoSuchSchemaException: If the containing schema does not exist.
"""
def table_exists(self, identifier: NameIdentifier) -> bool:
@@ -94,7 +96,7 @@ class TableCatalog(ABC):
Returns:
bool: `True` If the table exists, `False` otherwise.
"""
- with suppress(NoSuchTableException):
+ with suppress(NoSuchTableException, NoSuchSchemaException):
self.load_table(identifier)
return True
return False
diff --git a/clients/client-python/tests/unittests/test_relational_catalog.py b/clients/client-python/tests/unittests/test_relational_catalog.py
index 21e779980d..bdc093cc7e 100644
--- a/clients/client-python/tests/unittests/test_relational_catalog.py
+++ b/clients/client-python/tests/unittests/test_relational_catalog.py
@@ -233,6 +233,26 @@ class TestRelationalCatalog(unittest.TestCase):
with self.assertRaises(NoSuchTableException):
self.catalog.load_table(self.table_identifier)
+ def test_table_exists_with_missing_schema_or_table(self):
+ for failure in (
+ NoSuchSchemaException("Schema not found"),
+ NoSuchTableException("Table not found"),
+ ):
+ with self.subTest(failure=type(failure).__name__):
+ with patch(
+ "gravitino.utils.http_client.HTTPClient.get",
+ side_effect=failure,
+ ):
+ with self.assertRaises(type(failure)):
+ self.catalog.load_table(self.table_identifier)
+ self.assertFalse(self.catalog.table_exists(self.table_identifier))
+ with patch(
+ "gravitino.utils.http_client.HTTPClient.get",
+ side_effect=RuntimeError("Backend unavailable"),
+ ):
+ with self.assertRaises(RuntimeError):
+ self.catalog.table_exists(self.table_identifier)
+
def test_create_table_already_exists(self):
with patch(
"gravitino.utils.http_client.HTTPClient.post",
diff --git a/core/src/main/java/org/apache/gravitino/EntityFieldLimits.java b/core/src/main/java/org/apache/gravitino/EntityFieldLimits.java
index 90077d5138..9f71dc0b8c 100644
--- a/core/src/main/java/org/apache/gravitino/EntityFieldLimits.java
+++ b/core/src/main/java/org/apache/gravitino/EntityFieldLimits.java
@@ -30,9 +30,12 @@ import javax.annotation.Nullable;
*/
public final class EntityFieldLimits {
- /** The maximum number of characters of an entity name or a model version alias. */
+ /** The maximum number of characters of an entity name, except table columns, or a model alias. */
public static final int MAX_NAME_LENGTH = 128;
+ /** The maximum number of characters of a table column name. */
+ public static final int MAX_COLUMN_NAME_LENGTH = 300;
+
/** The maximum number of characters of an entity comment stored in a 256-character column. */
public static final int MAX_COMMENT_LENGTH = 256;
diff --git a/core/src/main/java/org/apache/gravitino/EntityStore.java b/core/src/main/java/org/apache/gravitino/EntityStore.java
index b6ec539096..3b9b2682a1 100644
--- a/core/src/main/java/org/apache/gravitino/EntityStore.java
+++ b/core/src/main/java/org/apache/gravitino/EntityStore.java
@@ -143,6 +143,10 @@ public interface EntityStore extends Closeable {
* Store the entity into the underlying storage. According to the {@code overwritten} flag, it
* will overwrite the existing entity or throw an {@link EntityAlreadyExistsException}.
*
+ * <p>Relational schema storage also rejects conflicting active identities when overwriting: a
+ * different ID at the same name, or an active ID owned by another catalog, requires explicit
+ * reconciliation. Overwrite does not authorize cascading deletion of the previous schema.
+ *
* <p>Note. The implementation should be transactional, and should be able to handle concurrent
* store of entities.
*
@@ -151,7 +155,7 @@ public interface EntityStore extends Closeable {
* @param <E> the type of the entity
* @throws IOException if the store operation fails
* @throws EntityAlreadyExistsException if the entity already exists and the overwritten flag is
- * set to false
+ * set to false, or relational schema storage detects conflicting active identities
*/
<E extends Entity & HasIdentifier> void put(E e, boolean overwritten)
throws IOException, EntityAlreadyExistsException;
diff --git a/core/src/main/java/org/apache/gravitino/catalog/SchemaDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SchemaDispatcher.java
index f9efb3737a..f09eca41f2 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SchemaDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SchemaDispatcher.java
@@ -62,6 +62,12 @@ public interface SchemaDispatcher extends SupportsSchemas {
* <p>The default implementation rejects create-time secrets. Implementations that support secrets
* must override this method.
*
+ * <p>A failure does not guarantee that the underlying catalog object was not created. In
+ * particular, source schema creation can succeed before Gravitino registration fails. Resolve the
+ * reported error, verify the source identity, and call {@link #loadSchema(NameIdentifier)} to
+ * import it instead of repeating creation. Reconcile an existing registration before creating the
+ * same name; an external rename does not make its metadata safe to delete.
+ *
* @param ident The name identifier of the schema.
* @param comment The comment of the schema.
* @param properties The properties of the schema.
diff --git a/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java
index 421f0f416c..1125b1c044 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java
@@ -30,6 +30,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.gravitino.EntityAlreadyExistsException;
@@ -41,6 +42,7 @@ import org.apache.gravitino.SchemaChange;
import org.apache.gravitino.StringIdentifier;
import org.apache.gravitino.connector.HasPropertyMetadata;
import org.apache.gravitino.connector.capability.Capability;
+import org.apache.gravitino.exceptions.GravitinoRuntimeException;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
@@ -54,11 +56,13 @@ import org.apache.gravitino.meta.FilesetEntity;
import org.apache.gravitino.meta.SchemaEntity;
import org.apache.gravitino.secret.SecretAlterChanges;
import org.apache.gravitino.secret.SecretBinding;
+import org.apache.gravitino.secret.SecretConstants;
import org.apache.gravitino.secret.SecretManager;
import org.apache.gravitino.secret.SecretMaterial;
import org.apache.gravitino.secret.SecretMaterialsHolder;
import org.apache.gravitino.secret.SecretPropertyUtils;
import org.apache.gravitino.secret.SecretReference;
+import org.apache.gravitino.secret.SecretUrn;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.utils.PrincipalUtils;
import org.apache.gravitino.utils.SchemaEntityCleaner;
@@ -136,6 +140,8 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc
* @throws NoSuchCatalogException If the catalog corresponding to the provided identifier does not
* exist.
* @throws SchemaAlreadyExistsException If a schema with the same identifier already exists.
+ * @throws GravitinoRuntimeException If external creation succeeds but registration fails; resolve
+ * the entity-store error, verify the source identity, and use loadSchema to import it.
*/
@Override
public Schema createSchema(NameIdentifier ident, String comment, Map<String, String> properties)
@@ -143,6 +149,13 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc
return createSchema(ident, comment, properties, Collections.emptyMap(), Collections.emptyMap());
}
+ /**
+ * {@inheritDoc}
+ *
+ * @throws GravitinoRuntimeException If external creation succeeds but registration fails; resolve
+ * the entity-store error, verify the source identity, and use loadSchema to import it. Secret
+ * material referenced by the externally created schema is retained for reconciliation.
+ */
@Override
public Schema createSchema(
NameIdentifier ident,
@@ -181,26 +194,52 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc
// Write secrets before createSchema: create paths that resolve URNs (e.g. Fileset FS
// mergeUpLevelConfigurations, catalog createBaseCatalog) require secrets to exist first.
- // Roll back on any create failure (same pattern as CatalogManager /
- // FilesetOperationDispatcher).
+ // Roll back secrets only if external creation has not succeeded. Once the source schema
+ // exists, it may reference these secrets even if registration fails.
secretManager.writeSecrets(secretMaterials);
+ AtomicBoolean createdInCatalog = new AtomicBoolean();
try {
return TreeLockUtils.doWithTreeLock(
catalogIdent,
LockType.WRITE,
() -> {
+ boolean isManagedSchema = isManagedEntity(catalogIdent, Capability.Scope.SCHEMA);
+ if (!isManagedSchema) {
+ // Check before source creation so a renamed schema can still be imported under its
+ // new name. Never interpret a store failure as permission to replace its identity.
+ try {
+ if (store.exists(ident, SCHEMA)) {
+ throw new SchemaAlreadyExistsException(
+ "Schema %s is already registered in Gravitino. If it was renamed externally, "
+ + "loadSchema under its new name before creating this name. Otherwise, "
+ + "verify the old source identity is gone before removing its registration.",
+ ident);
+ }
+ } catch (IOException e) {
+ throw new GravitinoRuntimeException(
+ e,
+ "Cannot verify the registration of schema %s. Resolve the entity-store error "
+ + "before retrying; source creation has not been attempted.",
+ ident);
+ }
+ }
// we do not retrieve the schema again (to obtain some values generated by underlying
// catalog)
// since some catalogs' API is async and the schema may not be created immediately
Schema schema =
doWithCatalog(
catalogIdent,
- c -> c.doWithSchemaOps(s -> s.createSchema(ident, comment, updatedProperties)),
+ c ->
+ c.doWithSchemaOps(
+ s -> {
+ Schema created = s.createSchema(ident, comment, updatedProperties);
+ createdInCatalog.set(true);
+ return created;
+ }),
NoSuchCatalogException.class,
SchemaAlreadyExistsException.class);
// If the Schema is maintained by the Gravitino's store, we don't have to store again.
- boolean isManagedSchema = isManagedEntity(catalogIdent, Capability.Scope.SCHEMA);
if (isManagedSchema) {
return EntityCombinedSchema.of(schema)
.withHiddenProperties(
@@ -227,14 +266,21 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc
try {
store.put(schemaEntity, true /* overwrite */);
+ } catch (EntityAlreadyExistsException e) {
+ throw new SchemaAlreadyExistsException(
+ e,
+ "Schema %s was created in the external catalog, but its registration conflicts "
+ + "with an existing entity. Verify and reconcile the registered and source "
+ + "identities before continuing; loading the schema does not resolve this conflict.",
+ ident);
} catch (Exception e) {
LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put", ident, e);
- return EntityCombinedSchema.of(schema)
- .withHiddenProperties(
- getMaskAndOmitKeys(
- catalogIdent,
- HasPropertyMetadata::schemaPropertiesMetadata,
- schema.properties()));
+ throw new GravitinoRuntimeException(
+ e,
+ "Schema %s was created in the external catalog, but its registration in Gravitino "
+ + "failed. Resolve the entity-store error, verify the source identity, and use "
+ + "loadSchema to import it. Do not repeat createSchema; it will report already exists.",
+ ident);
}
// Merge both the metadata from catalog operation and the metadata from entity store.
@@ -246,7 +292,11 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc
schema.properties()));
});
} catch (RuntimeException e) {
- secretManager.rollbackSecrets(secretMaterials);
+ // An externally created schema may already reference these URNs. Keep its credentials
+ // available for reconciliation when only the entity-store registration failed.
+ if (!createdInCatalog.get()) {
+ secretManager.rollbackSecrets(secretMaterials);
+ }
throw e;
}
}
@@ -684,13 +734,32 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc
}
}
+ // Persist source properties, not the masked client view, so a recovered registration retains
+ // secret URNs. The EntityCombinedSchema returned to the caller still applies masking.
+ Map<String, String> sourceProperties =
+ SecretPropertyUtils.copyEntityProperties(schema.schema().properties());
+ for (Map.Entry<String, String> property : sourceProperties.entrySet()) {
+ String value = property.getValue();
+ if (value != null && value.startsWith(SecretConstants.URN_PREFIX)) {
+ SecretUrn urn = SecretUrn.parse(value);
+ if (urn.identifierSegments().size() == 3
+ && !SecretPropertyUtils.isWriteThroughForEntity(
+ property.getKey(), value, "schema", uid)) {
+ throw new IllegalArgumentException(
+ String.format(
+ "Cannot import schema %s: write-through secret for property %s is not owned by "
+ + "this schema identifier and property. Remove the copied reference or "
+ + "restore the matching source identity before importing.",
+ identifier, property.getKey()));
+ }
+ }
+ }
SchemaEntity schemaEntity =
SchemaEntity.builder()
.withId(uid)
.withName(identifier.name())
.withNamespace(identifier.namespace())
- .withProperties(
- schema.properties() == null ? Collections.emptyMap() : schema.properties())
+ .withProperties(sourceProperties)
.withAuditInfo(
AuditInfo.builder()
.withCreator(schema.auditInfo().creator())
diff --git a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java
index d329725f07..4439b31145 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java
@@ -161,22 +161,37 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
* @param ident The identifier of the table to load.
* @return The loaded {@link Table} object representing the requested table.
* @throws NoSuchTableException If the specified table does not exist.
+ * @throws NoSuchSchemaException If the containing schema does not exist.
*/
@Override
public Table loadTable(NameIdentifier ident) throws NoSuchTableException {
EntityCombinedTable entityCombinedTable =
- TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadTable(ident));
-
- if (!entityCombinedTable.imported()) {
+ TreeLockUtils.doWithTreeLock(
+ ident,
+ LockType.READ,
+ () -> {
+ // A cold external table will be loaded under its own WRITE lock below. Do not
+ // fetch it here only to discard the snapshot and fetch it again during import.
+ // Managed catalogs do not need the external import path, even without a store row.
+ if (getEntity(ident, TABLE, TableEntity.class) == null
+ && !isManagedEntity(getCatalogIdentifier(ident), Capability.Scope.TABLE)) {
+ return null;
+ }
+ return internalLoadTable(ident);
+ });
+
+ if (entityCombinedTable == null || !entityCombinedTable.imported()) {
// Load the schema to make sure the schema is imported.
SchemaDispatcher schemaDispatcher = getSchemaDispatcher();
NameIdentifier schemaIdent = NameIdentifier.of(ident.namespace().levels());
schemaDispatcher.loadSchema(schemaIdent);
- // Import the table.
+ // Import under the table lock: the source snapshot and store write exclude local changes
+ // to this table, while sibling tables remain available. Ancestor READ locks still exclude
+ // schema drop/rename. Never reuse a snapshot read before acquiring this lock.
try {
entityCombinedTable =
- TreeLockUtils.doWithTreeLock(schemaIdent, LockType.WRITE, () -> importTable(ident));
+ TreeLockUtils.doWithTreeLock(ident, LockType.WRITE, () -> importTable(ident));
} catch (EntityAlreadyExistsException e) {
// HA race: another Gravitino node concurrently imported this table. Reload from the
// entity store to pick up the entity stored by the winning node.
@@ -213,6 +228,8 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
* @return The newly created {@link Table} object.
* @throws NoSuchSchemaException If the schema in which to create the table does not exist.
* @throws TableAlreadyExistsException If a table with the same name already exists in the schema.
+ * @throws GravitinoRuntimeException If external creation succeeds but registration fails; resolve
+ * the entity-store error, verify the source identity, and use loadTable to import it.
*/
@Override
public Table createTable(
@@ -238,8 +255,8 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
// Lock the table node, not the schema, so tables in the same schema can be created
// concurrently. The connector call and the entity-store write otherwise run under one
// schema-wide lock, which serialized all creates in a schema. Ancestors are still read-locked,
- // so create keeps excluding dropSchema/createSchema (catalog WRITE) and rename/drop/import
- // (schema WRITE); a same-name create, load or alter contends on the table node.
+ // so create keeps excluding dropSchema/createSchema (catalog WRITE) and rename/drop
+ // (schema WRITE); a same-name create, load/import or alter contends on the table node.
// Trade-off: listTables may briefly observe a table whose creation has not committed yet.
return TreeLockUtils.doWithTreeLock(
ident,
@@ -776,9 +793,21 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
try {
store.put(tableEntity, true /* overwrite */);
+ } catch (EntityAlreadyExistsException e) {
+ throw new TableAlreadyExistsException(
+ e,
+ "Table %s was created in the external catalog, but its registration conflicts with an "
+ + "existing entity. Verify and reconcile the registered and source identities before "
+ + "continuing; loading the table does not resolve this conflict.",
+ ident);
} catch (Exception e) {
LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put", ident, e);
- return EntityCombinedTable.of(table).withHiddenProperties(catalogResult.hiddenProperties);
+ throw new GravitinoRuntimeException(
+ e,
+ "Table %s was created in the external catalog, but its registration in Gravitino "
+ + "failed. Resolve the entity-store error, verify the source identity, and use "
+ + "loadTable to import it. Do not repeat createTable; it will report already exists.",
+ ident);
}
// Merge both the metadata from catalog operation and the metadata from entity store.
diff --git a/core/src/main/java/org/apache/gravitino/meta/ColumnEntity.java b/core/src/main/java/org/apache/gravitino/meta/ColumnEntity.java
index b46f07b983..451d18854a 100644
--- a/core/src/main/java/org/apache/gravitino/meta/ColumnEntity.java
+++ b/core/src/main/java/org/apache/gravitino/meta/ColumnEntity.java
@@ -42,7 +42,7 @@ public class ColumnEntity implements Entity, Auditable {
public static final Field ID = Field.required("id", Long.class, "The column's unique identifier");
public static final Field NAME =
- Field.required("name", "The column's name", EntityFieldLimits.MAX_NAME_LENGTH);
+ Field.required("name", "The column's name", EntityFieldLimits.MAX_COLUMN_NAME_LENGTH);
public static final Field POSITION =
Field.required("position", Integer.class, "The column's position");
public static final Field TYPE = Field.required("dataType", Type.class, "The column's data type");
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java
index f9eab1cd8f..6237c20cb9 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java
@@ -108,10 +108,15 @@ public interface RelationalBackend extends Closeable, SupportsRelationOperations
/**
* Stores the entity, possibly overwriting an existing entity if specified.
*
+ * <p>A schema overwrite must not replace a different active identity at the same name or move an
+ * active identity from another catalog. Such conflicts require explicit reconciliation, even when
+ * {@code overwritten} is true; an overwrite must not cascade-delete the old schema metadata.
+ *
* @param <E> The type of the entity returned.
* @param e The entity which need be stored.
* @param overwritten If true, overwrites the existing value.
- * @throws EntityAlreadyExistsException If the entity already exists and overwrite is false.
+ * @throws EntityAlreadyExistsException If the entity already exists and overwrite is false, or a
+ * schema overwrite conflicts with an active identity.
* @throws IOException If the store operation fails
*/
<E extends Entity & HasIdentifier> void insert(E e, boolean overwritten)
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SchemaMetaMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SchemaMetaMapper.java
index 1f6c844c19..35376961cd 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SchemaMetaMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SchemaMetaMapper.java
@@ -20,6 +20,7 @@
package org.apache.gravitino.storage.relational.mapper;
import java.util.List;
+import javax.annotation.Nullable;
import org.apache.gravitino.storage.relational.helper.SchemaIds;
import org.apache.gravitino.storage.relational.po.SchemaPO;
import org.apache.ibatis.annotations.DeleteProvider;
@@ -96,6 +97,18 @@ public interface SchemaMetaMapper {
@SelectProvider(type = SchemaMetaSQLProviderFactory.class, method = "selectActiveChildBySchemaId")
Integer selectActiveChildBySchemaId(@Param("schemaId") Long schemaId);
+ /**
+ * Locks a schema identity, whether active or retired, for an overwrite transaction.
+ *
+ * @param schemaId the schema identity to lock
+ * @return the locked row, or null if that identity has never been registered or was collected
+ */
+ @Nullable
+ @SelectProvider(
+ type = SchemaMetaSQLProviderFactory.class,
+ method = "selectSchemaMetaByIdIncludingDeletedForUpdate")
+ SchemaPO selectSchemaMetaByIdIncludingDeletedForUpdate(@Param("schemaId") Long schemaId);
+
/** Selects and locks an active schema by ID for the current transaction. */
@SelectProvider(
type = SchemaMetaSQLProviderFactory.class,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SchemaMetaSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SchemaMetaSQLProviderFactory.java
index bcebb42eb9..b9f56a9ccf 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SchemaMetaSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SchemaMetaSQLProviderFactory.java
@@ -106,6 +106,12 @@ public class SchemaMetaSQLProviderFactory {
return getProvider().selectSchemaMetaById(schemaId);
}
+ /** Returns SQL that selects and locks a schema by ID, including a retired row. */
+ public static String selectSchemaMetaByIdIncludingDeletedForUpdate(
+ @Param("schemaId") Long schemaId) {
+ return getProvider().selectSchemaMetaByIdIncludingDeletedForUpdate(schemaId);
+ }
+
/** Returns SQL that checks whether an active child exists in the schema. */
public static String selectActiveChildBySchemaId(@Param("schemaId") Long schemaId) {
return getProvider().selectActiveChildBySchemaId(schemaId);
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SchemaMetaBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SchemaMetaBaseSQLProvider.java
index c6357291d3..380cf69790 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SchemaMetaBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SchemaMetaBaseSQLProvider.java
@@ -35,6 +35,16 @@ import org.apache.gravitino.storage.relational.po.SchemaPO;
import org.apache.ibatis.annotations.Param;
public class SchemaMetaBaseSQLProvider {
+ private static final String SELECT_SCHEMA_BY_ID =
+ "SELECT schema_id as schemaId, schema_name as schemaName,"
+ + " metalake_id as metalakeId, catalog_id as catalogId,"
+ + " schema_comment as schemaComment, properties, audit_info as auditInfo,"
+ + " current_version as currentVersion, last_version as lastVersion,"
+ + " deleted_at as deletedAt"
+ + " FROM "
+ + TABLE_NAME
+ + " WHERE schema_id = #{schemaId}";
+
public String listSchemaPOsByCatalogId(@Param("catalogId") Long catalogId) {
return "SELECT schema_id as schemaId, schema_name as schemaName,"
+ " metalake_id as metalakeId, catalog_id as catalogId,"
@@ -180,14 +190,17 @@ public class SchemaMetaBaseSQLProvider {
}
public String selectSchemaMetaById(@Param("schemaId") Long schemaId) {
- return "SELECT schema_id as schemaId, schema_name as schemaName,"
- + " metalake_id as metalakeId, catalog_id as catalogId,"
- + " schema_comment as schemaComment, properties, audit_info as auditInfo,"
- + " current_version as currentVersion, last_version as lastVersion,"
- + " deleted_at as deletedAt"
- + " FROM "
- + TABLE_NAME
- + " WHERE schema_id = #{schemaId} AND deleted_at = 0";
+ return SELECT_SCHEMA_BY_ID + " AND deleted_at = 0";
+ }
+
+ /**
+ * Returns SQL that locks a schema identity, including a retired row that can be revived.
+ *
+ * @param schemaId the schema ID bound by MyBatis
+ * @return a select-for-update statement without a deleted-at filter
+ */
+ public String selectSchemaMetaByIdIncludingDeletedForUpdate(@Param("schemaId") Long schemaId) {
+ return SELECT_SCHEMA_BY_ID + " FOR UPDATE";
}
/** Returns SQL that checks whether an active child exists in the schema. */
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java
index 01ce984a66..6ddfe16616 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/SchemaMetaService.java
@@ -32,7 +32,9 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import javax.annotation.Nullable;
import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.HasIdentifier;
import org.apache.gravitino.MetadataObject;
@@ -135,6 +137,15 @@ public class SchemaMetaService {
return POConverters.fromSchemaPOs(schemaPOs, namespace);
}
+ /**
+ * Registers a schema without replacing another active identity at the same name.
+ *
+ * @param schemaEntity the schema to register
+ * @param overwrite whether to update or revive the same schema ID; active cross-catalog IDs and
+ * different active IDs at the same name are rejected even when true
+ * @throws EntityAlreadyExistsException if the name or identity conflicts with a registration
+ * @throws IOException if the store operation fails
+ */
@Monitored(
metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
baseMetricName = "insertSchema")
@@ -175,10 +186,10 @@ public class SchemaMetaService {
// Everything below runs in one transaction, and it starts by locking the parent catalog row.
// That lock is what stops a catalog drop from running at the same time as this insert. A
- // plain name is enough with a shared lock; a nested name needs an exclusive one, see
- // lockCatalogForSchemaCreate.
+ // plain insert can use a shared lock; nested ancestors or an overwrite need an exclusive
+ // lock to serialize the name/identity checks with other registrations and schema drops.
SessionUtils.doMultipleWithCommit(
- () -> lockCatalogForSchemaCreate(catalogPO, rowsToInsert.size() > 1),
+ () -> lockCatalogForSchemaCreate(catalogPO, rowsToInsert.size() > 1 || overwrite),
() ->
SessionUtils.doWithoutCommit(
SchemaMetaMapper.class,
@@ -220,7 +231,13 @@ public class SchemaMetaService {
SchemaPO leafPO =
POConverters.initializeSchemaPOWithVersion(
leafRow, newSchemaPOBuilder(catalogPO));
- ops.batchInsertPOs(mapper, Collections.singletonList(leafPO), overwrite);
+ boolean updateExistingId =
+ overwrite
+ && prepareSchemaOverwrite(
+ schemaEntity.nameIdentifier(), leafPO, mapper);
+ // A never-seen ID must use a plain insert. A concurrent catalog can register
+ // the same source ID after the lookup; an upsert would steal that winner.
+ ops.batchInsertPOs(mapper, Collections.singletonList(leafPO), updateExistingId);
}));
} catch (RuntimeException re) {
ExceptionUtils.checkSQLException(
@@ -485,23 +502,61 @@ public class SchemaMetaService {
mapper -> POStorageReadRouting.listPOs(mapper, namespace, ops, Entity.EntityType.SCHEMA));
}
+ private boolean prepareSchemaOverwrite(
+ NameIdentifier identifier, SchemaPO incoming, SchemaMetaMapper mapper) {
+ // Reject an active foreign identity before taking its row lock. The locking read below
+ // must still revalidate identity because the first check is only a fail-fast optimization.
+ SchemaPO registeredId = mapper.selectSchemaMetaById(incoming.getSchemaId());
+ rejectForeignSchemaIdentity(identifier, incoming, registeredId);
+ // Lock even a retired ID before reviving it. Otherwise two catalogs could both revive the
+ // same marker and the slower upsert would move the winner's newly live registration.
+ registeredId = mapper.selectSchemaMetaByIdIncludingDeletedForUpdate(incoming.getSchemaId());
+ rejectForeignSchemaIdentity(identifier, incoming, registeredId);
+ SchemaPO stored =
+ ops.listPOs(mapper, identifier.namespace(), List.of(identifier.name())).stream()
+ .findFirst()
+ .orElse(null);
+ if (stored != null && !stored.getSchemaId().equals(incoming.getSchemaId())) {
+ // A different ID at this name does not prove that the old source object was deleted: it
+ // may have been renamed externally. The store cannot resolve source identities, so preserve
+ // its children and governance metadata until the caller explicitly reconciles the conflict.
+ throw new EntityAlreadyExistsException(
+ "Schema %s is already registered with a different identifier. Reconcile the existing "
+ + "registration before replacing it; its source object may have been renamed.",
+ identifier);
+ }
+ return registeredId != null;
+ }
+
+ private static void rejectForeignSchemaIdentity(
+ NameIdentifier identifier, SchemaPO incoming, @Nullable SchemaPO registered) {
+ if (registered != null
+ && registered.getDeletedAt() == 0
+ && !Objects.equals(registered.getCatalogId(), incoming.getCatalogId())) {
+ throw new EntityAlreadyExistsException(
+ "Schema %s has an identifier already registered in another catalog", identifier);
+ }
+ }
+
/**
* Holds the parent catalog row for the rest of the transaction, so a schema cannot be created
* below a catalog that is being dropped. Dropping a catalog locks this same row, so the two can
* never run at the same time: the loser either finds the catalog gone or inserts below a catalog
* that is still there.
*
- * <p>A plain schema name only needs a shared lock, so many schemas can be created under one
- * catalog at once. A nested name is different: this request may have to create the missing
- * ancestors, and two requests can both find the same ancestor missing and both insert it. A
- * shared lock does not stop that, so the ancestor case takes an exclusive lock and serializes
- * every other schema create under the catalog until it finishes.
+ * <p>A non-overwriting plain schema insert only needs a shared lock, so many schemas can be
+ * created under one catalog at once. A nested name is different: this request may have to create
+ * the missing ancestors, and two requests can both find the same ancestor missing and both insert
+ * it. A shared lock does not stop that, so the ancestor case takes an exclusive lock and
+ * serializes every other schema create under the catalog until it finishes. An overwrite also
+ * takes the exclusive lock to keep its name/identity checks stable against registrations and
+ * drops. This deliberately avoids a shared-lock upgrade or a transaction retry on conflicts.
*
* <p>The name and the metalake are compared again because the caller looked the catalog up by
* name: if the row now has another name, the catalog named in the request no longer exists.
*/
private void lockCatalogForSchemaCreate(
- CatalogPO observedCatalogPO, boolean createsImplicitAncestors) {
+ CatalogPO observedCatalogPO, boolean requiresExclusiveLock) {
OccWriteSupport.lockParentForChildWrite(
observedCatalogPO.getCatalogName(),
Entity.EntityType.CATALOG,
@@ -509,7 +564,7 @@ public class SchemaMetaService {
SessionUtils.getWithoutCommit(
CatalogMetaMapper.class,
mapper ->
- createsImplicitAncestors
+ requiresExclusiveLock
? mapper.selectCatalogMetaByIdForUpdate(observedCatalogPO.getCatalogId())
: mapper.selectCatalogMetaByIdForShare(observedCatalogPO.getCatalogId())),
null,
diff --git a/core/src/main/java/org/apache/gravitino/utils/BoundedConnectionDriver.java b/core/src/main/java/org/apache/gravitino/utils/BoundedConnectionDriver.java
new file mode 100644
index 0000000000..6bc370a9a3
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/utils/BoundedConnectionDriver.java
@@ -0,0 +1,301 @@
+/*
+ * 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.gravitino.utils;
+
+import java.security.AccessControlContext;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.ProtectionDomain;
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverPropertyInfo;
+import java.sql.SQLException;
+import java.sql.SQLFeatureNotSupportedException;
+import java.sql.SQLTimeoutException;
+import java.sql.SQLTransientConnectionException;
+import java.util.Properties;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+import javax.annotation.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Bounds physical connection creation for drivers that cannot enforce a login timeout.
+ *
+ * <p>Only {@link Driver#connect} runs on a worker. Validation, metadata queries and DDL stay on the
+ * caller. A connection that arrives after timeout or interruption is closed by its worker and is
+ * never handed to a pool. Cancellation is best effort: a driver ignoring interruption retains a
+ * worker until it returns. A JVM-wide limit of 64 workers, with no queue, bounds that retention;
+ * excess attempts fail with {@link SQLTransientConnectionException}. Workers are daemon threads and
+ * release their catalog context class loader after each attempt. Each attempt, including late
+ * connection cleanup, runs with the submitting caller's access-control context and JAAS subject;
+ * shared workers do not inherit the creating request's JAAS subject. This does not isolate
+ * arbitrary {@link ThreadLocal} or {@link InheritableThreadLocal} state. Delegates must clean up
+ * such state and must not rely on it to carry a caller's identity. Drivers that cannot meet this
+ * requirement must not use this adapter's shared workers.
+ *
+ * <p>After a timeout, further attempts through this instance fail immediately until the abandoned
+ * attempt finishes cleanup. This prevents a lazy pool's initialization lock from serializing a
+ * backlog of new attempts against the same unreachable backend. Normal pool waits and SQL execution
+ * have their own budgets and are not bounded by this adapter.
+ */
+@SuppressWarnings("removal") // JDK 17 associates JAAS subjects with access-control contexts.
+public final class BoundedConnectionDriver implements Driver {
+ private static final Logger LOG = LoggerFactory.getLogger(BoundedConnectionDriver.class);
+
+ private static final AccessControlContext WORKER_CONTEXT =
+ new AccessControlContext(new ProtectionDomain[0]);
+
+ private static final ExecutorService WORKERS =
+ new ThreadPoolExecutor(
+ 0,
+ 64,
+ 60,
+ TimeUnit.SECONDS,
+ new SynchronousQueue<>(),
+ task ->
+ AccessController.doPrivileged(
+ (PrivilegedAction<Thread>)
+ () -> {
+ Thread thread = new Thread(task, "jdbc-connect-timeout");
+ thread.setDaemon(true);
+ thread.setContextClassLoader(
+ BoundedConnectionDriver.class.getClassLoader());
+ return thread;
+ },
+ WORKER_CONTEXT));
+
+ private final Driver delegate;
+ private final long timeoutMs;
+ private final ExecutorService workers;
+ private final AtomicInteger abandonedAttempts = new AtomicInteger();
+
+ /**
+ * Wraps a driver with a physical connection deadline.
+ *
+ * @param delegate the driver to call, without registering the wrapper with DriverManager
+ * @param timeoutMs a positive timeout in milliseconds
+ * @throws IllegalArgumentException if timeoutMs is not positive
+ */
+ public BoundedConnectionDriver(Driver delegate, long timeoutMs) {
+ this(delegate, timeoutMs, WORKERS);
+ }
+
+ BoundedConnectionDriver(Driver delegate, long timeoutMs, ExecutorService workers) {
+ if (timeoutMs <= 0) {
+ throw new IllegalArgumentException("JDBC connect timeout must be positive");
+ }
+ this.delegate = delegate;
+ this.timeoutMs = timeoutMs;
+ this.workers = workers;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws SQLTimeoutException if the connection deadline expires or the caller is interrupted
+ * @throws SQLTransientConnectionException if all workers are busy or a previous timed-out attempt
+ * through this driver is still running
+ */
+ @Override
+ public Connection connect(String url, @Nullable Properties info) throws SQLException {
+ if (abandonedAttempts.get() != 0) {
+ throw new SQLTransientConnectionException(
+ "A previous timed-out JDBC connection attempt is still running. Try again after it finishes.",
+ "08001");
+ }
+ Attempt attempt = new Attempt();
+ ClassLoader context = Thread.currentThread().getContextClassLoader();
+ AccessControlContext callerContext = AccessController.getContext();
+ Properties properties = info == null ? new Properties() : (Properties) info.clone();
+ try {
+ workers.execute(
+ () ->
+ AccessController.doPrivileged(
+ (PrivilegedAction<Void>)
+ () -> {
+ attempt.run(url, properties, context);
+ return null;
+ },
+ callerContext));
+ } catch (RejectedExecutionException e) {
+ throw new SQLTransientConnectionException(
+ "The JDBC connection attempt limit has been reached. Try again after an attempt finishes.",
+ "08001",
+ e);
+ }
+ try {
+ Connection connection = attempt.result.get(timeoutMs, TimeUnit.MILLISECONDS);
+ attempt.accept();
+ return connection;
+ } catch (TimeoutException e) {
+ attempt.abandon();
+ throw new SQLTimeoutException(
+ "JDBC connection attempt exceeded "
+ + timeoutMs
+ + " ms. Check backend and proxy connectivity.",
+ "08001",
+ e);
+ } catch (InterruptedException e) {
+ attempt.abandon();
+ Thread.currentThread().interrupt();
+ throw new SQLTimeoutException("Interrupted while opening a JDBC connection", "08001", e);
+ } catch (ExecutionException e) {
+ Throwable cause = e.getCause();
+ if (cause instanceof SQLException) {
+ throw (SQLException) cause;
+ }
+ if (cause instanceof RuntimeException) {
+ throw (RuntimeException) cause;
+ }
+ if (cause instanceof Error) {
+ throw (Error) cause;
+ }
+ throw new SQLException("Failed to open JDBC connection", "08001", cause);
+ } finally {
+ attempt.decision.countDown();
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean acceptsURL(String url) throws SQLException {
+ return delegate.acceptsURL(url);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
+ return delegate.getPropertyInfo(url, info);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public int getMajorVersion() {
+ return delegate.getMajorVersion();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public int getMinorVersion() {
+ return delegate.getMinorVersion();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean jdbcCompliant() {
+ return delegate.jdbcCompliant();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
+ return delegate.getParentLogger();
+ }
+
+ private final class Attempt {
+ private final CompletableFuture<Connection> result = new CompletableFuture<>();
+ private final CountDownLatch decision = new CountDownLatch(1);
+ private boolean accepted;
+ private boolean abandoned;
+ private boolean finished;
+ @Nullable private Thread runner;
+
+ synchronized void accept() {
+ accepted = true;
+ }
+
+ synchronized void abandon() {
+ if (!finished) {
+ abandoned = true;
+ abandonedAttempts.incrementAndGet();
+ if (runner != null) {
+ runner.interrupt();
+ }
+ }
+ }
+
+ void run(String url, Properties properties, @Nullable ClassLoader context) {
+ Thread current = Thread.currentThread();
+ ClassLoader previous = current.getContextClassLoader();
+ current.setContextClassLoader(context);
+ Connection connection = null;
+ boolean interrupted = false;
+ try {
+ synchronized (this) {
+ runner = current;
+ if (abandoned) {
+ return;
+ }
+ }
+ connection = delegate.connect(url, properties);
+ result.complete(connection);
+ while (true) {
+ try {
+ decision.await();
+ break;
+ } catch (InterruptedException e) {
+ // Cancellation must not bypass the handoff decision or discard a late connection.
+ interrupted = true;
+ }
+ }
+ } catch (Throwable e) {
+ result.completeExceptionally(e);
+ } finally {
+ // Cancellation must not make an interrupt-sensitive close fail before releasing the
+ // physical connection. Restore the signal only after cleanup, including delegate signals.
+ interrupted |= Thread.interrupted();
+ boolean delivered;
+ synchronized (this) {
+ delivered = accepted;
+ }
+ try {
+ if (!delivered && connection != null) {
+ try {
+ connection.close();
+ } catch (SQLException e) {
+ LOG.warn("Failed to close an abandoned JDBC connection", e);
+ }
+ }
+ } finally {
+ synchronized (this) {
+ finished = true;
+ runner = null;
+ if (abandoned) {
+ abandonedAttempts.decrementAndGet();
+ }
+ }
+ current.setContextClassLoader(previous);
+ if (interrupted) {
+ current.interrupt();
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java
index a8e54c0246..7f9c9c4878 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java
@@ -27,7 +27,9 @@ 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;
import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
@@ -49,10 +51,13 @@ import org.apache.gravitino.Namespace;
import org.apache.gravitino.Schema;
import org.apache.gravitino.SchemaChange;
import org.apache.gravitino.StringIdentifier;
+import org.apache.gravitino.TestCatalog;
import org.apache.gravitino.auth.AuthConstants;
import org.apache.gravitino.connector.HiddenPropertyMaskUtils;
import org.apache.gravitino.connector.TestCatalogOperations;
+import org.apache.gravitino.exceptions.GravitinoRuntimeException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.OptimisticLockException;
import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
import org.apache.gravitino.lock.LockManager;
@@ -61,6 +66,7 @@ import org.apache.gravitino.meta.SchemaEntity;
import org.apache.gravitino.secret.SecretBinding;
import org.apache.gravitino.secret.SecretConstants;
import org.apache.gravitino.secret.SecretManager;
+import org.apache.gravitino.secret.SecretPropertyOperationDispatcher;
import org.apache.gravitino.secret.SecretPropertyUtils;
import org.apache.gravitino.secret.SecretProviderRegistry;
import org.apache.gravitino.secret.SecretUrn;
@@ -68,6 +74,8 @@ import org.apache.gravitino.secret.memory.InMemorySecretsProvider;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
public class TestSchemaOperationDispatcher extends TestOperationDispatcher {
@@ -105,10 +113,56 @@ public class TestSchemaOperationDispatcher extends TestOperationDispatcher {
});
return null;
});
+ SchemaAlreadyExistsException conflict =
+ Assertions.assertThrows(
+ SchemaAlreadyExistsException.class,
+ () ->
+ dispatcher.createSchema(
+ original, "replacement", ImmutableMap.of("k1", "v1", "k2", "v2")));
+ Assertions.assertTrue(conflict.getMessage().contains(original.toString()));
+ Assertions.assertTrue(conflict.getMessage().contains("loadSchema under its new name"));
+ Assertions.assertEquals(
+ originalEntity.id(), entityStore.get(original, SCHEMA, SchemaEntity.class).id());
+ catalogManager.doWithCatalogWrapper(
+ NameIdentifier.of(metalake, catalog),
+ c -> {
+ boolean originalExists = c.doWithSchemaOps(ops -> ops.schemaExists(original));
+ boolean renamedExists = c.doWithSchemaOps(ops -> ops.schemaExists(renamed));
+ Assertions.assertFalse(originalExists);
+ Assertions.assertTrue(renamedExists);
+ return null;
+ });
Assertions.assertEquals(renamed.name(), dispatcher.loadSchema(renamed).name());
Assertions.assertEquals(
originalEntity.id(), entityStore.get(renamed, SCHEMA, SchemaEntity.class).id());
Assertions.assertFalse(entityStore.exists(original, SCHEMA));
+ dispatcher.createSchema(original, "replacement", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ Assertions.assertNotEquals(
+ originalEntity.id(), entityStore.get(original, SCHEMA, SchemaEntity.class).id());
+ Assertions.assertEquals(
+ originalEntity.id(), entityStore.get(renamed, SCHEMA, SchemaEntity.class).id());
+ }
+
+ @Test
+ void testCreateSchemaStopsBeforeSourceWhenRegistrationLookupFails() throws Exception {
+ NameIdentifier ident = NameIdentifier.of(metalake, catalog, "schema_preflight_failure");
+ IOException failure = new IOException("registration lookup failed");
+ doThrow(failure).when(entityStore).exists(ident, SCHEMA);
+ GravitinoRuntimeException error =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () -> dispatcher.createSchema(ident, "", ImmutableMap.of("k1", "v1", "k2", "v2")));
+ Assertions.assertSame(failure, error.getCause());
+ Assertions.assertTrue(error.getMessage().contains(ident.toString()));
+ Assertions.assertTrue(error.getMessage().contains("source creation has not been attempted"));
+ catalogManager.doWithCatalogWrapper(
+ NameIdentifier.of(metalake, catalog),
+ c -> {
+ boolean sourceExists = c.doWithSchemaOps(ops -> ops.schemaExists(ident));
+ Assertions.assertFalse(sourceExists);
+ return null;
+ });
+ verify(entityStore, never()).put(any(SchemaEntity.class), anyBoolean());
}
@Test
@@ -140,7 +194,7 @@ public class TestSchemaOperationDispatcher extends TestOperationDispatcher {
}
@Test
- public void testCreateAndListSchemas() throws IOException {
+ public void testCreateAndListSchemas() throws Exception {
Namespace ns = Namespace.of(metalake, catalog);
NameIdentifier schemaIdent = NameIdentifier.of(ns, "schema1");
@@ -185,24 +239,32 @@ public class TestSchemaOperationDispatcher extends TestOperationDispatcher {
.findFirst();
Assertions.assertTrue(ident1.isPresent());
- // Test when the entity store failed to put the schema entity
- doThrow(new IOException()).when(entityStore).put(any(), anyBoolean());
+ IOException registrationFailure = new IOException("store unavailable");
+ doThrow(registrationFailure).when(entityStore).put(any(), anyBoolean());
NameIdentifier schemaIdent2 = NameIdentifier.of(ns, "schema2");
- Schema schema2 = dispatcher.createSchema(schemaIdent2, "comment", props);
-
- // Check if the created Schema's field values are correct
- Assertions.assertEquals("schema2", schema2.name());
- Assertions.assertEquals("comment", schema2.comment());
- testProperties(props, schema2.properties());
-
- // Check if the Schema entity is stored in the EntityStore
+ GravitinoRuntimeException error =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () -> dispatcher.createSchema(schemaIdent2, "comment", props));
+ Assertions.assertSame(registrationFailure, error.getCause());
+ Assertions.assertTrue(error.getMessage().contains(schemaIdent2.toString()));
+ Assertions.assertTrue(error.getMessage().contains("created in the external catalog"));
+ Assertions.assertTrue(error.getMessage().contains("use loadSchema to import it"));
+ Assertions.assertTrue(error.getMessage().contains("Do not repeat createSchema"));
Assertions.assertFalse(entityStore.exists(schemaIdent2, SCHEMA));
+ Schema created =
+ catalogManager
+ .loadCatalogAndWrap(NameIdentifier.of(metalake, catalog))
+ .doWithSchemaOps(ops -> ops.loadSchema(schemaIdent2));
+ Assertions.assertEquals("schema2", created.name());
+ Assertions.assertEquals("comment", created.comment());
+ reset(entityStore);
Assertions.assertThrows(
- NoSuchEntityException.class,
- () -> entityStore.get(schemaIdent2, SCHEMA, SchemaEntity.class));
-
- // Audit info is gotten from the catalog, not from the entity store
- Assertions.assertEquals("test", schema2.auditInfo().creator());
+ SchemaAlreadyExistsException.class,
+ () -> dispatcher.createSchema(schemaIdent2, "comment", props));
+ Assertions.assertFalse(entityStore.exists(schemaIdent2, SCHEMA));
+ dispatcher.loadSchema(schemaIdent2);
+ Assertions.assertTrue(entityStore.exists(schemaIdent2, SCHEMA));
}
@Test
@@ -596,6 +658,181 @@ public class TestSchemaOperationDispatcher extends TestOperationDispatcher {
Assertions.assertTrue(entityStore.exists(ancestorA, SCHEMA));
}
+ @Test
+ void testNativeSchemaImportDoesNotOverwriteAnotherRegistration() throws Exception {
+ NameIdentifier ident = NameIdentifier.of(metalake, catalog, "schema_native_no_marker");
+ TestCatalog source =
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
+ ((TestCatalogOperations) source.ops())
+ .createSchema(ident, "native", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ reset(entityStore);
+ try {
+ Assertions.assertEquals(ident.name(), dispatcher.loadSchema(ident).name());
+ verify(entityStore).put(any(SchemaEntity.class), eq(false));
+ verify(entityStore, never()).put(any(SchemaEntity.class), eq(true));
+ } finally {
+ reset(entityStore);
+ }
+ }
+
+ @Test
+ void testRegistrationFailureRetainsSecretsUsedByCreatedSchema() throws Exception {
+ try (SecretManager secrets = memorySecretManager()) {
+ SchemaOperationDispatcher d =
+ new SchemaOperationDispatcher(catalogManager, entityStore, idGenerator, secrets);
+ NameIdentifier ident = NameIdentifier.of(metalake, catalog, "schema_secret_partial_create");
+ doThrow(new IOException("store unavailable"))
+ .when(entityStore)
+ .put(any(SchemaEntity.class), eq(true));
+ try {
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () ->
+ d.createSchema(
+ ident,
+ "comment",
+ ImmutableMap.of("k1", "v1"),
+ Map.of("k2", new SecretBinding("memory", "retained-secret")),
+ Map.of()));
+ Schema created =
+ catalogManager
+ .loadCatalogAndWrap(NameIdentifier.of(metalake, catalog))
+ .doWithSchemaOps(ops -> ops.loadSchema(ident));
+ SecretUrn urn = SecretUrn.parse(created.properties().get("k2"));
+ Assertions.assertEquals("retained-secret", secrets.readSecret(urn));
+ reset(entityStore);
+ Assertions.assertThrows(
+ SchemaAlreadyExistsException.class,
+ () -> d.createSchema(ident, "comment", ImmutableMap.of("k1", "v1", "k2", "v2")));
+ Assertions.assertFalse(entityStore.exists(ident, SCHEMA));
+ Schema imported = d.loadSchema(ident);
+ Assertions.assertEquals(
+ HiddenPropertyMaskUtils.MASKED_VALUE, imported.properties().get("k2"));
+ Assertions.assertFalse(imported.properties().containsKey(ID_KEY));
+ Assertions.assertEquals(
+ urn.toString(),
+ entityStore.get(ident, SCHEMA, SchemaEntity.class).properties().get("k2"));
+ Assertions.assertEquals("retained-secret", secrets.readSecret(urn));
+ Assertions.assertTrue(d.dropSchema(ident, false));
+ Assertions.assertThrows(IllegalArgumentException.class, () -> secrets.readSecret(urn));
+ } finally {
+ reset(entityStore);
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"entity-id", "entity-type", "property-key"})
+ void testImportRejectsForeignWriteThroughSecrets(String mismatch) throws Exception {
+ try (SecretManager secrets = memorySecretManager()) {
+ SchemaOperationDispatcher d =
+ new SchemaOperationDispatcher(catalogManager, entityStore, idGenerator, secrets);
+ SecretPropertyOperationDispatcher secretDispatcher =
+ new SecretPropertyOperationDispatcher(catalogManager, entityStore, idGenerator, secrets);
+ NameIdentifier original = NameIdentifier.of(metalake, catalog, "secret_owner_" + mismatch);
+ NameIdentifier copy = NameIdentifier.of(metalake, catalog, "secret_copy_" + mismatch);
+ d.createSchema(
+ original,
+ "owner",
+ Map.of("k1", "v1"),
+ Map.of("k2", new SecretBinding("memory", "original-secret")),
+ Map.of());
+ SchemaEntity owner = entityStore.get(original, SCHEMA, SchemaEntity.class);
+ SecretUrn originalUrn = SecretUrn.parse(owner.properties().get("k2"));
+ Map<String, String> properties = new HashMap<>();
+ properties.put("k1", "v1");
+ if (mismatch.equals("entity-id")) {
+ // A copied URN without its source marker would otherwise be imported under a new id.
+ properties.put("k2", originalUrn.toString());
+ } else {
+ long copyId = idGenerator.nextId();
+ properties.put(ID_KEY, StringIdentifier.fromId(copyId).toString());
+ properties.put(
+ "k2",
+ SecretUrn.buildWriteThrough(
+ "memory",
+ Map.of(
+ SecretConstants.ATTR_ENTITY_TYPE,
+ mismatch.equals("entity-type") ? "catalog" : "schema",
+ SecretConstants.ATTR_ENTITY_ID,
+ String.valueOf(copyId),
+ SecretConstants.ATTR_PROPERTY_KEY,
+ mismatch.equals("property-key") ? "otherk2" : "k2"))
+ .toString());
+ }
+ catalogManager.doWithCatalogWrapper(
+ NameIdentifier.of(metalake, catalog),
+ c -> c.doWithSchemaOps(ops -> ops.createSchema(copy, "copy", properties)));
+
+ IllegalArgumentException failure =
+ Assertions.assertThrows(IllegalArgumentException.class, () -> d.loadSchema(copy));
+ Assertions.assertTrue(failure.getMessage().contains(copy.toString()));
+ Assertions.assertTrue(failure.getMessage().contains("property k2"));
+ Assertions.assertFalse(entityStore.exists(copy, SCHEMA));
+ Assertions.assertThrows(
+ NoSuchSchemaException.class, () -> secretDispatcher.getSecrets(copy, SCHEMA));
+ Assertions.assertTrue(d.dropSchema(copy, false));
+ Assertions.assertEquals("original-secret", secrets.readSecret(originalUrn));
+ Assertions.assertEquals(
+ owner.id(), entityStore.get(original, SCHEMA, SchemaEntity.class).id());
+ Assertions.assertTrue(d.dropSchema(original, false));
+ }
+ }
+
+ @Test
+ void testImportRetainsExternalSecretReference() throws Exception {
+ NameIdentifier ident = NameIdentifier.of(metalake, catalog, "external_secret_reference");
+ String reference = "urn:gravitino-secret:external:credential:k2";
+ catalogManager.doWithCatalogWrapper(
+ NameIdentifier.of(metalake, catalog),
+ c ->
+ c.doWithSchemaOps(
+ ops -> ops.createSchema(ident, "external", Map.of("k1", "v1", "k2", reference))));
+
+ Schema imported = dispatcher.loadSchema(ident);
+ Assertions.assertEquals(HiddenPropertyMaskUtils.MASKED_VALUE, imported.properties().get("k2"));
+ Assertions.assertEquals(
+ reference, entityStore.get(ident, SCHEMA, SchemaEntity.class).properties().get("k2"));
+ Assertions.assertTrue(dispatcher.dropSchema(ident, false));
+ }
+
+ @Test
+ void testCreateSchemaReportsRegistrationConflictAndRetainsSecrets() throws Exception {
+ try (SecretManager secrets = memorySecretManager()) {
+ SchemaOperationDispatcher d =
+ new SchemaOperationDispatcher(catalogManager, entityStore, idGenerator, secrets);
+ NameIdentifier ident = NameIdentifier.of(metalake, catalog, "schema_registration_conflict");
+ EntityAlreadyExistsException conflict =
+ new EntityAlreadyExistsException("concurrent registration");
+ doThrow(conflict).when(entityStore).put(any(SchemaEntity.class), eq(true));
+ try {
+ SchemaAlreadyExistsException failure =
+ Assertions.assertThrows(
+ SchemaAlreadyExistsException.class,
+ () ->
+ d.createSchema(
+ ident,
+ "",
+ Map.of("k1", "v1"),
+ Map.of("k2", new SecretBinding("memory", "retained-secret")),
+ Map.of()));
+ Assertions.assertSame(conflict, failure.getCause());
+ Assertions.assertTrue(failure.getMessage().contains(ident.toString()));
+ Assertions.assertTrue(failure.getMessage().contains("reconcile"));
+ Assertions.assertFalse(failure.getMessage().contains("use loadSchema to import"));
+ Schema source =
+ catalogManager
+ .loadCatalogAndWrap(NameIdentifier.of(metalake, catalog))
+ .doWithSchemaOps(ops -> ops.loadSchema(ident));
+ Assertions.assertEquals(
+ "retained-secret", secrets.readSecret(SecretUrn.parse(source.properties().get("k2"))));
+ } finally {
+ reset(entityStore);
+ }
+ }
+ }
+
@Test
public void testSecrets() throws Exception {
try (SecretManager secrets = memorySecretManager()) {
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java
index 5d58fe6900..d153edf8f9 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java
@@ -35,8 +35,10 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
+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 com.google.common.collect.ImmutableMap;
import java.io.IOException;
@@ -47,6 +49,11 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
@@ -67,11 +74,15 @@ import org.apache.gravitino.TestTable;
import org.apache.gravitino.auth.AuthConstants;
import org.apache.gravitino.connector.HiddenPropertyMaskUtils;
import org.apache.gravitino.connector.TestCatalogOperations;
+import org.apache.gravitino.connector.capability.Capability;
+import org.apache.gravitino.connector.capability.CapabilityResult;
import org.apache.gravitino.dto.util.DTOConverters;
import org.apache.gravitino.exceptions.GravitinoRuntimeException;
import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.exceptions.OptimisticLockException;
+import org.apache.gravitino.exceptions.TableAlreadyExistsException;
import org.apache.gravitino.lock.LockManager;
import org.apache.gravitino.lock.LockType;
import org.apache.gravitino.meta.AuditInfo;
@@ -101,6 +112,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
public class TestTableOperationDispatcher extends TestOperationDispatcher {
static TableOperationDispatcher tableOperationDispatcher;
@@ -194,25 +206,71 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
.findFirst();
Assertions.assertTrue(ident1.isPresent());
- // Test when the entity store failed to put the table entity
- doThrow(new IOException()).when(entityStore).put(any(), anyBoolean());
+ // Source creation succeeds, but a failed registration must not be reported as success.
+ IOException registrationFailure = new IOException("store unavailable");
+ doThrow(registrationFailure).when(entityStore).put(any(), anyBoolean());
NameIdentifier tableIdent2 = NameIdentifier.of(tableNs, "table2");
- Table table2 =
- tableOperationDispatcher.createTable(
- tableIdent2, columns, "comment", props, new Transform[0]);
-
- // Check if the created Schema's field values are correct
- Assertions.assertEquals("table2", table2.name());
- Assertions.assertEquals("comment", table2.comment());
- testProperties(props, table2.properties());
-
- // Check if the Table entity is stored in the EntityStore
+ GravitinoRuntimeException error =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () ->
+ tableOperationDispatcher.createTable(
+ tableIdent2, columns, "comment", props, new Transform[0]));
+ Assertions.assertSame(registrationFailure, error.getCause());
+ Assertions.assertTrue(error.getMessage().contains(tableIdent2.toString()));
+ Assertions.assertTrue(error.getMessage().contains("created in the external catalog"));
+ Assertions.assertTrue(error.getMessage().contains("use loadTable to import it"));
+ Assertions.assertTrue(error.getMessage().contains("Do not repeat createTable"));
Assertions.assertFalse(entityStore.exists(tableIdent2, TABLE));
+ catalogManager.doWithCatalog(
+ NameIdentifier.of(metalake, catalog),
+ source -> {
+ Table created = ((TestCatalogOperations) source.ops()).loadTable(tableIdent2);
+ Assertions.assertEquals("table2", created.name());
+ Assertions.assertEquals("comment", created.comment());
+ return null;
+ });
+ reset(entityStore);
Assertions.assertThrows(
- NoSuchEntityException.class, () -> entityStore.get(tableIdent2, TABLE, TableEntity.class));
+ TableAlreadyExistsException.class,
+ () ->
+ tableOperationDispatcher.createTable(
+ tableIdent2, columns, "comment", props, new Transform[0]));
+ Assertions.assertFalse(entityStore.exists(tableIdent2, TABLE));
+ tableOperationDispatcher.loadTable(tableIdent2);
+ Assertions.assertTrue(entityStore.exists(tableIdent2, TABLE));
+ }
- // Audit info is gotten from the catalog, not from the entity store
- Assertions.assertEquals("test", table2.auditInfo().creator());
+ @Test
+ void testCreateTableReportsRegistrationConflict() throws Exception {
+ NameIdentifier schema = NameIdentifier.of(metalake, catalog, "table_conflict_schema");
+ schemaOperationDispatcher.createSchema(schema, "", Map.of("k1", "v1", "k2", "v2"));
+ NameIdentifier ident = NameIdentifier.of(metalake, catalog, schema.name(), "conflicting_table");
+ Column[] columns = {
+ TestColumn.builder().withName("id").withPosition(0).withType(Types.IntegerType.get()).build()
+ };
+ EntityAlreadyExistsException conflict =
+ new EntityAlreadyExistsException("concurrent registration");
+ doThrow(conflict).when(entityStore).put(any(TableEntity.class), eq(true));
+ try {
+ TableAlreadyExistsException failure =
+ Assertions.assertThrows(
+ TableAlreadyExistsException.class,
+ () ->
+ tableOperationDispatcher.createTable(
+ ident, columns, "", Map.of("k1", "v1", "k2", "v2"), new Transform[0]));
+ Assertions.assertSame(conflict, failure.getCause());
+ Assertions.assertTrue(failure.getMessage().contains(ident.toString()));
+ Assertions.assertTrue(failure.getMessage().contains("reconcile"));
+ Assertions.assertFalse(failure.getMessage().contains("use loadTable to import"));
+ Table source =
+ catalogManager
+ .loadCatalogAndWrap(NameIdentifier.of(metalake, catalog))
+ .doWithTableOps(ops -> ops.loadTable(ident));
+ Assertions.assertEquals(ident.name(), source.name());
+ } finally {
+ reset(entityStore);
+ }
}
@Test
@@ -333,6 +391,243 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
exception.getMessage());
}
+ /** Verifies a cold table lookup preserves the missing-schema signal. */
+ @Test
+ public void testColdLoadWithMissingSchemaPreservesSchemaError() {
+ NameIdentifier ident =
+ NameIdentifier.of(metalake, catalog, "schema_missing_import", "missing_table");
+ NoSuchSchemaException error =
+ Assertions.assertThrows(
+ NoSuchSchemaException.class, () -> tableOperationDispatcher.loadTable(ident));
+ Assertions.assertTrue(error.getMessage().contains("schema_missing_import"));
+ Assertions.assertFalse(tableOperationDispatcher.tableExists(ident));
+ }
+
+ /**
+ * Verifies managed tables do not require external schema import when no registration is present.
+ *
+ * @throws Exception if fixture setup or concurrent verification fails
+ */
+ @Test
+ public void testManagedTableWithoutStoreRowDoesNotImportSchema() throws Exception {
+ Namespace ns = Namespace.of(metalake, catalog, "schema_managed_load");
+ NameIdentifier ident = NameIdentifier.of(ns, "managed_table");
+ TestCatalog source =
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
+ TestCatalogOperations operations = (TestCatalogOperations) source.ops();
+ operations.createSchema(NameIdentifier.of(ns.levels()), "", Map.of());
+ operations.createTable(
+ ident,
+ new Column[] {Column.of("col", Types.StringType.get())},
+ "managed",
+ Map.of(),
+ new Transform[0],
+ Distributions.NONE,
+ new SortOrder[0],
+ Indexes.EMPTY_INDEXES);
+ Capability original = source.capability();
+ Capability managed =
+ new Capability() {
+ @Override
+ public CapabilityResult managedStorage(Scope scope) {
+ return scope == Scope.TABLE
+ ? CapabilityResult.SUPPORTED
+ : original.managedStorage(scope);
+ }
+ };
+ FieldUtils.writeField(source, "capability", managed, true);
+ SchemaDispatcher schemaDispatcher = mock(SchemaDispatcher.class);
+ TableOperationDispatcher dispatcher =
+ new TableOperationDispatcher(
+ catalogManager, entityStore, idGenerator, () -> schemaDispatcher, secretManager);
+ try {
+ clearInvocations(entityStore);
+ Assertions.assertEquals("managed", dispatcher.loadTable(ident).comment());
+ verify(entityStore, times(1)).get(ident, TABLE, TableEntity.class);
+ verifyNoInteractions(schemaDispatcher);
+ Assertions.assertFalse(entityStore.exists(ident, TABLE));
+ } finally {
+ FieldUtils.writeField(source, "capability", original, true);
+ }
+ }
+
+ /**
+ * Verifies a native table is imported from one source read and keeps its identity on warm loads.
+ *
+ * @throws Exception if fixture setup or concurrent verification fails
+ */
+ @Test
+ public void testNativeTableImportLoadsSourceOnce() throws Exception {
+ Namespace ns = Namespace.of(metalake, catalog, "schema_import_once");
+ schemaOperationDispatcher.createSchema(
+ NameIdentifier.of(ns.levels()), "", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ NameIdentifier ident = NameIdentifier.of(ns, "native_table");
+ TestCatalog source =
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
+ TestCatalogOperations original = (TestCatalogOperations) source.ops();
+ original.createTable(
+ ident,
+ new Column[] {Column.of("col", Types.StringType.get())},
+ "native",
+ Map.of(),
+ new Transform[0],
+ Distributions.NONE,
+ new SortOrder[0],
+ Indexes.EMPTY_INDEXES);
+ TestCatalogOperations operations = spy(original);
+ FieldUtils.writeField(source, "ops", operations, true);
+ try {
+ Table loaded = tableOperationDispatcher.loadTable(ident);
+ Assertions.assertEquals("native", loaded.comment());
+ Assertions.assertTrue(entityStore.exists(ident, TABLE));
+ verify(operations, times(1)).loadTable(ident);
+ long importedId = entityStore.get(ident, TABLE, TableEntity.class).id();
+ clearInvocations(entityStore);
+ tableOperationDispatcher.loadTable(ident);
+ // Accepted cost: the preflight and warm metadata path each read the registration.
+ verify(entityStore, times(2)).get(ident, TABLE, TableEntity.class);
+ verify(operations, times(2)).loadTable(ident);
+ Assertions.assertEquals(importedId, entityStore.get(ident, TABLE, TableEntity.class).id());
+ } finally {
+ FieldUtils.writeField(source, "ops", original, true);
+ }
+ }
+
+ /**
+ * Verifies importing a native table does not contend with a sibling table write lock.
+ *
+ * @throws Exception if fixture setup or concurrent verification fails
+ */
+ @Test
+ public void testNativeImportDoesNotWaitForSiblingTableWriteLock() throws Exception {
+ Namespace ns = Namespace.of(metalake, catalog, "schema_import_sibling");
+ schemaOperationDispatcher.createSchema(
+ NameIdentifier.of(ns.levels()), "", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ NameIdentifier ident = NameIdentifier.of(ns, "native_table");
+ TestCatalog source =
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
+ ((TestCatalogOperations) source.ops())
+ .createTable(
+ ident,
+ new Column[] {Column.of("col", Types.StringType.get())},
+ "native",
+ Map.of(),
+ new Transform[0],
+ Distributions.NONE,
+ new SortOrder[0],
+ Indexes.EMPTY_INDEXES);
+ try (TreeLockTestSupport.HeldLock other =
+ TreeLockTestSupport.HeldLock.acquire(
+ NameIdentifier.of(ns, "other_table"), LockType.WRITE)) {
+ TreeLockTestSupport.assertRunsConcurrentlyWith(
+ other, () -> tableOperationDispatcher.loadTable(ident));
+ }
+ Assertions.assertTrue(entityStore.exists(ident, TABLE));
+ }
+
+ /**
+ * Verifies a blocked source import leaves sibling cold and warm table loads available.
+ *
+ * @throws Exception if fixture setup or concurrent verification fails
+ */
+ @Test
+ public void testSlowNativeImportAllowsSiblingColdAndWarmLoads() throws Exception {
+ Namespace ns = Namespace.of(metalake, catalog, "schema_import_parallel");
+ schemaOperationDispatcher.createSchema(
+ NameIdentifier.of(ns.levels()), "", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ NameIdentifier slow = NameIdentifier.of(ns, "slow_native");
+ NameIdentifier cold = NameIdentifier.of(ns, "cold_native");
+ NameIdentifier warm = NameIdentifier.of(ns, "warm_table");
+ tableOperationDispatcher.createTable(
+ warm,
+ new Column[] {Column.of("col", Types.StringType.get())},
+ "warm",
+ ImmutableMap.of("k1", "v1", "k2", "v2"));
+ TestCatalog source =
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
+ TestCatalogOperations original = (TestCatalogOperations) source.ops();
+ for (NameIdentifier ident : new NameIdentifier[] {slow, cold}) {
+ original.createTable(
+ ident,
+ new Column[] {Column.of("col", Types.StringType.get())},
+ "native",
+ Map.of(),
+ new Transform[0],
+ Distributions.NONE,
+ new SortOrder[0],
+ Indexes.EMPTY_INDEXES);
+ }
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ TestCatalogOperations operations = spy(original);
+ doAnswer(
+ invocation -> {
+ entered.countDown();
+ Assertions.assertTrue(
+ release.await(30, TimeUnit.SECONDS), "Slow source was not released");
+ return invocation.callRealMethod();
+ })
+ .when(operations)
+ .loadTable(slow);
+ FieldUtils.writeField(source, "ops", operations, true);
+ ExecutorService executor = Executors.newFixedThreadPool(3);
+ Future<Table> slowLoad = executor.submit(() -> tableOperationDispatcher.loadTable(slow));
+ try {
+ Assertions.assertTrue(entered.await(30, TimeUnit.SECONDS));
+ Future<Table> coldLoad = executor.submit(() -> tableOperationDispatcher.loadTable(cold));
+ Future<Table> warmLoad = executor.submit(() -> tableOperationDispatcher.loadTable(warm));
+ Assertions.assertEquals(cold.name(), coldLoad.get(10, TimeUnit.SECONDS).name());
+ Assertions.assertEquals(warm.name(), warmLoad.get(10, TimeUnit.SECONDS).name());
+ Assertions.assertFalse(slowLoad.isDone());
+ verify(operations, times(1)).loadTable(cold);
+ verify(operations, times(1)).loadTable(warm);
+ } finally {
+ release.countDown();
+ try {
+ Assertions.assertEquals(slow.name(), slowLoad.get(30, TimeUnit.SECONDS).name());
+ verify(operations, times(1)).loadTable(slow);
+ } finally {
+ executor.shutdownNow();
+ Assertions.assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS));
+ FieldUtils.writeField(source, "ops", original, true);
+ }
+ }
+ }
+
+ /**
+ * Verifies the import write lock waits for a reader after the preflight read can complete.
+ *
+ * @throws Exception if fixture setup or concurrent verification fails
+ */
+ @Test
+ public void testNativeImportWaitsForSameTableReadLock() throws Exception {
+ Namespace ns = Namespace.of(metalake, catalog, "schema_import_same");
+ schemaOperationDispatcher.createSchema(
+ NameIdentifier.of(ns.levels()), "", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ NameIdentifier ident = NameIdentifier.of(ns, "native_table");
+ TestCatalog source =
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
+ ((TestCatalogOperations) source.ops())
+ .createTable(
+ ident,
+ new Column[] {Column.of("col", Types.StringType.get())},
+ "native",
+ Map.of(),
+ new Transform[0],
+ Distributions.NONE,
+ new SortOrder[0],
+ Indexes.EMPTY_INDEXES);
+ try (TreeLockTestSupport.HeldLock same =
+ TreeLockTestSupport.HeldLock.acquire(ident, LockType.READ)) {
+ TreeLockTestSupport.assertWaitsFor(same, () -> tableOperationDispatcher.loadTable(ident));
+ }
+ }
+
@Test
public void testConcurrentImportTableReusesExistingEntity() throws IOException {
Namespace tableNs = Namespace.of(metalake, catalog, "schema52");
@@ -713,13 +1008,49 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
});
}
+ /**
+ * Verifies native columns at the old and new boundaries survive import and repeated loads.
+ *
+ * @param length the native column name length
+ * @throws IOException if the test store cannot be accessed
+ */
+ @ParameterizedTest
+ @ValueSource(ints = {128, 129, 300})
+ public void testImportNativeTableWithLongColumnName(int length) throws IOException {
+ Namespace ns = Namespace.of(metalake, catalog, "schema_native_long_column_" + length);
+ schemaOperationDispatcher.createSchema(
+ NameIdentifier.of(ns.levels()), "", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ NameIdentifier ident = NameIdentifier.of(ns, "native_table");
+ String columnName = "c".repeat(length);
+ Column[] columns = new Column[] {Column.of(columnName, Types.StringType.get())};
+ TestCatalog source =
+ (TestCatalog)
+ catalogManager.loadCatalogAndWrap(NameIdentifier.of(metalake, catalog)).catalog();
+ ((TestCatalogOperations) source.ops())
+ .createTable(
+ ident,
+ columns,
+ "native",
+ Map.of(),
+ new Transform[0],
+ Distributions.NONE,
+ new SortOrder[0],
+ Indexes.EMPTY_INDEXES);
+ Assertions.assertEquals(
+ columnName, tableOperationDispatcher.loadTable(ident).columns()[0].name());
+ Assertions.assertEquals(
+ columnName, entityStore.get(ident, TABLE, TableEntity.class).columns().get(0).name());
+ Assertions.assertEquals(
+ columnName, tableOperationDispatcher.loadTable(ident).columns()[0].name());
+ }
+
@Test
public void testRejectsOversizedColumnFieldsBeforeExternalChange() throws IOException {
Namespace tableNs = Namespace.of(metalake, catalog, "schema_column_field_limits");
NameIdentifier validTableIdent = NameIdentifier.of(tableNs, "valid_table");
NameIdentifier invalidNameTableIdent = NameIdentifier.of(tableNs, "invalid_column_name");
NameIdentifier invalidCommentTableIdent = NameIdentifier.of(tableNs, "invalid_column_comment");
- String oversizedName = "a".repeat(EntityFieldLimits.MAX_NAME_LENGTH + 1);
+ String oversizedName = "a".repeat(EntityFieldLimits.MAX_COLUMN_NAME_LENGTH + 1);
String oversizedComment = "a".repeat(EntityFieldLimits.MAX_COLUMN_COMMENT_LENGTH + 1);
Map<String, String> props = ImmutableMap.of("k1", "v1", "k2", "v2");
Column validColumn =
@@ -749,7 +1080,7 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
props,
new Transform[0]));
Assertions.assertEquals(
- "The name of the column must not exceed 128 characters", createNameException.getMessage());
+ "The name of the column must not exceed 300 characters", createNameException.getMessage());
IllegalArgumentException createCommentException =
Assertions.assertThrows(
@@ -783,7 +1114,7 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
validTableIdent,
TableChange.addColumn(new String[] {oversizedName}, Types.StringType.get())));
Assertions.assertEquals(
- "The name of the column must not exceed 128 characters", addNameException.getMessage());
+ "The name of the column must not exceed 300 characters", addNameException.getMessage());
IllegalArgumentException addCommentException =
Assertions.assertThrows(
@@ -805,7 +1136,7 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
validTableIdent,
TableChange.renameColumn(new String[] {"col1"}, oversizedName)));
Assertions.assertEquals(
- "The name of the column must not exceed 128 characters", renameException.getMessage());
+ "The name of the column must not exceed 300 characters", renameException.getMessage());
IllegalArgumentException updateCommentException =
Assertions.assertThrows(
@@ -2246,7 +2577,7 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
@Test
public void testCreateTableWaitsForSchemaWriteLock() throws Exception {
- // Rename, drop and import of tables in the schema take the schema WRITE lock.
+ // Rename and drop of tables in the schema take the schema WRITE lock.
Namespace tableNs = Namespace.of(metalake, catalog, "schema_create_lock_3");
NameIdentifier schemaIdent = NameIdentifier.of(tableNs.levels());
schemaOperationDispatcher.createSchema(
diff --git a/core/src/test/java/org/apache/gravitino/meta/TestEntityFieldLimits.java b/core/src/test/java/org/apache/gravitino/meta/TestEntityFieldLimits.java
index eab52d2474..78eff70279 100644
--- a/core/src/test/java/org/apache/gravitino/meta/TestEntityFieldLimits.java
+++ b/core/src/test/java/org/apache/gravitino/meta/TestEntityFieldLimits.java
@@ -76,6 +76,16 @@ public class TestEntityFieldLimits {
assertLengthLimit(builder, "alias", "model version", EntityFieldLimits.MAX_NAME_LENGTH);
}
+ /** Verifies column names use their own limit while other entity names keep the existing limit. */
+ @Test
+ public void testColumnNameLength() {
+ assertLengthLimit(
+ name -> columnBuilder(name, null),
+ "name",
+ "column",
+ EntityFieldLimits.MAX_COLUMN_NAME_LENGTH);
+ }
+
@Test
public void testColumnCommentLength() {
assertLengthLimit(
@@ -129,7 +139,6 @@ public class TestEntityFieldLimits {
private static Stream<Arguments> nameBuilders() {
return Stream.of(
- Arguments.of("column", (Function<String, Entity>) name -> columnBuilder(name, null)),
Arguments.of(
"table",
(Function<String, Entity>)
diff --git a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
index 008b5b75a2..6b04a69b0f 100644
--- a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
+++ b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
@@ -400,6 +400,45 @@ public class TestSQLScripts extends TestJDBCBackend {
}
}
+ /**
+ * Verifies the 2.0 migration expands column names and preserves data on retry.
+ *
+ * @throws SQLException if the migrated database cannot be queried
+ * @throws IOException if the scripts cannot be read
+ */
+ @TestTemplate
+ public void testUpgradeToTwoZeroSupportsLongColumnNames() throws SQLException, IOException {
+ Path scriptDir = upgradeScriptDirectory();
+ String suffix = "-" + backendType.toLowerCase() + ".sql";
+ File upgrade = scriptDir.resolve("upgrade-1.3.0-to-2.0.0" + suffix).toFile();
+ dropAllTables();
+ executeScript(scriptDir.resolve("schema-1.3.0" + suffix).toFile());
+ String insert =
+ "INSERT INTO table_column_version_info "
+ + "(metalake_id, catalog_id, schema_id, table_id, table_version, column_id, column_name, "
+ + "column_position, column_type, column_op_type, audit_info) "
+ + "VALUES (1, 2, 3, 4, 1, %d, '%s', 0, 'string', 0, '{}')";
+ String oldName = "c".repeat(128);
+ executeStatements(List.of(String.format(insert, 1, oldName)), "existing 1.3 column");
+ executeScript(upgrade);
+ String longName = "c".repeat(300);
+ executeStatements(List.of(String.format(insert, 2, longName)), "new long column");
+ executeScript(upgrade);
+ try (SqlSession sqlSession =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = sqlSession.getConnection();
+ Statement statement = connection.createStatement();
+ ResultSet rows =
+ statement.executeQuery(
+ "SELECT column_name FROM table_column_version_info ORDER BY column_id")) {
+ Assertions.assertTrue(rows.next());
+ Assertions.assertEquals(oldName, rows.getString(1));
+ Assertions.assertTrue(rows.next());
+ Assertions.assertEquals(longName, rows.getString(1));
+ Assertions.assertFalse(rows.next());
+ }
+ }
+
/** Verifies a completed upgrade can be repeated without resetting migrated data. */
@TestTemplate
public void testUpgradeToTwoZeroIsIdempotent() throws SQLException, IOException {
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSchemaMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSchemaMetaService.java
index 7c51e764af..506973a73d 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSchemaMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSchemaMetaService.java
@@ -44,7 +44,10 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.NameIdentifier;
@@ -80,6 +83,7 @@ import org.apache.gravitino.storage.relational.po.SchemaPO;
import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.session.SqlSessions;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.utils.NameIdentifierUtil;
@@ -87,6 +91,7 @@ import org.apache.gravitino.utils.NamespaceUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.TestTemplate;
+import org.mockito.AdditionalAnswers;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
@@ -94,6 +99,255 @@ public class TestSchemaMetaService extends TestJDBCBackend {
private final String metalakeName = "metalake_for_catalog_test";
private final String catalogName = "catalog_for_catalog_test";
+ @TestTemplate
+ void testOverwriteDifferentSchemaIdPreservesRegisteredHierarchy() throws Exception {
+ createAndInsertMakeLake(metalakeName);
+ createAndInsertCatalog(metalakeName, catalogName);
+ SchemaEntity stale = createAndInsertSchema(metalakeName, catalogName, "stale_schema");
+ SchemaEntity nested = createAndInsertSchema(metalakeName, catalogName, "stale_schema:child");
+ TableEntity child =
+ createAndInsertTableEntity(
+ Namespace.of(metalakeName, catalogName, stale.name()), "old_table");
+ TagEntity tag = createAndInsertTagEntity("tag_on_stale_schema", "", metalakeName);
+ TagMetaService.getInstance()
+ .associateTagsWithMetadataObject(
+ stale.nameIdentifier(),
+ Entity.EntityType.SCHEMA,
+ new NameIdentifier[] {tag.nameIdentifier()},
+ new NameIdentifier[0]);
+ SchemaEntity replacement =
+ createSchemaEntity(
+ RandomIdGenerator.INSTANCE.nextId(), stale.namespace(), stale.name(), AUDIT_INFO);
+ EntityAlreadyExistsException conflict =
+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(replacement, true));
+ assertTrue(conflict.getMessage().contains(stale.nameIdentifier().toString()));
+ assertTrue(conflict.getMessage().contains("Reconcile the existing registration"));
+ Assertions.assertEquals(
+ stale.id(),
+ backend.<SchemaEntity>get(stale.nameIdentifier(), Entity.EntityType.SCHEMA).id());
+ Assertions.assertEquals(
+ child.id(), backend.<TableEntity>get(child.nameIdentifier(), Entity.EntityType.TABLE).id());
+ Assertions.assertEquals(
+ nested.id(),
+ backend.<SchemaEntity>get(nested.nameIdentifier(), Entity.EntityType.SCHEMA).id());
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = session.getConnection();
+ Statement statement = connection.createStatement();
+ ResultSet rows =
+ statement.executeQuery(
+ "SELECT COUNT(*) FROM tag_relation_meta WHERE metadata_object_id = "
+ + stale.id()
+ + " AND deleted_at = 0")) {
+ assertTrue(rows.next());
+ Assertions.assertEquals(1, rows.getLong(1));
+ }
+ }
+
+ @TestTemplate
+ void testOverwriteSameSchemaIdKeepsChildren() throws Exception {
+ createAndInsertMakeLake(metalakeName);
+ createAndInsertCatalog(metalakeName, catalogName);
+ SchemaEntity original = createAndInsertSchema(metalakeName, catalogName, "same_schema_id");
+ TableEntity child =
+ createAndInsertTableEntity(
+ Namespace.of(metalakeName, catalogName, original.name()), "retained_table");
+ backend.insert(
+ createSchemaEntity(original.id(), original.namespace(), original.name(), AUDIT_INFO), true);
+ Assertions.assertEquals(
+ original.id(),
+ backend.<SchemaEntity>get(original.nameIdentifier(), Entity.EntityType.SCHEMA).id());
+ Assertions.assertEquals(
+ child.id(), backend.<TableEntity>get(child.nameIdentifier(), Entity.EntityType.TABLE).id());
+ }
+
+ @TestTemplate
+ void testOverwriteDoesNotStealSchemaIdFromAnotherCatalog() throws Exception {
+ createAndInsertMakeLake(metalakeName);
+ createAndInsertCatalog(metalakeName, catalogName);
+ createAndInsertCatalog(metalakeName, "other_catalog");
+ SchemaEntity original =
+ createAndInsertSchema(metalakeName, catalogName, "schema_identity_conflict");
+ SchemaEntity other = createAndInsertSchema(metalakeName, "other_catalog", "other_schema");
+ TableEntity child =
+ createAndInsertTableEntity(
+ Namespace.of(metalakeName, catalogName, original.name()), "retained_table");
+ SchemaEntity conflicting =
+ createSchemaEntity(other.id(), original.namespace(), original.name(), AUDIT_INFO);
+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(conflicting, true));
+ Assertions.assertEquals(
+ original.id(),
+ backend.<SchemaEntity>get(original.nameIdentifier(), Entity.EntityType.SCHEMA).id());
+ Assertions.assertEquals(
+ other.id(),
+ backend.<SchemaEntity>get(other.nameIdentifier(), Entity.EntityType.SCHEMA).id());
+ Assertions.assertEquals(
+ child.id(), backend.<TableEntity>get(child.nameIdentifier(), Entity.EntityType.TABLE).id());
+ }
+
+ @TestTemplate
+ void testOverwriteCanReviveRetiredSchemaIdentityInNewCatalog() throws Exception {
+ createAndInsertMakeLake(metalakeName);
+ CatalogEntity oldCatalog = createAndInsertCatalog(metalakeName, catalogName);
+ createAndInsertCatalog(metalakeName, "new_catalog");
+ SchemaEntity retired = createAndInsertSchema(metalakeName, catalogName, "retired_schema");
+ TableEntity child =
+ createAndInsertTableEntity(
+ Namespace.of(metalakeName, catalogName, retired.name()), "old_table");
+ backend.delete(oldCatalog.nameIdentifier(), Entity.EntityType.CATALOG, true);
+ SchemaEntity revived =
+ createSchemaEntity(
+ retired.id(), Namespace.of(metalakeName, "new_catalog"), retired.name(), AUDIT_INFO);
+ backend.insert(revived, true);
+ Assertions.assertEquals(
+ revived.id(),
+ backend.<SchemaEntity>get(revived.nameIdentifier(), Entity.EntityType.SCHEMA).id());
+ assertFalse(backend.exists(child.nameIdentifier(), Entity.EntityType.TABLE));
+ }
+
+ @TestTemplate
+ void testConcurrentRevivalOfRetiredSchemaIdKeepsOneOwner() throws Exception {
+ createAndInsertMakeLake(metalakeName);
+ createAndInsertCatalog(metalakeName, catalogName);
+ createAndInsertCatalog(metalakeName, "first_revival_catalog");
+ createAndInsertCatalog(metalakeName, "second_revival_catalog");
+ SchemaEntity retired = createAndInsertSchema(metalakeName, catalogName, "retired_identity");
+ backend.delete(retired.nameIdentifier(), Entity.EntityType.SCHEMA, true);
+ SchemaEntity first =
+ createSchemaEntity(
+ retired.id(),
+ Namespace.of(metalakeName, "first_revival_catalog"),
+ "revived",
+ AUDIT_INFO);
+ SchemaEntity second =
+ createSchemaEntity(
+ retired.id(),
+ Namespace.of(metalakeName, "second_revival_catalog"),
+ "revived",
+ AUDIT_INFO);
+ CountDownLatch lockingReadsStarted = new CountDownLatch(2);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<Throwable> firstResult;
+ Future<Throwable> secondResult;
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(false)) {
+ SchemaPO locked =
+ session
+ .getMapper(SchemaMetaMapper.class)
+ .selectSchemaMetaByIdIncludingDeletedForUpdate(retired.id());
+ Assertions.assertNotNull(locked);
+ assertTrue(locked.getDeletedAt() > 0);
+ firstResult =
+ executor.submit(() -> reviveSchemaAfterIdentityCheck(first, lockingReadsStarted));
+ secondResult =
+ executor.submit(() -> reviveSchemaAfterIdentityCheck(second, lockingReadsStarted));
+ // Both non-locking checks have observed no active owner. Hold the retired row until both
+ // writers reach the locking read, forcing the loser to revalidate the winner's active ID.
+ assertTrue(lockingReadsStarted.await(30, TimeUnit.SECONDS));
+ session.commit();
+ }
+ Throwable firstFailure = firstResult.get(30, TimeUnit.SECONDS);
+ Throwable secondFailure = secondResult.get(30, TimeUnit.SECONDS);
+ assertTrue((firstFailure == null) != (secondFailure == null), "Exactly one revival must win");
+ Assertions.assertInstanceOf(
+ EntityAlreadyExistsException.class, firstFailure == null ? secondFailure : firstFailure);
+ SchemaEntity winner = firstFailure == null ? first : second;
+ SchemaEntity loser = firstFailure == null ? second : first;
+ Assertions.assertEquals(
+ retired.id(),
+ backend.<SchemaEntity>get(winner.nameIdentifier(), Entity.EntityType.SCHEMA).id());
+ assertFalse(backend.exists(loser.nameIdentifier(), Entity.EntityType.SCHEMA));
+ } finally {
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS));
+ }
+ }
+
+ @TestTemplate
+ void testNewSchemaIdCannotOverwriteConcurrentWinnerInAnotherCatalog() throws Exception {
+ createAndInsertMakeLake(metalakeName);
+ CatalogEntity targetCatalog = createAndInsertCatalog(metalakeName, catalogName);
+ createAndInsertCatalog(metalakeName, "winning_catalog");
+ SchemaEntity original =
+ createAndInsertSchema(metalakeName, catalogName, "schema_losing_registration");
+ long sharedId = RandomIdGenerator.INSTANCE.nextId();
+ SchemaEntity losing =
+ createSchemaEntity(sharedId, original.namespace(), "unregistered_schema", AUDIT_INFO);
+ SchemaEntity winner =
+ createSchemaEntity(
+ sharedId, Namespace.of(metalakeName, "winning_catalog"), "winning_schema", AUDIT_INFO);
+ SchemaMetaService service = SchemaMetaService.getInstance();
+ BasePOStorageOps<SchemaPO, SchemaMetaMapper> originalOps = service.ops();
+ BasePOStorageOps<SchemaPO, SchemaMetaMapper> racedOps = Mockito.spy(originalOps);
+ AtomicBoolean insertedWinner = new AtomicBoolean();
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ Mockito.doAnswer(
+ invocation -> {
+ List<SchemaPO> rows = invocation.getArgument(1);
+ if (rows.size() == 1
+ && Objects.equals(rows.get(0).getCatalogId(), targetCatalog.id())
+ && insertedWinner.compareAndSet(false, true)) {
+ executor
+ .submit(
+ () -> {
+ backend.insert(winner, true);
+ return null;
+ })
+ .get(30, TimeUnit.SECONDS);
+ }
+ return invocation.callRealMethod();
+ })
+ .when(racedOps)
+ .batchInsertPOs(Mockito.any(), Mockito.anyList(), Mockito.anyBoolean());
+ FieldUtils.writeField(service, "ops", racedOps, true);
+ try {
+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(losing, true));
+ } finally {
+ FieldUtils.writeField(service, "ops", originalOps, true);
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS));
+ }
+ assertTrue(insertedWinner.get());
+ assertFalse(backend.exists(losing.nameIdentifier(), Entity.EntityType.SCHEMA));
+ Assertions.assertEquals(
+ original.id(),
+ backend.<SchemaEntity>get(original.nameIdentifier(), Entity.EntityType.SCHEMA).id());
+ Assertions.assertEquals(
+ winner.id(),
+ backend.<SchemaEntity>get(winner.nameIdentifier(), Entity.EntityType.SCHEMA).id());
+ }
+
+ @TestTemplate
+ void testSameIdentityOverwriteRollsBackIfWriteFails() throws Exception {
+ createAndInsertMakeLake(metalakeName);
+ createAndInsertCatalog(metalakeName, catalogName);
+ SchemaEntity original =
+ createAndInsertSchema(metalakeName, catalogName, "schema_replace_rollback");
+ TableEntity child =
+ createAndInsertTableEntity(
+ Namespace.of(metalakeName, catalogName, original.name()), "retained_table");
+ SchemaEntity replacement =
+ createSchemaEntity(original.id(), original.namespace(), original.name(), AUDIT_INFO);
+ SchemaMetaService service = SchemaMetaService.getInstance();
+ BasePOStorageOps<SchemaPO, SchemaMetaMapper> originalOps = service.ops();
+ BasePOStorageOps<SchemaPO, SchemaMetaMapper> failingOps = Mockito.spy(originalOps);
+ Mockito.doThrow(new IllegalStateException("new schema insert failed"))
+ .when(failingOps)
+ .batchInsertPOs(Mockito.any(), Mockito.anyList(), Mockito.anyBoolean());
+ FieldUtils.writeField(service, "ops", failingOps, true);
+ try {
+ assertThrows(IllegalStateException.class, () -> backend.insert(replacement, true));
+ } finally {
+ FieldUtils.writeField(service, "ops", originalOps, true);
+ }
+ Assertions.assertEquals(
+ original.id(),
+ backend.<SchemaEntity>get(original.nameIdentifier(), Entity.EntityType.SCHEMA).id());
+ Assertions.assertEquals(
+ child.id(), backend.<TableEntity>get(child.nameIdentifier(), Entity.EntityType.TABLE).id());
+ }
+
@TestTemplate
void testDeleteSchemaAndGetRollsBackWhenCleanupFails() throws IOException {
createAndInsertMakeLake(metalakeName);
@@ -2423,4 +2677,37 @@ public class TestSchemaMetaService extends TestJDBCBackend {
private interface SchemaChildMove {
void run(NameIdentifier childIdentifier, String targetSchemaName) throws Exception;
}
+
+ @Nullable
+ private Throwable reviveSchemaAfterIdentityCheck(
+ SchemaEntity schema, CountDownLatch lockingReadsStarted) {
+ // Static mocks are thread-local: install this observer in each database writer, and delegate
+ // every mapper call to the real session so the row locks and transaction remain real.
+ try (MockedStatic<SqlSessions> sessions =
+ Mockito.mockStatic(
+ SqlSessions.class,
+ invocation -> {
+ Object result = invocation.callRealMethod();
+ if (!"getMapper".equals(invocation.getMethod().getName())
+ || invocation.getArgument(0) != SchemaMetaMapper.class) {
+ return result;
+ }
+ SchemaMetaMapper actual = (SchemaMetaMapper) result;
+ SchemaMetaMapper observed =
+ Mockito.mock(SchemaMetaMapper.class, AdditionalAnswers.delegatesTo(actual));
+ Mockito.doAnswer(
+ call -> {
+ lockingReadsStarted.countDown();
+ return actual.selectSchemaMetaByIdIncludingDeletedForUpdate(schema.id());
+ })
+ .when(observed)
+ .selectSchemaMetaByIdIncludingDeletedForUpdate(schema.id());
+ return observed;
+ })) {
+ backend.insert(schema, true);
+ return null;
+ } catch (Throwable failure) {
+ return failure;
+ }
+ }
}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableMetaService.java
index 4e4fc85f34..c3dc239748 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableMetaService.java
@@ -117,6 +117,32 @@ public class TestTableMetaService extends TestJDBCBackend {
Assertions.assertNull(TableMetaService.getInstance().getMetalakeNameByTableId(table.id() + 1));
}
+ /**
+ * Verifies every relational backend stores the full 300-character column name and its identity.
+ *
+ * @throws IOException if the backend write fails
+ */
+ @TestTemplate
+ public void testLongColumnNamesRoundTrip() throws IOException {
+ createParentEntities(metalakeName, catalogName, schemaName, AUDIT_INFO);
+ Namespace namespace = NamespaceUtil.ofTable(metalakeName, catalogName, schemaName);
+ String name = "c".repeat(300);
+ ColumnEntity original = column(name, Types.StringType.get());
+ TableEntity table =
+ TableEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName("table_long_column")
+ .withNamespace(namespace)
+ .withColumns(List.of(original))
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ TableMetaService service = TableMetaService.getInstance();
+ service.insertTable(table, false);
+ TableEntity loaded = service.getTableByIdentifier(table.nameIdentifier());
+ Assertions.assertEquals(name, loaded.columns().get(0).name());
+ Assertions.assertEquals(original.id(), loaded.columns().get(0).id());
+ }
+
@TestTemplate
public void testLegacyTimelineDeleteKeepsLiveVersionsOfSameTable() throws Exception {
createAndInsertMakeLake(metalakeName);
diff --git a/core/src/test/java/org/apache/gravitino/utils/TestBoundedConnectionDriver.java b/core/src/test/java/org/apache/gravitino/utils/TestBoundedConnectionDriver.java
new file mode 100644
index 0000000000..39846d168e
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/utils/TestBoundedConnectionDriver.java
@@ -0,0 +1,547 @@
+/*
+ * 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.gravitino.utils;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTimeout;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import java.security.AccessController;
+import java.security.PrivilegedExceptionAction;
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.SQLException;
+import java.sql.SQLTimeoutException;
+import java.sql.SQLTransientConnectionException;
+import java.time.Duration;
+import java.util.Properties;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.security.auth.Subject;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+class TestBoundedConnectionDriver {
+ private final ExecutorService workers = Executors.newSingleThreadExecutor();
+
+ @AfterEach
+ void close() throws Exception {
+ workers.shutdownNow();
+ assertTrue(workers.awaitTermination(10, TimeUnit.SECONDS));
+ }
+
+ @Test
+ void testSuccessfulHandoffAndContextRestoration() throws Exception {
+ Driver driver = mock(Driver.class);
+ Connection connection = mock(Connection.class);
+ Properties properties = new Properties();
+ properties.setProperty("user", "test");
+ ClassLoader workerLoader =
+ workers.submit(() -> Thread.currentThread().getContextClassLoader()).get();
+ ClassLoader callerLoader = new ClassLoader(workerLoader) {};
+ AtomicReference<Properties> received = new AtomicReference<>();
+ when(driver.connect(eq("jdbc:test"), any()))
+ .thenAnswer(
+ invocation -> {
+ assertSame(callerLoader, Thread.currentThread().getContextClassLoader());
+ received.set(invocation.getArgument(1));
+ return connection;
+ });
+ ClassLoader previous = Thread.currentThread().getContextClassLoader();
+ try {
+ Thread.currentThread().setContextClassLoader(callerLoader);
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 5000, workers);
+ assertSame(connection, bounded.connect("jdbc:test", properties));
+ } finally {
+ Thread.currentThread().setContextClassLoader(previous);
+ }
+ assertEquals(properties, received.get());
+ assertNotSame(properties, received.get());
+ assertSame(
+ workerLoader, workers.submit(() -> Thread.currentThread().getContextClassLoader()).get());
+ verify(connection, never()).close();
+ }
+
+ @Test
+ @SuppressWarnings("removal")
+ void testConnectPreservesCallerSubjectOnExistingWorker() throws Exception {
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ Driver driver = mock(Driver.class);
+ Connection connection = mock(Connection.class);
+ AtomicReference<Subject> observed = new AtomicReference<>();
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ observed.set(Subject.getSubject(AccessController.getContext()));
+ return connection;
+ });
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 5000, workers);
+ Subject subject = new Subject();
+
+ assertSame(
+ connection,
+ Subject.doAs(
+ subject,
+ (PrivilegedExceptionAction<Connection>)
+ () -> bounded.connect("jdbc:test", new Properties())));
+ assertSame(subject, observed.get());
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ assertNull(workers.submit(() -> Subject.getSubject(AccessController.getContext())).get());
+ }
+
+ @Test
+ @SuppressWarnings("removal")
+ void testReusedWorkerDoesNotAuthenticateAsPreviousCaller() throws Exception {
+ Driver driver = mock(Driver.class);
+ AtomicReference<Subject> observed = new AtomicReference<>();
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ observed.set(Subject.getSubject(AccessController.getContext()));
+ return null;
+ });
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 5000, workers);
+ Subject first = new Subject();
+ Subject second = new Subject();
+ Subject.doAs(
+ first,
+ (PrivilegedExceptionAction<Connection>)
+ () -> bounded.connect("jdbc:test", new Properties()));
+ assertSame(first, observed.get());
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ Subject.doAs(
+ second,
+ (PrivilegedExceptionAction<Connection>)
+ () -> bounded.connect("jdbc:test", new Properties()));
+ assertSame(second, observed.get());
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ bounded.connect("jdbc:test", new Properties());
+ assertNull(observed.get());
+ }
+
+ @Test
+ @SuppressWarnings("removal")
+ void testSharedWorkerDoesNotInheritCreatingCallerSubject() throws Exception {
+ ThreadPoolExecutor pool =
+ (ThreadPoolExecutor)
+ FieldUtils.readStaticField(BoundedConnectionDriver.class, "WORKERS", true);
+ AtomicReference<Subject> observed = new AtomicReference<>();
+ Subject subject = new Subject();
+ Thread worker =
+ Subject.doAs(
+ subject,
+ (PrivilegedExceptionAction<Thread>)
+ () ->
+ pool.getThreadFactory()
+ .newThread(
+ () -> observed.set(Subject.getSubject(AccessController.getContext()))));
+ worker.start();
+ worker.join(10000);
+ assertFalse(worker.isAlive());
+ assertNull(observed.get());
+ }
+
+ @Test
+ @SuppressWarnings("removal")
+ void testLateClosePreservesSubmittingSubject() throws Exception {
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ Driver driver = mock(Driver.class);
+ Connection late = mock(Connection.class);
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ AtomicReference<Subject> observed = new AtomicReference<>();
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ entered.countDown();
+ awaitIgnoringInterrupts(release);
+ return late;
+ });
+ doAnswer(
+ invocation -> {
+ observed.set(Subject.getSubject(AccessController.getContext()));
+ return null;
+ })
+ .when(late)
+ .close();
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 100, workers);
+ Subject subject = new Subject();
+ try {
+ Subject.doAs(
+ subject,
+ (PrivilegedExceptionAction<Void>)
+ () -> {
+ assertThrows(
+ SQLTimeoutException.class,
+ () -> bounded.connect("jdbc:test", new Properties()));
+ return null;
+ });
+ assertTrue(entered.await(10, TimeUnit.SECONDS));
+ } finally {
+ release.countDown();
+ }
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ verify(late).close();
+ assertSame(subject, observed.get());
+ assertNull(workers.submit(() -> Subject.getSubject(AccessController.getContext())).get());
+ }
+
+ @Test
+ void testNullPropertiesArePassedAsEmptyProperties() throws Exception {
+ Driver driver = mock(Driver.class);
+ Connection connection = mock(Connection.class);
+ AtomicReference<Properties> received = new AtomicReference<>();
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ received.set(invocation.getArgument(1));
+ return connection;
+ });
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 5000, workers);
+ assertSame(connection, bounded.connect("jdbc:test", null));
+ assertNotNull(received.get());
+ assertTrue(received.get().isEmpty());
+ }
+
+ @Test
+ void testLateCloseRunsWithoutCancellationInterrupt() throws Exception {
+ Driver driver = mock(Driver.class);
+ Connection late = mock(Connection.class);
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ AtomicReference<Boolean> closed = new AtomicReference<>(false);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ entered.countDown();
+ awaitIgnoringInterrupts(release);
+ return late;
+ });
+ doAnswer(
+ invocation -> {
+ if (Thread.currentThread().isInterrupted()) {
+ throw new SQLException("Cleanup interrupted before closing the connection");
+ }
+ closed.set(true);
+ return null;
+ })
+ .when(late)
+ .close();
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 100, workers);
+ try {
+ assertThrows(SQLTimeoutException.class, () -> bounded.connect("jdbc:test", new Properties()));
+ assertTrue(entered.await(10, TimeUnit.SECONDS));
+ } finally {
+ release.countDown();
+ }
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ assertTrue(closed.get(), "The physical connection must close despite cancellation");
+ }
+
+ @Test
+ void testSqlFailurePreservesCauseAndState() throws Exception {
+ Driver driver = mock(Driver.class);
+ SQLException failure = new SQLException("backend refused", "28000", 17);
+ when(driver.connect(anyString(), any())).thenThrow(failure);
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 5000, workers);
+ assertSame(
+ failure,
+ assertThrows(SQLException.class, () -> bounded.connect("jdbc:test", new Properties())));
+ }
+
+ @Test
+ void testUnsupportedUrlReturnsNull() throws Exception {
+ Driver driver = mock(Driver.class);
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 5000, workers);
+ assertNull(bounded.connect("jdbc:unsupported", new Properties()));
+ }
+
+ @Test
+ void testTimeoutClosesLateConnectionAndQuarantinesUntilCleanup() throws Exception {
+ Driver driver = mock(Driver.class);
+ Connection late = mock(Connection.class);
+ Connection healthy = mock(Connection.class);
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ CountDownLatch closed = new CountDownLatch(1);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ entered.countDown();
+ awaitIgnoringInterrupts(release);
+ return late;
+ })
+ .thenReturn(healthy);
+ doAnswer(
+ invocation -> {
+ closed.countDown();
+ return null;
+ })
+ .when(late)
+ .close();
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 100, workers);
+ try {
+ SQLTimeoutException error =
+ assertTimeout(
+ Duration.ofSeconds(3),
+ () ->
+ assertThrows(
+ SQLTimeoutException.class,
+ () -> bounded.connect("jdbc:test", new Properties())));
+ assertTrue(entered.await(10, TimeUnit.SECONDS));
+ assertTrue(error.getMessage().contains("100 ms"));
+ assertEquals("08001", error.getSQLState());
+ assertNotNull(error.getCause());
+ assertThrows(
+ SQLTransientConnectionException.class,
+ () -> bounded.connect("jdbc:test", new Properties()));
+ verify(driver, times(1)).connect(anyString(), any());
+ verify(late, never()).close();
+ } finally {
+ release.countDown();
+ }
+ assertTrue(closed.await(10, TimeUnit.SECONDS));
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ assertSame(healthy, bounded.connect("jdbc:test", new Properties()));
+ verify(late, times(1)).close();
+ verify(late, never()).createStatement();
+ }
+
+ @Test
+ void testBlockedLateCloseKeepsQuarantineUntilCleanupCompletes() throws Exception {
+ Driver driver = mock(Driver.class);
+ Connection late = mock(Connection.class);
+ Connection healthy = mock(Connection.class);
+ CountDownLatch connectEntered = new CountDownLatch(1);
+ CountDownLatch releaseConnect = new CountDownLatch(1);
+ CountDownLatch closeEntered = new CountDownLatch(1);
+ CountDownLatch releaseClose = new CountDownLatch(1);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ connectEntered.countDown();
+ awaitIgnoringInterrupts(releaseConnect);
+ return late;
+ })
+ .thenReturn(healthy);
+ doAnswer(
+ invocation -> {
+ closeEntered.countDown();
+ awaitIgnoringInterrupts(releaseClose);
+ return null;
+ })
+ .when(late)
+ .close();
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 100, workers);
+ try {
+ assertThrows(SQLTimeoutException.class, () -> bounded.connect("jdbc:test", new Properties()));
+ assertTrue(connectEntered.await(10, TimeUnit.SECONDS));
+ releaseConnect.countDown();
+ assertTrue(closeEntered.await(10, TimeUnit.SECONDS));
+ SQLTransientConnectionException error =
+ assertThrows(
+ SQLTransientConnectionException.class,
+ () -> bounded.connect("jdbc:test", new Properties()));
+ assertEquals("08001", error.getSQLState());
+ verify(driver, times(1)).connect(anyString(), any());
+ } finally {
+ releaseConnect.countDown();
+ releaseClose.countDown();
+ }
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ assertSame(healthy, bounded.connect("jdbc:test", new Properties()));
+ verify(late, times(1)).close();
+ }
+
+ @Test
+ void testCallerInterruptClosesLateConnection() throws Exception {
+ Driver driver = mock(Driver.class);
+ Connection late = mock(Connection.class);
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ CountDownLatch closed = new CountDownLatch(1);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ entered.countDown();
+ awaitIgnoringInterrupts(release);
+ return late;
+ });
+ doAnswer(
+ invocation -> {
+ closed.countDown();
+ return null;
+ })
+ .when(late)
+ .close();
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 30000, workers);
+ AtomicReference<Throwable> failure = new AtomicReference<>();
+ Thread caller =
+ new Thread(
+ () -> {
+ try {
+ assertThrows(
+ SQLTimeoutException.class,
+ () -> bounded.connect("jdbc:test", new Properties()));
+ assertTrue(Thread.currentThread().isInterrupted());
+ } catch (Throwable error) {
+ failure.set(error);
+ }
+ });
+ caller.start();
+ try {
+ assertTrue(entered.await(10, TimeUnit.SECONDS));
+ caller.interrupt();
+ caller.join(10000);
+ assertFalse(caller.isAlive());
+ assertNull(failure.get());
+ } finally {
+ release.countDown();
+ caller.interrupt();
+ caller.join(10000);
+ }
+ assertTrue(closed.await(10, TimeUnit.SECONDS));
+ verify(late, times(1)).close();
+ }
+
+ @Test
+ void testTimeoutBeforeWorkerStartsDoesNotOpenLateConnection() throws Exception {
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ Future<?> blocking =
+ workers.submit(
+ () -> {
+ entered.countDown();
+ awaitIgnoringInterrupts(release);
+ });
+ assertTrue(entered.await(10, TimeUnit.SECONDS));
+ Driver driver = mock(Driver.class);
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 100, workers);
+ try {
+ assertThrows(SQLTimeoutException.class, () -> bounded.connect("jdbc:test", new Properties()));
+ verifyNoInteractions(driver);
+ } finally {
+ release.countDown();
+ }
+ blocking.get(10, TimeUnit.SECONDS);
+ workers.submit(() -> {}).get(10, TimeUnit.SECONDS);
+ assertNull(bounded.connect("jdbc:unsupported", new Properties()));
+ verify(driver, times(1)).connect(anyString(), any());
+ }
+
+ @Test
+ void testSaturationRejectsWithoutCallingDriver() throws Exception {
+ ExecutorService single =
+ new ThreadPoolExecutor(0, 1, 1, TimeUnit.SECONDS, new SynchronousQueue<>());
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ single.submit(
+ () -> {
+ entered.countDown();
+ awaitIgnoringInterrupts(release);
+ });
+ assertTrue(entered.await(10, TimeUnit.SECONDS));
+ Driver driver = mock(Driver.class);
+ try {
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 1000, single);
+ SQLTransientConnectionException error =
+ assertThrows(
+ SQLTransientConnectionException.class,
+ () -> bounded.connect("jdbc:test", new Properties()));
+ assertInstanceOf(RejectedExecutionException.class, error.getCause());
+ verifyNoInteractions(driver);
+ } finally {
+ release.countDown();
+ single.shutdownNow();
+ assertTrue(single.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ @Test
+ void testLateCloseFailureDoesNotPinContextOrQuarantine() throws Exception {
+ Driver driver = mock(Driver.class);
+ Connection late = mock(Connection.class);
+ CountDownLatch release = new CountDownLatch(1);
+ when(driver.connect(anyString(), any()))
+ .thenAnswer(
+ invocation -> {
+ awaitIgnoringInterrupts(release);
+ return late;
+ })
+ .thenReturn(null);
+ doThrow(new SQLException("close failed")).when(late).close();
+ ClassLoader loader = workers.submit(() -> Thread.currentThread().getContextClassLoader()).get();
+ BoundedConnectionDriver bounded = new BoundedConnectionDriver(driver, 100, workers);
+ try {
+ assertThrows(SQLTimeoutException.class, () -> bounded.connect("jdbc:test", new Properties()));
+ } finally {
+ release.countDown();
+ }
+ assertSame(
+ loader,
+ workers
+ .submit(() -> Thread.currentThread().getContextClassLoader())
+ .get(10, TimeUnit.SECONDS));
+ assertNull(bounded.connect("jdbc:test", new Properties()));
+ verify(late).close();
+ }
+
+ private static void awaitIgnoringInterrupts(CountDownLatch latch) {
+ boolean interrupted = false;
+ while (true) {
+ try {
+ if (!latch.await(10, TimeUnit.SECONDS)) {
+ throw new AssertionError("Test did not release driver");
+ }
+ break;
+ } catch (InterruptedException e) {
+ interrupted = true;
+ }
+ }
+ if (interrupted) {
+ Thread.currentThread().interrupt();
+ }
+ }
+}
diff --git a/docs/how-to-upgrade.md b/docs/how-to-upgrade.md
index 268ab09599..8de22b1977 100644
--- a/docs/how-to-upgrade.md
+++ b/docs/how-to-upgrade.md
@@ -274,4 +274,22 @@ After restoring, verify that your Gravitino instance starts
successfully with the restored database before attempting the
upgrade again.
+## Column name capacity in 2.0
+
+The entity store supports top-level table column names up to 300 characters; other entity names retain
+their 128-character limit. Catalog-specific name restrictions still apply. Fresh 2.0 installs
+and the 1.3-to-2.0 upgrade scripts include this column expansion.
+
+If the database was initialized with an earlier 2.0 SNAPSHOT schema, stop Gravitino and back
+up the entity store, then apply the `table_column_version_info.column_name` expansion from
+the corresponding H2, MySQL or PostgreSQL upgrade script before starting the new binary.
+To roll back, restore the pre-upgrade database backup and matching binary; changes made
+after the backup will be lost. Renaming or dropping a long-named column does not remove
+its historical rows. Mixed-version writers are not supported.
+
+The 300-character boundary is consistent for ASCII/BMP names. Java validation counts Unicode
+code points, whereas H2 counts UTF-16 code units for `VARCHAR` capacity. Names containing
+supplementary characters can reach H2's storage limit sooner; this existing backend difference
+is not changed by the expansion.
+
<img src="https://analytics.apache.org/matomo.php?idsite=62&rec=1&bots=1&action_name=HowToUpgrade" alt="" />
diff --git a/docs/jdbc-catalog-connection-validation.md b/docs/jdbc-catalog-connection-validation.md
index c5ba0307f0..f4aa15c3f3 100644
--- a/docs/jdbc-catalog-connection-validation.md
+++ b/docs/jdbc-catalog-connection-validation.md
@@ -110,3 +110,34 @@ A timeout value you set directly on the connection or in the `jdbc-url` query st
overridden; drivers whose family is not recognized are left unbounded by Gravitino. The pooled
timeout is applied as a per-connection bound, so the pool stays lazy and no connection is opened
until the first real round trip.
+
+## Driver adapter for physical connection deadlines
+
+Connector implementations can opt into `org.apache.gravitino.utils.BoundedConnectionDriver`
+when their JDBC driver does not enforce a login timeout. Wrap the driver with a positive
+timeout in milliseconds and pass the wrapper to the connection pool as its driver. No
+existing connector is automatically switched to this adapter by this addition.
+
+Only `Driver.connect` runs on a worker. Metadata, validation and SQL remain on the caller;
+this does not introduce delayed DDL or an automatic retry. A connection returned after
+timeout/interruption is closed by the worker and never handed to the caller or pool.
+While an abandoned attempt is still connecting or closing, new attempts through that wrapper
+fail immediately. Pool waits, connection validation, SQL and total request duration retain
+their own budgets.
+
+The core-loaded adapter shares at most 64 daemon workers per server JVM, with no queue.
+Saturation fails new connects with `SQLTransientConnectionException`, including otherwise
+healthy connects. Cancellation is best effort: an uninterruptible driver or close can retain
+a worker and its driver resources until it returns or the server restarts. Completed workers
+restore their context class loader. The adapter does not bound arbitrary driver constructor
+work or clean up driver-owned global threads.
+
+Each attempt and its late connection cleanup use the submitting caller's access-control
+context and JAAS subject. Shared workers are created without inheriting the first caller's
+subject, so reusing a worker does not reuse that caller's JAAS subject.
+
+This guarantee covers access-control contexts and JAAS subjects, not arbitrary `ThreadLocal`
+or `InheritableThreadLocal` state. Drivers using the shared workers must clean up their own
+thread-local state and must not depend on inherited thread locals for caller authentication.
+Drivers that cannot meet these requirements must not opt into this adapter. Isolating workers
+by catalog alone would not isolate different users of the same catalog.
diff --git a/docs/manage-catalogs-and-schemas.md b/docs/manage-catalogs-and-schemas.md
index 27d0f43786..94825c6e33 100644
--- a/docs/manage-catalogs-and-schemas.md
+++ b/docs/manage-catalogs-and-schemas.md
@@ -292,6 +292,25 @@ schema = catalog.as_schemas().create_schema(
### Load a Schema
+If schema creation reports that the source object was created but Gravitino registration failed,
+resolve the entity-store error and verify the source object's identity. Use `loadSchema` (or the
+load-schema REST API below) to import the existing object. Repeating `createSchema` returns an
+already-exists error; creation is not automatically replayed. Secrets referenced by the created
+object are retained. Import reads the properties available from the source; if that source omits
+secret references, reconcile those references separately before deleting any retained secrets.
+
+Creating an external schema with an existing Gravitino registration is rejected before source
+creation. External schema creation now checks the entity store before calling the source; a failed
+registration lookup stops creation without issuing source DDL. Managed schema creation does not
+perform this additional lookup.
+A different source identifier does not prove that the old object was deleted: it may have been
+renamed. For an external rename that preserves the Gravitino identifier, load the new name first
+to move the registration before creating the old name again. If the old source identity was
+actually deleted, verify that fact before explicitly removing its stale registration. Conflicting
+registrations are never automatically cascade-deleted by an overwrite; children and governance
+metadata remain intact. A concurrent registration after the preflight can still cause a partial
+create failure, since source creation and the entity-store write are not one transaction.
+
<Tabs groupId='language' queryString>
<TabItem value="shell" label="REST">
diff --git a/docs/manage-relational-metadata-using-gravitino.md b/docs/manage-relational-metadata-using-gravitino.md
index 92c78c355a..0876445b1a 100644
--- a/docs/manage-relational-metadata-using-gravitino.md
+++ b/docs/manage-relational-metadata-using-gravitino.md
@@ -116,6 +116,17 @@ order, and indexes](./table-partitioning-distribution-sort-order-indexes.md).
### Load a Table
+If table creation reports that the source table was created but Gravitino registration failed,
+resolve the entity-store error and verify the source table's identity, then use `loadTable` (or
+the load-table REST API below) to import it. Repeating `createTable` returns an already-exists
+error; Gravitino does not automatically replay the DDL. Resolve any conflicting registration
+before importing the table.
+
+A cold table load reports `NoSuchSchemaException` when its containing schema is missing. A
+missing table in an existing schema reports `NoSuchTableException`. The Java `tableExists` and
+Python `table_exists` helpers return false for either missing-object signal and propagate other
+failures.
+
<Tabs groupId='language' queryString>
<TabItem value="shell" label="REST">
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java
index d72cc3f880..a512eaf444 100644
--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java
@@ -63,6 +63,8 @@ import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
public class TestIcebergNamespaceOperationExecutor {
@@ -226,11 +228,36 @@ public class TestIcebergNamespaceOperationExecutor {
verifyNoInteractions(mockCatalogWrapper);
}
+ @ParameterizedTest
+ @ValueSource(
+ ints = {EntityFieldLimits.MAX_NAME_LENGTH + 1, EntityFieldLimits.MAX_COLUMN_NAME_LENGTH})
+ void testExpandedColumnNamesReachRegister(int length) {
+ Namespace namespace = Namespace.of("test_namespace");
+ String metadataLocation = "file:/tmp/test.metadata.json";
+ RegisterTableRequest request = mock(RegisterTableRequest.class);
+ when(request.name()).thenReturn("test_table");
+ when(request.metadataLocation()).thenReturn(metadataLocation);
+ Schema schema = new Schema(NestedField.required(1, "a".repeat(length), StringType.get()));
+ TableMetadata metadata =
+ TableMetadata.newTableMetadata(
+ schema, PartitionSpec.unpartitioned(), "file:/tmp/table", Collections.emptyMap());
+ when(mockCatalogWrapper.loadTableMetadataFromLocation(metadataLocation)).thenReturn(metadata);
+
+ executor.registerTable(mockContext, namespace, request);
+
+ verify(mockCatalogWrapper).loadTableMetadataFromLocation(metadataLocation);
+ verify(mockCatalogWrapper).registerTable(namespace, request, false);
+ }
+
@Test
public void testRejectsOversizedColumnNameBeforeRegister() {
- String oversizedName = "a".repeat(EntityFieldLimits.MAX_NAME_LENGTH + 1);
+ String oversizedName = "a".repeat(EntityFieldLimits.MAX_COLUMN_NAME_LENGTH + 1);
Schema schema = new Schema(NestedField.required(1, oversizedName, StringType.get()));
- assertRegisterRejectsSchema(schema, "The name of the column must not exceed 128 characters");
+ assertRegisterRejectsSchema(
+ schema,
+ "The name of the column must not exceed "
+ + EntityFieldLimits.MAX_COLUMN_NAME_LENGTH
+ + " characters");
}
@Test
@@ -270,15 +297,17 @@ public class TestIcebergNamespaceOperationExecutor {
String originalMetadataLocation =
writeMetadata(
tempDir.resolve("v1.metadata.json"),
- new Schema(NestedField.required(1, "id", StringType.get())));
+ new Schema(
+ NestedField.required(
+ 1, "a".repeat(EntityFieldLimits.MAX_COLUMN_NAME_LENGTH), StringType.get())));
RegisterTableRequest originalRequest =
ImmutableRegisterTableRequest.builder()
.name("test_table")
.metadataLocation(originalMetadataLocation)
.build();
- catalogWrapper.registerTable(namespace, originalRequest, false);
+ executor.registerTable(mockContext, namespace, originalRequest);
- String oversizedName = "a".repeat(EntityFieldLimits.MAX_NAME_LENGTH + 1);
+ String oversizedName = "a".repeat(EntityFieldLimits.MAX_COLUMN_NAME_LENGTH + 1);
String invalidMetadataLocation =
writeMetadata(
tempDir.resolve("v2.metadata.json"),
diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergTableOperationExecutor.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergTableOperationExecutor.java
index cbfd05dde4..c287f1f760 100644
--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergTableOperationExecutor.java
+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergTableOperationExecutor.java
@@ -31,6 +31,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.apache.gravitino.EntityFieldLimits;
+import org.apache.gravitino.auth.AuthConstants;
import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
import org.apache.gravitino.iceberg.service.CatalogWrapperForREST;
import org.apache.gravitino.iceberg.service.IcebergCatalogWrapperManager;
@@ -50,6 +51,8 @@ import org.apache.iceberg.types.Types.StringType;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
public class TestIcebergTableOperationExecutor {
@@ -233,9 +236,31 @@ public class TestIcebergTableOperationExecutor {
verifyNoInteractions(mockCatalogWrapper);
}
+ @ParameterizedTest
+ @ValueSource(
+ ints = {EntityFieldLimits.MAX_NAME_LENGTH + 1, EntityFieldLimits.MAX_COLUMN_NAME_LENGTH})
+ void testExpandedColumnNamesReachCreateAndUpdate(int length) {
+ Schema schema = new Schema(NestedField.required(1, "a".repeat(length), StringType.get()));
+ Namespace namespace = Namespace.of("test_namespace");
+ CreateTableRequest createRequest =
+ CreateTableRequest.builder().withName("test_table").withSchema(schema).build();
+ when(mockContext.userName()).thenReturn(AuthConstants.ANONYMOUS_USER);
+
+ executor.createTable(mockContext, namespace, createRequest);
+
+ verify(mockCatalogWrapper).createTable(namespace, createRequest, false);
+
+ TableIdentifier table = TableIdentifier.of(namespace, "test_table");
+ UpdateTableRequest updateRequest = updateRequest(schema);
+
+ executor.updateTable(mockContext, table, updateRequest);
+
+ verify(mockCatalogWrapper).updateTable(table, updateRequest);
+ }
+
@Test
public void testRejectsOversizedColumnFieldsBeforeCreate() {
- String oversizedName = "a".repeat(EntityFieldLimits.MAX_NAME_LENGTH + 1);
+ String oversizedName = "a".repeat(EntityFieldLimits.MAX_COLUMN_NAME_LENGTH + 1);
Schema oversizedNameSchema =
new Schema(NestedField.required(1, oversizedName, StringType.get()));
CreateTableRequest oversizedNameRequest =
@@ -248,7 +273,10 @@ public class TestIcebergTableOperationExecutor {
executor.createTable(
mockContext, Namespace.of("test_namespace"), oversizedNameRequest));
Assertions.assertEquals(
- "The name of the column must not exceed 128 characters", nameException.getMessage());
+ "The name of the column must not exceed "
+ + EntityFieldLimits.MAX_COLUMN_NAME_LENGTH
+ + " characters",
+ nameException.getMessage());
String oversizedComment = "a".repeat(EntityFieldLimits.MAX_COLUMN_COMMENT_LENGTH + 1);
Schema oversizedCommentSchema =
@@ -302,7 +330,7 @@ public class TestIcebergTableOperationExecutor {
@Test
public void testRejectsOversizedColumnFieldsBeforeUpdate() {
- String oversizedName = "a".repeat(EntityFieldLimits.MAX_NAME_LENGTH + 1);
+ String oversizedName = "a".repeat(EntityFieldLimits.MAX_COLUMN_NAME_LENGTH + 1);
UpdateTableRequest oversizedNameRequest =
updateRequest(new Schema(NestedField.required(1, oversizedName, StringType.get())));
@@ -315,7 +343,10 @@ public class TestIcebergTableOperationExecutor {
TableIdentifier.of("test_namespace", "test_table"),
oversizedNameRequest));
Assertions.assertEquals(
- "The name of the column must not exceed 128 characters", nameException.getMessage());
+ "The name of the column must not exceed "
+ + EntityFieldLimits.MAX_COLUMN_NAME_LENGTH
+ + " characters",
+ nameException.getMessage());
String oversizedComment = "a".repeat(EntityFieldLimits.MAX_COLUMN_COMMENT_LENGTH + 1);
UpdateTableRequest oversizedCommentRequest =
diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sql
index 82496f0cf8..a1fc82b59d 100644
--- a/scripts/h2/schema-2.0.0-h2.sql
+++ b/scripts/h2/schema-2.0.0-h2.sql
@@ -92,7 +92,7 @@ CREATE TABLE IF NOT EXISTS `table_column_version_info` (
`table_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'table id',
`table_version` INT UNSIGNED NOT NULL COMMENT 'table version',
`column_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'column id',
- `column_name` VARCHAR(128) NOT NULL COMMENT 'column name',
+ `column_name` VARCHAR(300) NOT NULL COMMENT 'column name',
`column_position` INT UNSIGNED NOT NULL COMMENT 'column position, starting from 0',
`column_type` CLOB NOT NULL COMMENT 'column type',
`column_comment` VARCHAR(4096) DEFAULT '' COMMENT 'column comment',
diff --git a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
index 3bb896304e..1151ba1755 100644
--- a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
+++ b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
@@ -26,6 +26,9 @@
ALTER TABLE `table_column_version_info`
ALTER COLUMN `column_comment` VARCHAR(4096) DEFAULT '';
+-- Support external column names up to 300 characters (including BigQuery).
+ALTER TABLE `table_column_version_info` ALTER COLUMN `column_name` VARCHAR(300) NOT NULL;
+
ALTER TABLE `model_meta` ADD COLUMN IF NOT EXISTS `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'model current version' AFTER `model_latest_version`;
ALTER TABLE `model_meta` ADD COLUMN IF NOT EXISTS `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'model last allocated version' AFTER `current_version`;
diff --git a/scripts/mysql/schema-2.0.0-mysql.sql b/scripts/mysql/schema-2.0.0-mysql.sql
index 630754a99a..93b12fd127 100644
--- a/scripts/mysql/schema-2.0.0-mysql.sql
+++ b/scripts/mysql/schema-2.0.0-mysql.sql
@@ -87,7 +87,7 @@ CREATE TABLE IF NOT EXISTS `table_column_version_info` (
`table_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'table id',
`table_version` INT UNSIGNED NOT NULL COMMENT 'table version',
`column_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'column id',
- `column_name` VARCHAR(128) NOT NULL COMMENT 'column name',
+ `column_name` VARCHAR(300) NOT NULL COMMENT 'column name',
`column_position` INT UNSIGNED NOT NULL COMMENT 'column position, starting from 0',
`column_type` TEXT NOT NULL COMMENT 'column type',
`column_comment` VARCHAR(4096) DEFAULT '' COMMENT 'column comment',
diff --git a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
index 870aea6395..90cab77bea 100644
--- a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
+++ b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
@@ -27,6 +27,9 @@
ALTER TABLE `table_column_version_info`
MODIFY COLUMN `column_comment` VARCHAR(4096) DEFAULT '' COMMENT 'column comment';
+-- Support external column names up to 300 characters (including BigQuery).
+ALTER TABLE `table_column_version_info` MODIFY COLUMN `column_name` VARCHAR(300) NOT NULL COMMENT 'column name';
+
SET @ddl = IF(EXISTS(SELECT 1 FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = 'tag_meta' AND column_name = 'allowed_values'),
'SELECT 1',
diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql b/scripts/postgresql/schema-2.0.0-postgresql.sql
index 6047a316a8..f9e6bfe7dc 100644
--- a/scripts/postgresql/schema-2.0.0-postgresql.sql
+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql
@@ -147,7 +147,7 @@ CREATE TABLE IF NOT EXISTS table_column_version_info (
table_id BIGINT NOT NULL,
table_version INT NOT NULL,
column_id BIGINT NOT NULL,
- column_name VARCHAR(128) NOT NULL,
+ column_name VARCHAR(300) NOT NULL,
column_position INT NOT NULL,
column_type TEXT NOT NULL,
column_comment VARCHAR(4096) DEFAULT '',
diff --git a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
index 828f7454ea..28906b2de3 100644
--- a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
+++ b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
@@ -27,6 +27,9 @@
ALTER TABLE table_column_version_info
ALTER COLUMN column_comment TYPE VARCHAR(4096);
+-- Support external column names up to 300 characters (including BigQuery).
+ALTER TABLE table_column_version_info ALTER COLUMN column_name TYPE VARCHAR(300);
+
ALTER TABLE model_meta ADD COLUMN IF NOT EXISTS current_version INT NOT NULL DEFAULT 1;
ALTER TABLE model_meta ADD COLUMN IF NOT EXISTS last_version INT NOT NULL DEFAULT 1;
COMMENT ON COLUMN model_meta.current_version IS 'model current version';
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestTableOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestTableOperations.java
index 3cd369ab79..d974cdc430 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestTableOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestTableOperations.java
@@ -656,6 +656,18 @@ public class TestTableOperations extends BaseOperationsTest {
Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResp.getCode());
Assertions.assertEquals(NoSuchTableException.class.getSimpleName(), errorResp.getType());
+ doThrow(new NoSuchSchemaException("schema missing")).when(dispatcher).loadTable(any());
+ Response missingSchema =
+ target(tablePath(metalake, catalog, schema) + "table1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), missingSchema.getStatus());
+ ErrorResponse schemaError = missingSchema.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, schemaError.getCode());
+ Assertions.assertEquals(NoSuchSchemaException.class.getSimpleName(), schemaError.getType());
+ Assertions.assertTrue(schemaError.getMessage().contains("schema missing"));
+
// Test throw RuntimeException
doThrow(new RuntimeException("mock error")).when(dispatcher).loadTable(any());