Skip to content

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

[#13770] fix(core): Prevent external imports from overwriting identities (#13771)

roryqi3627297fa300
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogCapability.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogCapability.java
index 1201f3e703..6e9c88eb02 100644
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogCapability.java
+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveCatalogCapability.java
@@ -62,6 +62,7 @@ public class HiveCatalogCapability implements Capability {
switch (scope) {
case SCHEMA:
case TABLE:
+ case VIEW:
case COLUMN:
// Hive is case insensitive, see
// https://cwiki.apache.org/confluence/display/Hive/User+FAQ#UserFAQ-AreHiveSQLidentifiers(e.g.tablenames,columnnames,etc)casesensitive?
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogCapability.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogCapability.java
index 919d411d0f..e8b873798d 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogCapability.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogCapability.java
@@ -22,12 +22,23 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.connector.capability.CapabilityResult;
import org.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion;
import org.junit.jupiter.api.Test;
public class TestHiveCatalogCapability {
+ @Test
+ public void testHiveEntityNamesAreCaseInsensitive() {
+ HiveCatalogCapability capability = new HiveCatalogCapability(() -> HiveVersion.HIVE2);
+
+ assertFalse(capability.caseSensitiveOnName(Capability.Scope.SCHEMA).supported());
+ assertFalse(capability.caseSensitiveOnName(Capability.Scope.TABLE).supported());
+ assertFalse(capability.caseSensitiveOnName(Capability.Scope.VIEW).supported());
+ assertFalse(capability.caseSensitiveOnName(Capability.Scope.COLUMN).supported());
+ }
+
@Test
public void testColumnConstraintsOnHive2() {
HiveCatalogCapability capability = new HiveCatalogCapability(() -> HiveVersion.HIVE2);
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
index 3c5a5a225c..73bcad1c70 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHive2IT.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.catalog.hive.integration.test;
import static org.apache.gravitino.catalog.hive.HiveConstants.COMMENT;
+import static org.apache.gravitino.catalog.hive.HiveConstants.DEFAULT_CATALOG;
import static org.apache.gravitino.catalog.hive.HiveConstants.EXTERNAL;
import static org.apache.gravitino.catalog.hive.HiveConstants.FORMAT;
import static org.apache.gravitino.catalog.hive.HiveConstants.INPUT_FORMAT;
@@ -58,6 +59,7 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.Schema;
import org.apache.gravitino.SchemaChange;
+import org.apache.gravitino.StringIdentifier;
import org.apache.gravitino.SupportsSchemas;
import org.apache.gravitino.auth.AuthConstants;
import org.apache.gravitino.catalog.hive.HiveCatalogOperations;
@@ -1542,7 +1544,7 @@ public class CatalogHive2IT extends BaseIT {
}
@Test
- public void testOutOfBandRenameKeepsColumnTags() throws InterruptedException {
+ public void testOutOfBandRenameRequiresIdentifierCleanup() throws InterruptedException {
// Hive stores names in lower case, and tag operations resolve a column by its stored name.
String schema = schemaName.toLowerCase(Locale.ROOT);
NameIdentifier ident =
@@ -1557,7 +1559,7 @@ public class CatalogHive2IT extends BaseIT {
loadColumn(ident, HIVE_COL_NAME1).supportsTags().associateTags(new String[] {tagName}, null);
// Rename the table directly in the Hive Metastore. It keeps its Gravitino id in its table
- // parameters, so loading it under the new name imports it again over the same id.
+ // parameters, but Gravitino must not automatically move the stored identity to the new path.
String newName = GravitinoITUtils.genRandomName("hive_oob_renamed_table");
HiveTable hiveTable = loadHiveTable(schema, ident.name());
HiveTable.Builder renamed =
@@ -1580,20 +1582,91 @@ public class CatalogHive2IT extends BaseIT {
return null;
});
- // The column keeps its id, so the tag follows the table to its new name.
+ // Loading the external name now requires manual identifier cleanup. The rejected import must
+ // leave the tag relation attached to the original Gravitino identity.
NameIdentifier newIdent = NameIdentifier.of(schema, newName);
- Column column = loadColumn(newIdent, HIVE_COL_NAME1);
- Assertions.assertArrayEquals(new String[] {tagName}, column.supportsTags().listTags());
+ UnsupportedOperationException exception =
+ assertThrows(
+ UnsupportedOperationException.class, () -> loadColumn(newIdent, HIVE_COL_NAME1));
+ Assertions.assertTrue(
+ exception
+ .getMessage()
+ .contains(
+ "does not automatically reconcile conflicting external table registrations"),
+ exception.getMessage());
MetadataObject[] objects = metalake.getTag(tagName).associatedObjects().objects();
Assertions.assertEquals(1, objects.length);
Assertions.assertEquals(
- String.join(".", catalogName, schema, newName, HIVE_COL_NAME1).toLowerCase(Locale.ROOT),
+ String.join(".", catalogName, schema, ident.name(), HIVE_COL_NAME1)
+ .toLowerCase(Locale.ROOT),
objects[0].fullName().toLowerCase(Locale.ROOT));
} finally {
metalake.deleteTag(tagName);
}
}
+ @Test
+ void testCatalogReregistrationKeepsExternalIdentifiers() throws InterruptedException {
+ String reregisteredCatalogName = GravitinoITUtils.genRandomName("hive_reregistered_catalog");
+ String externalSchemaName = GravitinoITUtils.genRandomName("hive_reregistered_schema");
+ String externalTableName = GravitinoITUtils.genRandomName("hive_reregistered_table");
+ Map<String, String> catalogProperties =
+ ImmutableMap.of(METASTORE_URIS, hiveMetastoreUris, DEFAULT_CATALOG, hmsCatalog);
+
+ Catalog originalCatalog =
+ metalake.createCatalog(
+ reregisteredCatalogName,
+ Catalog.Type.RELATIONAL,
+ provider,
+ "comment",
+ catalogProperties);
+ originalCatalog.asSchemas().createSchema(externalSchemaName, "comment", Collections.emptyMap());
+ NameIdentifier externalTableIdentifier =
+ NameIdentifier.of(externalSchemaName, externalTableName);
+ originalCatalog
+ .asTableCatalog()
+ .createTable(
+ externalTableIdentifier,
+ createColumns(),
+ TABLE_COMMENT,
+ createProperties(),
+ Transforms.EMPTY_TRANSFORM);
+
+ Assertions.assertTrue(metalake.dropCatalog(reregisteredCatalogName, true));
+ Catalog reregisteredCatalog =
+ metalake.createCatalog(
+ reregisteredCatalogName,
+ Catalog.Type.RELATIONAL,
+ provider,
+ "comment",
+ catalogProperties);
+
+ String originalSchemaId =
+ loadHiveSchema(externalSchemaName).properties().get(StringIdentifier.ID_KEY);
+ String originalTableId =
+ loadHiveTable(externalSchemaName, externalTableName)
+ .properties()
+ .get(StringIdentifier.ID_KEY);
+ Assertions.assertNotNull(originalSchemaId);
+ Assertions.assertNotNull(originalTableId);
+ Assertions.assertEquals(
+ externalSchemaName.toLowerCase(Locale.ROOT),
+ reregisteredCatalog.asSchemas().loadSchema(externalSchemaName).name());
+ Assertions.assertEquals(
+ externalTableName.toLowerCase(Locale.ROOT),
+ reregisteredCatalog.asTableCatalog().loadTable(externalTableIdentifier).name());
+ Assertions.assertEquals(
+ originalSchemaId,
+ loadHiveSchema(externalSchemaName).properties().get(StringIdentifier.ID_KEY));
+ Assertions.assertEquals(
+ originalTableId,
+ loadHiveTable(externalSchemaName, externalTableName)
+ .properties()
+ .get(StringIdentifier.ID_KEY));
+ Assertions.assertTrue(reregisteredCatalog.asSchemas().dropSchema(externalSchemaName, true));
+ Assertions.assertTrue(metalake.dropCatalog(reregisteredCatalogName, true));
+ }
+
@Test
public void testCrossSchemaTableRename() throws TException, InterruptedException {
// Create a second schema to serve as the rename destination.
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveViewIT.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveViewIT.java
index 630c2e472b..53e382a924 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveViewIT.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/integration/test/CatalogHiveViewIT.java
@@ -154,7 +154,8 @@ public class CatalogHiveViewIT extends BaseIT {
Assertions.assertEquals(
HIVE_DIALECT, ((SQLRepresentation) created.representations()[0]).dialect());
- View loaded = viewCatalog.loadView(NameIdentifier.of(schemaName, viewName));
+ View loaded =
+ viewCatalog.loadView(NameIdentifier.of(schemaName, viewName.toUpperCase(Locale.ROOT)));
Assertions.assertEquals(viewName, loaded.name());
Assertions.assertEquals(VIEW_COMMENT, loaded.comment());
Assertions.assertEquals(1, loaded.representations().length);
diff --git a/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/integration/test/CatalogKafkaIT.java b/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/integration/test/CatalogKafkaIT.java
index 12c19eab1d..76a870478f 100644
--- a/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/integration/test/CatalogKafkaIT.java
+++ b/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/integration/test/CatalogKafkaIT.java
@@ -192,6 +192,74 @@ public class CatalogKafkaIT extends BaseIT {
Assertions.assertFalse(adminClient.listTopics().names().get().isEmpty());
}
+ @Test
+ public void testCatalogReregistrationLoadsExistingTopic()
+ throws ExecutionException, InterruptedException {
+ String catalogName = GravitinoITUtils.genRandomName("test_catalog_reregistration");
+ String topicName = GravitinoITUtils.genRandomName("test_topic_reregistration");
+ NameIdentifier topicIdent = NameIdentifier.of(DEFAULT_SCHEMA_NAME, topicName);
+ Map<String, String> properties = ImmutableMap.of(BOOTSTRAP_SERVERS, kafkaBootstrapServers);
+
+ adminClient.createTopics(ImmutableList.of(new NewTopic(topicName, 1, (short) 1))).all().get();
+
+ Catalog originalCatalog = createCatalog(catalogName, "original catalog", properties);
+ Assertions.assertEquals(
+ topicName, originalCatalog.asTopicCatalog().loadTopic(topicIdent).name());
+
+ Assertions.assertTrue(metalake.dropCatalog(catalogName, true));
+ Assertions.assertTrue(topicExistsInKafka(topicName));
+
+ Catalog reregisteredCatalog = createCatalog(catalogName, "re-registered catalog", properties);
+ Topic restoredTopic =
+ Assertions.assertDoesNotThrow(
+ () -> reregisteredCatalog.asTopicCatalog().loadTopic(topicIdent));
+ Assertions.assertEquals(topicName, restoredTopic.name());
+ checkTopicReadWrite(topicName);
+
+ Assertions.assertTrue(reregisteredCatalog.asTopicCatalog().dropTopic(topicIdent));
+ awaitTopicDeletedInKafka(topicName);
+ Assertions.assertTrue(metalake.dropCatalog(catalogName, true));
+ }
+
+ @Test
+ public void testActiveTopicRegistrationCannotBeRebound()
+ throws ExecutionException, InterruptedException {
+ String originalCatalogName =
+ GravitinoITUtils.genRandomName("test_active_topic_original_catalog");
+ String conflictingCatalogName =
+ GravitinoITUtils.genRandomName("test_active_topic_conflicting_catalog");
+ String topicName = GravitinoITUtils.genRandomName("test_active_topic_registration");
+ NameIdentifier topicIdent = NameIdentifier.of(DEFAULT_SCHEMA_NAME, topicName);
+ Map<String, String> properties = ImmutableMap.of(BOOTSTRAP_SERVERS, kafkaBootstrapServers);
+
+ adminClient.createTopics(ImmutableList.of(new NewTopic(topicName, 1, (short) 1))).all().get();
+
+ Catalog originalCatalog = createCatalog(originalCatalogName, "original catalog", properties);
+ Assertions.assertEquals(
+ topicName, originalCatalog.asTopicCatalog().loadTopic(topicIdent).name());
+
+ Catalog conflictingCatalog =
+ createCatalog(conflictingCatalogName, "conflicting catalog", properties);
+ UnsupportedOperationException exception =
+ Assertions.assertThrows(
+ UnsupportedOperationException.class,
+ () -> conflictingCatalog.asTopicCatalog().loadTopic(topicIdent));
+ Assertions.assertTrue(
+ exception
+ .getMessage()
+ .contains("metadata-only unregister of an individual external topic"));
+ Assertions.assertTrue(exception.getMessage().contains("catalog-specific recovery guidance"));
+
+ // The rejected import must not move the active entity away from its original path.
+ Assertions.assertEquals(
+ topicName, originalCatalog.asTopicCatalog().loadTopic(topicIdent).name());
+
+ Assertions.assertTrue(metalake.dropCatalog(conflictingCatalogName, true));
+ Assertions.assertTrue(originalCatalog.asTopicCatalog().dropTopic(topicIdent));
+ awaitTopicDeletedInKafka(topicName);
+ Assertions.assertTrue(metalake.dropCatalog(originalCatalogName, true));
+ }
+
@Test
public void testCatalogException() {
String catalogName1 = GravitinoITUtils.genRandomName("test_catalog");
diff --git a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalog.java b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalog.java
index 8dcf787ae2..5b60243af6 100644
--- a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalog.java
+++ b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalog.java
@@ -22,6 +22,7 @@ import java.util.Map;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.CatalogOperations;
import org.apache.gravitino.connector.PropertiesMetadata;
+import org.apache.gravitino.connector.capability.Capability;
/** Implementation of an Apache Hudi catalog in Apache Gravitino. */
public class HudiCatalog extends BaseCatalog<HudiCatalog> {
@@ -59,6 +60,11 @@ public class HudiCatalog extends BaseCatalog<HudiCatalog> {
return new HudiCatalogOperations();
}
+ @Override
+ public Capability newCapability() {
+ return new HudiCatalogCapability();
+ }
+
@Override
public PropertiesMetadata catalogPropertiesMetadata() throws UnsupportedOperationException {
return CATALOG_PROPERTIES_METADATA;
diff --git a/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalogCapability.java b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalogCapability.java
new file mode 100644
index 0000000000..90261f3bc1
--- /dev/null
+++ b/catalogs/catalog-lakehouse-hudi/src/main/java/org/apache/gravitino/catalog/lakehouse/hudi/HudiCatalogCapability.java
@@ -0,0 +1,38 @@
+/*
+ * 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.catalog.lakehouse.hudi;
+
+import org.apache.gravitino.connector.capability.Capability;
+import org.apache.gravitino.connector.capability.CapabilityResult;
+
+/** Describes the capabilities of the Hudi catalog backed by Hive Metastore. */
+public class HudiCatalogCapability implements Capability {
+
+ /** Creates a Hudi catalog capability for the Hive Metastore backend. */
+ public HudiCatalogCapability() {}
+
+ @Override
+ public CapabilityResult caseSensitiveOnName(Scope scope) {
+ if (scope == Scope.SCHEMA || scope == Scope.TABLE) {
+ return CapabilityResult.unsupported(
+ "The Hudi Hive backend is case insensitive for schemas and tables.");
+ }
+ return Capability.super.caseSensitiveOnName(scope);
+ }
+}
diff --git a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/TestHudiCatalogCapability.java b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/TestHudiCatalogCapability.java
new file mode 100644
index 0000000000..839bf9b48d
--- /dev/null
+++ b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/TestHudiCatalogCapability.java
@@ -0,0 +1,42 @@
+/*
+ * 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.catalog.lakehouse.hudi;
+
+import org.apache.gravitino.connector.capability.Capability;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Tests for {@link HudiCatalogCapability}. */
+public class TestHudiCatalogCapability {
+
+ @Test
+ public void testHiveBackendFoldsSchemaAndTableNamesOnly() {
+ HudiCatalogCapability capability = new HudiCatalogCapability();
+
+ Assertions.assertFalse(capability.caseSensitiveOnName(Capability.Scope.SCHEMA).supported());
+ Assertions.assertFalse(capability.caseSensitiveOnName(Capability.Scope.TABLE).supported());
+ Assertions.assertTrue(capability.caseSensitiveOnName(Capability.Scope.VIEW).supported());
+ Assertions.assertTrue(capability.caseSensitiveOnName(Capability.Scope.COLUMN).supported());
+
+ Assertions.assertEquals("schema", capability.normalizeName(Capability.Scope.SCHEMA, "Schema"));
+ Assertions.assertEquals("table", capability.normalizeName(Capability.Scope.TABLE, "Table"));
+ Assertions.assertEquals("View", capability.normalizeName(Capability.Scope.VIEW, "View"));
+ Assertions.assertEquals("Column", capability.normalizeName(Capability.Scope.COLUMN, "Column"));
+ }
+}
diff --git a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogHMSIT.java b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogHMSIT.java
index e2cf741fb1..3d0fc29698 100644
--- a/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogHMSIT.java
+++ b/catalogs/catalog-lakehouse-hudi/src/test/java/org/apache/gravitino/catalog/lakehouse/hudi/integration/test/HudiCatalogHMSIT.java
@@ -27,6 +27,7 @@ import com.google.common.collect.ImmutableMap;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.gravitino.Catalog;
@@ -209,7 +210,7 @@ public class HudiCatalogHMSIT extends BaseIT {
Assertions.assertTrue(Arrays.asList(schemas).contains(DB_NAME));
// test load
- Schema schema = schemaOps.loadSchema(DB_NAME);
+ Schema schema = schemaOps.loadSchema(DB_NAME.toUpperCase(Locale.ROOT));
Assertions.assertEquals(DB_NAME, schema.name());
Assertions.assertEquals("", schema.comment());
Assertions.assertTrue(schema.properties().get(LOCATION).endsWith(DB_NAME));
@@ -260,7 +261,10 @@ public class HudiCatalogHMSIT extends BaseIT {
Assertions.assertTrue(tableNames.contains(MOR_TABLE + "_ro"));
// test load
- Table table = tableOps.loadTable(NameIdentifier.of(DB_NAME, COW_TABLE));
+ Table table =
+ tableOps.loadTable(
+ NameIdentifier.of(
+ DB_NAME.toUpperCase(Locale.ROOT), COW_TABLE.toUpperCase(Locale.ROOT)));
Assertions.assertEquals(COW_TABLE, table.name());
assertTable(table);
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalog.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalog.java
index b30235201c..7a072f0438 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalog.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalog.java
@@ -86,7 +86,11 @@ public class IcebergCatalog extends BaseCatalog<IcebergCatalog> {
@Override
public Capability newCapability() {
- return new IcebergCatalogCapability(HierarchicalSchemaUtil.schemaSeparator());
+ Map<String, String> properties = entity().getProperties();
+ String backend = properties == null ? null : properties.get(IcebergConstants.CATALOG_BACKEND);
+ return new IcebergCatalogCapability(
+ HierarchicalSchemaUtil.schemaSeparator(),
+ IcebergCatalogBackend.HIVE.name().equalsIgnoreCase(backend));
}
@Override
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogCapability.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogCapability.java
index 15f82042c0..b02a8a7919 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogCapability.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogCapability.java
@@ -25,6 +25,7 @@ import org.apache.gravitino.utils.HierarchicalSchemaUtil;
public class IcebergCatalogCapability implements Capability {
private final String schemaSeparator;
+ private final boolean hiveBackend;
/**
* Creates a capability with the given external schema separator.
@@ -32,7 +33,18 @@ public class IcebergCatalogCapability implements Capability {
* @param schemaSeparator the external separator used in logical schema names (e.g. {@code ":"})
*/
public IcebergCatalogCapability(String schemaSeparator) {
+ this(schemaSeparator, false);
+ }
+
+ /**
+ * Creates a capability with the given external schema separator and backend behavior.
+ *
+ * @param schemaSeparator the external separator used in logical schema names (e.g. {@code ":"})
+ * @param hiveBackend whether the Iceberg catalog uses Hive as its backend
+ */
+ public IcebergCatalogCapability(String schemaSeparator, boolean hiveBackend) {
this.schemaSeparator = schemaSeparator;
+ this.hiveBackend = hiveBackend;
}
@Override
@@ -48,6 +60,15 @@ public class IcebergCatalogCapability implements Capability {
return CapabilityResult.SUPPORTED;
}
+ @Override
+ public CapabilityResult caseSensitiveOnName(Scope scope) {
+ if (hiveBackend && (scope == Scope.SCHEMA || scope == Scope.TABLE || scope == Scope.VIEW)) {
+ return CapabilityResult.unsupported(
+ "The Iceberg Hive backend is case insensitive for schemas, tables, and views.");
+ }
+ return Capability.super.caseSensitiveOnName(scope);
+ }
+
/**
* Validates the schema name specification for Iceberg.
*
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalog.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalog.java
index a03c590d0b..63ed2bade8 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalog.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalog.java
@@ -32,6 +32,7 @@ import org.apache.gravitino.connector.CatalogOperations;
import org.apache.gravitino.connector.HasPropertyMetadata;
import org.apache.gravitino.connector.HiddenPropertyMaskUtils;
import org.apache.gravitino.connector.PropertiesMetadata;
+import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.credential.AzureAccountKeyCredential;
import org.apache.gravitino.credential.CredentialConstants;
import org.apache.gravitino.credential.JdbcCredential;
@@ -130,6 +131,8 @@ public class TestIcebergCatalog {
Map<String, String> conf = Maps.newHashMap();
IcebergCatalog icebergCatalog =
new IcebergCatalog().withCatalogConf(conf).withCatalogEntity(entity);
+ Assertions.assertTrue(
+ icebergCatalog.newCapability().caseSensitiveOnName(Capability.Scope.SCHEMA).supported());
CatalogOperations catalogOperations = icebergCatalog.ops();
Assertions.assertTrue(catalogOperations instanceof IcebergCatalogOperations);
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogCapability.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogCapability.java
index 20810b2a04..274321d8b5 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogCapability.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergCatalogCapability.java
@@ -98,6 +98,35 @@ public class TestIcebergCatalogCapability {
Assertions.assertTrue(capability.supportsHierarchicalSchema().supported());
}
+ @Test
+ public void testHiveBackendFoldsSchemaTableAndViewNamesOnly() {
+ IcebergCatalogCapability capability = new IcebergCatalogCapability(":", true);
+
+ Assertions.assertFalse(capability.caseSensitiveOnName(Capability.Scope.SCHEMA).supported());
+ Assertions.assertFalse(capability.caseSensitiveOnName(Capability.Scope.TABLE).supported());
+ Assertions.assertFalse(capability.caseSensitiveOnName(Capability.Scope.VIEW).supported());
+ Assertions.assertEquals("schema", capability.normalizeName(Capability.Scope.SCHEMA, "Schema"));
+ Assertions.assertEquals("table", capability.normalizeName(Capability.Scope.TABLE, "Table"));
+ Assertions.assertEquals("view", capability.normalizeName(Capability.Scope.VIEW, "View"));
+
+ Assertions.assertTrue(capability.caseSensitiveOnName(Capability.Scope.COLUMN).supported());
+ Assertions.assertEquals("Column", capability.normalizeName(Capability.Scope.COLUMN, "Column"));
+ }
+
+ @Test
+ public void testNonHiveBackendKeepsEntityNameCase() {
+ IcebergCatalogCapability capability = new IcebergCatalogCapability(":", false);
+
+ Assertions.assertTrue(capability.caseSensitiveOnName(Capability.Scope.SCHEMA).supported());
+ Assertions.assertTrue(capability.caseSensitiveOnName(Capability.Scope.TABLE).supported());
+ Assertions.assertTrue(capability.caseSensitiveOnName(Capability.Scope.VIEW).supported());
+ Assertions.assertTrue(capability.caseSensitiveOnName(Capability.Scope.COLUMN).supported());
+ Assertions.assertEquals("Schema", capability.normalizeName(Capability.Scope.SCHEMA, "Schema"));
+ Assertions.assertEquals("Table", capability.normalizeName(Capability.Scope.TABLE, "Table"));
+ Assertions.assertEquals("View", capability.normalizeName(Capability.Scope.VIEW, "View"));
+ Assertions.assertEquals("Column", capability.normalizeName(Capability.Scope.COLUMN, "Column"));
+ }
+
@Test
public void testCustomSeparatorSlash() {
IcebergCatalogCapability capability = new IcebergCatalogCapability("/");
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/CatalogIcebergBaseIT.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/CatalogIcebergBaseIT.java
index e7daf4f57b..0801b127aa 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/CatalogIcebergBaseIT.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/CatalogIcebergBaseIT.java
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.catalog.lakehouse.iceberg.integration.test;
+import static org.apache.gravitino.StringIdentifier.ID_KEY;
import static org.apache.gravitino.catalog.lakehouse.iceberg.IcebergTable.DEFAULT_ICEBERG_PROVIDER;
import static org.apache.gravitino.catalog.lakehouse.iceberg.IcebergTable.ICEBERG_AVRO_FILE_FORMAT;
import static org.apache.gravitino.catalog.lakehouse.iceberg.IcebergTable.ICEBERG_ORC_FILE_FORMAT;
@@ -261,6 +262,44 @@ public abstract class CatalogIcebergBaseIT extends BaseIT {
catalog = loadCatalog;
}
+ @Test
+ void testRecreateTableAfterExternalDropDoesNotInheritGovernance() {
+ NameIdentifier identifier = NameIdentifier.of(schemaName, tableName);
+ TableIdentifier sourceIdentifier =
+ TableIdentifier.of(IcebergCatalogWrapperHelper.getIcebergNamespace(schemaName), tableName);
+ Column[] columns = new Column[] {Column.of("value", Types.IntegerType.get())};
+ TableCatalog tables = catalog.asTableCatalog();
+ Table original =
+ tables.createTable(
+ identifier, columns, "original", Collections.emptyMap(), new Transform[0]);
+ String oldId = icebergCatalog.loadTable(sourceIdentifier).properties().get(ID_KEY);
+ Assertions.assertNotNull(oldId);
+
+ String tagName = GravitinoITUtils.genRandomName("old_table_tag");
+ metalake.createTag(tagName, "old registration", Collections.emptyMap());
+ try {
+ original.supportsTags().associateTags(new String[] {tagName}, null);
+ Assertions.assertEquals(1, metalake.getTag(tagName).associatedObjects().objects().length);
+
+ // Bypass Gravitino exactly as an external REST client would (issue #14865). Its old
+ // metadata registration remains live when the source table is dropped without purging.
+ Assertions.assertTrue(icebergCatalog.dropTable(sourceIdentifier, false));
+ Assertions.assertDoesNotThrow(
+ () ->
+ tables.createTable(
+ identifier, columns, "replacement", Collections.emptyMap(), new Transform[0]));
+ String newId = icebergCatalog.loadTable(sourceIdentifier).properties().get(ID_KEY);
+ Assertions.assertNotNull(newId);
+ Assertions.assertNotEquals(oldId, newId);
+ Table loaded = Assertions.assertDoesNotThrow(() -> tables.loadTable(identifier));
+ Assertions.assertEquals("replacement", loaded.comment());
+ Assertions.assertEquals(0, loaded.supportsTags().listTags().length);
+ Assertions.assertEquals(0, metalake.getTag(tagName).associatedObjects().objects().length);
+ } finally {
+ metalake.deleteTag(tagName);
+ }
+ }
+
@Test
void testExistingCatalogConnection() {
Assertions.assertDoesNotThrow(() -> metalake.testConnection(catalogName));
diff --git a/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/PaimonCatalog.java b/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/PaimonCatalog.java
index 6f7379be7f..10fc53ed54 100644
--- a/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/PaimonCatalog.java
+++ b/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/PaimonCatalog.java
@@ -89,7 +89,9 @@ public class PaimonCatalog extends BaseCatalog<PaimonCatalog> {
@Override
public Capability newCapability() {
- return new PaimonCatalogCapability();
+ Map<String, String> properties = entity().getProperties();
+ String backend = properties == null ? null : properties.get(PaimonConstants.CATALOG_BACKEND);
+ return new PaimonCatalogCapability(PaimonCatalogBackend.HIVE.name().equalsIgnoreCase(backend));
}
@Override
diff --git a/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/PaimonCatalogCapability.java b/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/PaimonCatalogCapability.java
index 4bd283d020..cc584b0f4f 100644
--- a/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/PaimonCatalogCapability.java
+++ b/catalogs/catalog-lakehouse-paimon/src/main/java/org/apache/gravitino/catalog/lakehouse/paimon/PaimonCatalogCapability.java
@@ -23,10 +23,30 @@ import org.apache.gravitino.connector.capability.CapabilityResult;
public class PaimonCatalogCapability implements Capability {
+ private final boolean hiveBackend;
+
+ /** Creates a Paimon catalog capability with the default case-sensitive name behavior. */
+ public PaimonCatalogCapability() {
+ this(false);
+ }
+
+ PaimonCatalogCapability(boolean hiveBackend) {
+ this.hiveBackend = hiveBackend;
+ }
+
@Override
public CapabilityResult columnDefaultValue() {
// See https://github.com/apache/paimon/pull/1425/files
return CapabilityResult.unsupported(
"Paimon set column default value through table properties instead of column info.");
}
+
+ @Override
+ public CapabilityResult caseSensitiveOnName(Scope scope) {
+ if (hiveBackend && (scope == Scope.SCHEMA || scope == Scope.TABLE || scope == Scope.VIEW)) {
+ return CapabilityResult.unsupported(
+ "The Paimon Hive backend is case insensitive for schemas, tables, and views.");
+ }
+ return Capability.super.caseSensitiveOnName(scope);
+ }
}
diff --git a/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/TestPaimonCatalog.java b/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/TestPaimonCatalog.java
index 38dac59319..db1d2c61cf 100644
--- a/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/TestPaimonCatalog.java
+++ b/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/TestPaimonCatalog.java
@@ -37,6 +37,7 @@ import org.apache.gravitino.catalog.lakehouse.paimon.ops.PaimonCatalogOps;
import org.apache.gravitino.connector.CatalogOperations;
import org.apache.gravitino.connector.HasPropertyMetadata;
import org.apache.gravitino.connector.PropertiesMetadata;
+import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.credential.AzureAccountKeyCredential;
import org.apache.gravitino.credential.CredentialConstants;
import org.apache.gravitino.credential.DlfSecretKeyCredential;
@@ -129,6 +130,8 @@ public class TestPaimonCatalog {
conf.put(PaimonCatalogPropertiesMetadata.WAREHOUSE, tempDir);
PaimonCatalog paimonCatalog =
new PaimonCatalog().withCatalogConf(conf).withCatalogEntity(entity);
+ Assertions.assertTrue(
+ paimonCatalog.newCapability().caseSensitiveOnName(Capability.Scope.SCHEMA).supported());
CatalogOperations catalogOperations = paimonCatalog.ops();
Assertions.assertInstanceOf(PaimonCatalogOperations.class, catalogOperations);
diff --git a/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/TestPaimonCatalogCapability.java b/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/TestPaimonCatalogCapability.java
new file mode 100644
index 0000000000..88e063c467
--- /dev/null
+++ b/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/TestPaimonCatalogCapability.java
@@ -0,0 +1,52 @@
+/*
+ * 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.catalog.lakehouse.paimon;
+
+import org.apache.gravitino.connector.capability.Capability;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/** Tests for {@link PaimonCatalogCapability}. */
+public class TestPaimonCatalogCapability {
+
+ @Test
+ public void testHiveBackendFoldsSchemaTableAndViewNamesOnly() {
+ PaimonCatalogCapability capability = new PaimonCatalogCapability(true);
+
+ Assertions.assertFalse(capability.caseSensitiveOnName(Capability.Scope.SCHEMA).supported());
+ Assertions.assertFalse(capability.caseSensitiveOnName(Capability.Scope.TABLE).supported());
+ Assertions.assertFalse(capability.caseSensitiveOnName(Capability.Scope.VIEW).supported());
+ Assertions.assertTrue(capability.caseSensitiveOnName(Capability.Scope.COLUMN).supported());
+
+ Assertions.assertEquals("schema", capability.normalizeName(Capability.Scope.SCHEMA, "Schema"));
+ Assertions.assertEquals("table", capability.normalizeName(Capability.Scope.TABLE, "Table"));
+ Assertions.assertEquals("view", capability.normalizeName(Capability.Scope.VIEW, "View"));
+ Assertions.assertEquals("Column", capability.normalizeName(Capability.Scope.COLUMN, "Column"));
+ }
+
+ @Test
+ public void testNonHiveBackendKeepsEntityNameCase() {
+ PaimonCatalogCapability capability = new PaimonCatalogCapability(false);
+
+ Assertions.assertEquals("Schema", capability.normalizeName(Capability.Scope.SCHEMA, "Schema"));
+ Assertions.assertEquals("Table", capability.normalizeName(Capability.Scope.TABLE, "Table"));
+ Assertions.assertEquals("View", capability.normalizeName(Capability.Scope.VIEW, "View"));
+ Assertions.assertEquals("Column", capability.normalizeName(Capability.Scope.COLUMN, "Column"));
+ }
+}
diff --git a/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/integration/test/CatalogPaimonHiveIT.java b/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/integration/test/CatalogPaimonHiveIT.java
index f943d971dc..baf83adf61 100644
--- a/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/integration/test/CatalogPaimonHiveIT.java
+++ b/catalogs/catalog-lakehouse-paimon/src/test/java/org/apache/gravitino/catalog/lakehouse/paimon/integration/test/CatalogPaimonHiveIT.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.catalog.lakehouse.paimon.integration.test;
import com.google.common.collect.Maps;
import java.util.Collections;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Schema;
@@ -31,6 +32,7 @@ import org.apache.gravitino.integration.test.util.GravitinoITUtils;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Representation;
import org.apache.gravitino.rel.SQLRepresentation;
+import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.View;
import org.apache.gravitino.rel.ViewCatalog;
import org.apache.gravitino.rel.types.Types;
@@ -142,6 +144,19 @@ public class CatalogPaimonHiveIT extends CatalogPaimonBaseIT {
schemaName,
Collections.emptyMap());
+ View loadedView =
+ viewCatalog.loadView(NameIdentifier.of(schemaName, viewName.toUpperCase(Locale.ROOT)));
+ Assertions.assertEquals(viewName, loadedView.name());
+
+ Table loadedTable =
+ catalog
+ .asTableCatalog()
+ .loadTable(
+ NameIdentifier.of(
+ schemaName.toUpperCase(Locale.ROOT),
+ baseTableIdentifier.name().toUpperCase(Locale.ROOT)));
+ Assertions.assertEquals(baseTableIdentifier.name(), loadedTable.name());
+
Dataset<Row> rows =
spark.sql(String.format("SELECT * FROM paimon.%s.%s ORDER BY id", schemaName, viewName));
List<Row> results = rows.collectAsList();
@@ -166,7 +181,7 @@ public class CatalogPaimonHiveIT extends CatalogPaimonBaseIT {
Assertions.assertEquals(createdSchema.properties().get("key"), "hive");
// load schema check.
- Schema schema = schemas.loadSchema(schemaIdent.name());
+ Schema schema = schemas.loadSchema(schemaIdent.name().toUpperCase(Locale.ROOT));
Assertions.assertEquals(schema.properties().get("key"), "hive");
Map<String, String> loadedProps = paimonCatalog.getDatabase(schemaIdent.name()).options();
Assertions.assertEquals(loadedProps.get("key"), "hive");
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java
index d70a3b775e..781e07427e 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java
@@ -826,6 +826,9 @@ public class ErrorHandlers {
case ErrorConstants.ALREADY_EXISTS_CODE:
throw new TopicAlreadyExistsException(errorMessage);
+ case ErrorConstants.UNSUPPORTED_OPERATION_CODE:
+ throw new UnsupportedOperationException(errorMessage);
+
case ErrorConstants.FORBIDDEN_CODE:
throw new ForbiddenException(errorMessage);
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestMessagingCatalog.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestMessagingCatalog.java
index bc42a6ec6f..5db4b64194 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestMessagingCatalog.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestMessagingCatalog.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.client;
import static org.apache.hc.core5.http.HttpStatus.SC_CONFLICT;
import static org.apache.hc.core5.http.HttpStatus.SC_NOT_FOUND;
+import static org.apache.hc.core5.http.HttpStatus.SC_NOT_IMPLEMENTED;
import static org.apache.hc.core5.http.HttpStatus.SC_OK;
import static org.apache.hc.core5.http.HttpStatus.SC_SERVER_ERROR;
@@ -163,6 +164,14 @@ public class TestMessagingCatalog extends TestBase {
Assertions.assertThrows(
NoSuchSchemaException.class, () -> catalog.asTopicCatalog().loadTopic(topic));
Assertions.assertEquals("schema not found", ex.getMessage());
+
+ // test UnsupportedOperationException
+ ErrorResponse unsupportedResp = ErrorResponse.unsupportedOperation("unsupported operation");
+ buildMockResource(Method.GET, topicPath, null, unsupportedResp, SC_NOT_IMPLEMENTED);
+ ex =
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> catalog.asTopicCatalog().loadTopic(topic));
+ Assertions.assertEquals("unsupported operation", ex.getMessage());
}
@Test
diff --git a/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java
index dd0486318d..9fe4bfd002 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/OperationDispatcher.java
@@ -88,6 +88,51 @@ public abstract class OperationDispatcher {
this.secretManager = secretManager;
}
+ /**
+ * Creates the user-facing error for an external identifier conflict with active metadata.
+ *
+ * <p>The error describes the supported recovery choices without implying that Gravitino offers
+ * object-level metadata-only unregister operations.
+ *
+ * @param ident the external entity identifier
+ * @param entityType the type of the external entity
+ * @return an exception containing conflict recovery instructions
+ */
+ protected UnsupportedOperationException retainedExternalIdentifierConflictException(
+ NameIdentifier ident, Entity.EntityType entityType) {
+ String entityName;
+ switch (entityType) {
+ case SCHEMA:
+ entityName = "schema";
+ break;
+ case TABLE:
+ entityName = "table";
+ break;
+ case VIEW:
+ entityName = "view";
+ break;
+ case TOPIC:
+ entityName = "topic";
+ break;
+ default:
+ entityName = "object";
+ }
+
+ return new UnsupportedOperationException(
+ String.format(
+ "%s %s cannot be imported because its name or external identifier is already managed "
+ + "under a different Gravitino identifier. Gravitino does not automatically "
+ + "reconcile conflicting external %s registrations, and it does not support "
+ + "metadata-only unregister of an individual external %s. Recovery requires an "
+ + "administrator to force-drop and recreate the containing Gravitino catalog "
+ + "registration. This catalog-wide reset removes every stored registration and "
+ + "its privileges, tags, and other relationships in that Gravitino catalog. "
+ + "Follow the catalog-specific recovery guidance to confirm that external objects "
+ + "are retained. Their existing external identifiers can be imported again after "
+ + "the conflicting catalog registration has been dropped.",
+ entityName, ident, entityName, entityName));
+ }
+
/**
* Fills missing creation fields when another node imported the same object first. The cold import
* already carries these fields in its initial write and needs no additional update. Ordinary
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 670c1ef380..e2f22d6900 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SchemaOperationDispatcher.java
@@ -671,17 +671,16 @@ public class SchemaOperationDispatcher extends OperationDispatcher implements Sc
LockType.WRITE,
() -> importSchemaFromCatalog(ident, importAudit));
} catch (EntityAlreadyExistsException e) {
- // HA race: another Gravitino node concurrently imported this schema. Reload from the
- // entity store to verify the entity stored by the winning node is consistent.
+ // A create-only import can conflict with a concurrent import or an identity registered
+ // under another catalog. Reload to verify the winning registration's identity.
LOG.info(
- "Schema {} was concurrently imported by another node; reloading from store.", ident);
+ "Schema {} import conflicted with existing metadata; reloading from store: {}",
+ ident,
+ e.getMessage());
EntityCombinedSchema reloaded =
TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadSchema(ident));
if (!reloaded.imported()) {
- throw new UnsupportedOperationException(
- "Schema managed by multiple catalogs. This may cause unexpected issues such as "
- + "privilege conflicts. To resolve: Remove all catalogs managing this schema, "
- + "then recreate one catalog to ensure single-catalog management.");
+ throw retainedExternalIdentifierConflictException(ident, SCHEMA);
}
schema = reloaded;
}
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 29521eaf88..dee8cd263c 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/TableOperationDispatcher.java
@@ -600,17 +600,17 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
TreeLockUtils.doWithTreeLock(
ident, LockType.WRITE, () -> importTableFromCatalog(ident, importAudit));
} 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.
+ // A create-only import can conflict either because another Gravitino node won an HA race,
+ // or because the external identifier is already stored under another Gravitino path.
+ // Reload to distinguish a successful concurrent import from an identity conflict.
LOG.info(
- "Table {} was concurrently imported by another node; reloading from store.", ident);
+ "Table {} import conflicted with existing metadata; reloading from store: {}",
+ ident,
+ e.getMessage());
entityCombinedTable =
TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadTable(ident));
if (!entityCombinedTable.imported()) {
- throw new UnsupportedOperationException(
- "Table managed by multiple catalogs. This may cause unexpected issues such as "
- + "privilege conflicts. To resolve: Remove all catalogs managing this table, "
- + "then recreate one catalog to ensure single-catalog management.");
+ throw retainedExternalIdentifierConflictException(ident, TABLE);
}
}
}
@@ -696,13 +696,17 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
long uid;
if (stringId != null) {
- // If the entity in the store doesn't match the external system, we use the data
- // of external system to correct it.
+ // An external identifier may already be stored under another Gravitino path because the
+ // table was renamed outside Gravitino or because multiple catalogs expose one metastore.
+ // Those cases are indistinguishable here, so Gravitino must not automatically reassign the
+ // stored identity because doing so can silently move the table between paths. The create-only
+ // write below reports the conflict for manual identifier cleanup.
LOG.warn(
- "The Table uid {} existed but still need to be imported, this could be happened "
- + "when Table is renamed by external systems not controlled by Gravitino. In this "
- + "case, we need to overwrite the stored entity to keep the consistency.",
- stringId);
+ "Table uid {} exists externally but is not imported at {}. Gravitino will use a "
+ + "create-only import; if this uid is already stored under another identifier, "
+ + "manual identifier cleanup is required.",
+ stringId,
+ identifier);
uid = stringId.id();
} else {
// If entity doesn't exist, we import the entity from the external system.
@@ -730,11 +734,10 @@ public class TableOperationDispatcher extends OperationDispatcher implements Tab
.withAuditInfo(audit)
.build();
try {
- // Overwrite only with the id stored in the catalog: it identifies the table, so a row under
- // the same name with another id is stale and gets replaced. A generated id identifies
- // nothing, so a row that appeared meanwhile, e.g. from a concurrent import on another node,
- // must win. The plain insert then conflicts, and loadTable reloads that row.
- store.put(tableEntity, stringId != null);
+ // Never overwrite imported table metadata. In particular, an overwrite by stable ID can
+ // silently change schema or catalog ownership and make existing privileges refer to the
+ // wrong path.
+ store.put(tableEntity, false);
} catch (EntityAlreadyExistsException e) {
throw e;
} catch (OptimisticLockException e) {
diff --git a/core/src/main/java/org/apache/gravitino/catalog/TopicOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/TopicOperationDispatcher.java
index a5f878ab37..58ecd63a6d 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/TopicOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/TopicOperationDispatcher.java
@@ -26,6 +26,7 @@ import static org.apache.gravitino.utils.NameIdentifierUtil.getCatalogIdentifier
import java.time.Instant;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.EntityStore;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
@@ -125,14 +126,20 @@ public class TopicOperationDispatcher extends OperationDispatcher implements Top
NameIdentifier schemaIdent = NameIdentifier.of(ident.namespace().levels());
schemaDispatcher.loadSchema(schemaIdent);
- // Import the topic
- TreeLockUtils.doWithTreeLock(
- schemaIdent,
- LockType.WRITE,
- () -> {
- importTopic(ident);
- return null;
- });
+ try {
+ topic = TreeLockUtils.doWithTreeLock(schemaIdent, LockType.WRITE, () -> importTopic(ident));
+ } catch (EntityAlreadyExistsException e) {
+ // A create-only import can conflict either because another Gravitino node won an HA race,
+ // or because the Kafka UUID is actively registered under another Gravitino path.
+ LOG.info(
+ "Topic {} import conflicted with existing metadata; reloading from store: {}",
+ ident,
+ e.getMessage());
+ topic = TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadTopic(ident));
+ if (!topic.imported()) {
+ throw retainedExternalIdentifierConflictException(ident, TOPIC);
+ }
+ }
}
return topic;
@@ -284,12 +291,12 @@ public class TopicOperationDispatcher extends OperationDispatcher implements Top
});
}
- private void importTopic(NameIdentifier identifier) {
+ private EntityCombinedTopic importTopic(NameIdentifier identifier) {
EntityCombinedTopic topic = internalLoadTopic(identifier);
if (topic.imported()) {
- return;
+ return topic;
}
StringIdentifier stringId = null;
@@ -329,7 +336,9 @@ public class TopicOperationDispatcher extends OperationDispatcher implements Top
.build();
try {
- store.put(topicEntity, true);
+ store.put(topicEntity, false);
+ } catch (EntityAlreadyExistsException e) {
+ throw e;
} catch (OptimisticLockException e) {
// A conflict with a concurrent writer, such as a lock wait timeout; the load can be retried.
throw e;
@@ -337,6 +346,13 @@ public class TopicOperationDispatcher extends OperationDispatcher implements Top
LOG.error(FormattedErrorMessages.STORE_OP_FAILURE, "put", identifier, e);
throw new RuntimeException("Failed to import topic entity to the store", e);
}
+
+ return EntityCombinedTopic.of(topic, topicEntity)
+ .withHiddenProperties(
+ getMaskAndOmitKeys(
+ getCatalogIdentifier(identifier),
+ HasPropertyMetadata::topicPropertiesMetadata,
+ topic.properties()));
}
private EntityCombinedTopic internalLoadTopic(NameIdentifier ident) {
diff --git a/core/src/main/java/org/apache/gravitino/catalog/ViewOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/ViewOperationDispatcher.java
index 22c31b333f..292f8491f1 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/ViewOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/ViewOperationDispatcher.java
@@ -543,9 +543,24 @@ public class ViewOperationDispatcher extends OperationDispatcher implements View
NameIdentifier schemaIdent = NameIdentifier.of(ident.namespace().levels());
schemaDispatcher.loadSchema(schemaIdent);
- entityCombinedView =
- TreeLockUtils.doWithTreeLock(
- schemaIdent, LockType.WRITE, () -> importViewFromCatalog(ident, importAudit));
+ try {
+ entityCombinedView =
+ TreeLockUtils.doWithTreeLock(
+ schemaIdent, LockType.WRITE, () -> importViewFromCatalog(ident, importAudit));
+ } catch (EntityAlreadyExistsException e) {
+ // A create-only import can conflict either because another Gravitino node won an HA race,
+ // or because the external identifier is already stored under another Gravitino path.
+ // Reload to distinguish a successful concurrent import from an identity conflict.
+ LOG.info(
+ "View {} import conflicted with existing metadata; reloading from store: {}",
+ ident,
+ e.getMessage());
+ entityCombinedView =
+ TreeLockUtils.doWithTreeLock(ident, LockType.READ, () -> internalLoadView(ident));
+ if (!entityCombinedView.imported()) {
+ throw retainedExternalIdentifierConflictException(ident, VIEW);
+ }
+ }
}
ViewEntity entity =
@@ -587,13 +602,17 @@ public class ViewOperationDispatcher extends OperationDispatcher implements View
long uid;
if (stringId != null) {
- // If the entity in the store doesn't match the external system, we use the data
- // of external system to correct it.
+ // An external identifier may already be stored under another Gravitino path because the
+ // view was renamed outside Gravitino or because multiple catalogs expose one metastore.
+ // Those cases are indistinguishable here, so Gravitino must not automatically reassign the
+ // stored identity because doing so can silently move the view between paths. The create-only
+ // write below reports the conflict for manual identifier cleanup.
LOG.warn(
- "The View uid {} existed but still need to be imported, this could happen "
- + "when View is renamed by external systems not controlled by Gravitino. In this "
- + "case, we need to overwrite the stored entity to keep the consistency.",
- stringId);
+ "View uid {} exists externally but is not imported at {}. Gravitino will use a "
+ + "create-only import; if this uid is already stored under another identifier, "
+ + "manual identifier cleanup is required.",
+ stringId,
+ ident);
uid = stringId.id();
} else {
// If entity doesn't exist, we import the entity from the external system.
@@ -628,12 +647,12 @@ public class ViewOperationDispatcher extends OperationDispatcher implements View
.withAuditInfo(audit)
.build();
try {
- store.put(viewEntity, true /* overwrite */);
+ // Never overwrite imported view metadata. In particular, an overwrite by stable ID can
+ // silently change schema or catalog ownership and make existing privileges refer to the
+ // wrong path.
+ store.put(viewEntity, false);
} catch (EntityAlreadyExistsException e) {
- LOG.error("Failed to import view {} with id {} to the store.", ident, uid, e);
- throw new UnsupportedOperationException(
- "View managed by multiple catalogs. This may cause unexpected issues such as privilege conflicts. "
- + "To resolve: Remove all catalogs managing this view, then recreate one catalog to ensure single-catalog management.");
+ throw e;
} catch (OptimisticLockException e) {
// A conflict with a concurrent writer, such as a lock wait timeout; the load can be retried.
throw e;
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 35376961cd..1f6c844c19 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,7 +20,6 @@
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;
@@ -97,18 +96,6 @@ 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 b9f56a9ccf..bcebb42eb9 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,12 +106,6 @@ 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/TableMetaMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TableMetaMapper.java
index be36fe45d7..722f4d3493 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TableMetaMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TableMetaMapper.java
@@ -160,17 +160,24 @@ public interface TableMetaMapper {
@Param("newSchemaId") Long newSchemaId);
/**
- * Soft-deletes a table only if its version has not changed since the caller read it.
+ * Soft-deletes an observed table registration in the same catalog lifetime.
*
- * @param tableId the table ID
- * @param currentVersion the version observed by the caller
- * @return the number of deleted rows; zero means the table changed or disappeared
+ * @param tableId the stable external identity
+ * @param currentVersion the observed row version
+ * @param catalogId the observed parent catalog identity
+ * @param schemaId the observed parent schema identity
+ * @param tableName the observed table name
+ * @return the number of affected rows
*/
@UpdateProvider(
type = TableMetaSQLProviderFactory.class,
method = "softDeleteTableMetasByTableId")
Integer softDeleteTableMetasByTableId(
- @Param("tableId") Long tableId, @Param("currentVersion") Long currentVersion);
+ @Param("tableId") Long tableId,
+ @Param("currentVersion") Long currentVersion,
+ @Param("catalogId") Long catalogId,
+ @Param("schemaId") Long schemaId,
+ @Param("tableName") String tableName);
@UpdateProvider(
type = TableMetaSQLProviderFactory.class,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TableMetaSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TableMetaSQLProviderFactory.java
index 10ea2fd2a0..070e03b8c3 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TableMetaSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TableMetaSQLProviderFactory.java
@@ -115,15 +115,23 @@ public class TableMetaSQLProviderFactory {
}
/**
- * Returns SQL that soft-deletes a table with a version check.
+ * Soft-deletes an observed table registration in the same catalog lifetime.
*
- * @param tableId the table ID
- * @param currentVersion the version observed by the caller
- * @return the version-checked delete SQL
+ * @param tableId the stable external identity
+ * @param currentVersion the observed row version
+ * @param catalogId the observed parent catalog identity
+ * @param schemaId the observed parent schema identity
+ * @param tableName the observed table name
+ * @return the guarded soft-delete SQL
*/
public static String softDeleteTableMetasByTableId(
- @Param("tableId") Long tableId, @Param("currentVersion") Long currentVersion) {
- return getProvider().softDeleteTableMetasByTableId(tableId, currentVersion);
+ @Param("tableId") Long tableId,
+ @Param("currentVersion") Long currentVersion,
+ @Param("catalogId") Long catalogId,
+ @Param("schemaId") Long schemaId,
+ @Param("tableName") String tableName) {
+ return getProvider()
+ .softDeleteTableMetasByTableId(tableId, currentVersion, catalogId, schemaId, tableName);
}
public static String softDeleteTableMetasByMetalakeId(@Param("metalakeId") Long metalakeId) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TopicMetaMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TopicMetaMapper.java
index 23b781129d..42232cceb2 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TopicMetaMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TopicMetaMapper.java
@@ -89,17 +89,24 @@ public interface TopicMetaMapper {
@Param("schemaId") Long schemaId, @Param("topicName") String name);
/**
- * Soft-deletes a topic only if its version has not changed since the caller read it.
+ * Soft-deletes an observed topic registration in the same catalog lifetime.
*
- * @param topicId the topic ID
- * @param currentVersion the version observed by the caller
- * @return the number of deleted rows; zero means the topic changed or disappeared
+ * @param topicId the stable external identity
+ * @param currentVersion the observed row version
+ * @param catalogId the observed parent catalog identity
+ * @param schemaId the observed parent schema identity
+ * @param topicName the observed topic name
+ * @return the number of affected rows
*/
@UpdateProvider(
type = TopicMetaSQLProviderFactory.class,
method = "softDeleteTopicMetasByTopicId")
Integer softDeleteTopicMetasByTopicId(
- @Param("topicId") Long topicId, @Param("currentVersion") Long currentVersion);
+ @Param("topicId") Long topicId,
+ @Param("currentVersion") Long currentVersion,
+ @Param("catalogId") Long catalogId,
+ @Param("schemaId") Long schemaId,
+ @Param("topicName") String topicName);
@UpdateProvider(
type = TopicMetaSQLProviderFactory.class,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TopicMetaSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TopicMetaSQLProviderFactory.java
index 3e808b53f1..103f1c98ab 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TopicMetaSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/TopicMetaSQLProviderFactory.java
@@ -124,15 +124,23 @@ public class TopicMetaSQLProviderFactory {
}
/**
- * Returns SQL that soft-deletes a topic by ID and expected version.
+ * Soft-deletes an observed topic registration in the same catalog lifetime.
*
- * @param topicId the topic ID
- * @param currentVersion the version observed by the caller
- * @return the version-checked delete SQL
+ * @param topicId the stable external identity
+ * @param currentVersion the observed row version
+ * @param catalogId the observed parent catalog identity
+ * @param schemaId the observed parent schema identity
+ * @param topicName the observed topic name
+ * @return the guarded soft-delete SQL
*/
public static String softDeleteTopicMetasByTopicId(
- @Param("topicId") Long topicId, @Param("currentVersion") Long currentVersion) {
- return getProvider().softDeleteTopicMetasByTopicId(topicId, currentVersion);
+ @Param("topicId") Long topicId,
+ @Param("currentVersion") Long currentVersion,
+ @Param("catalogId") Long catalogId,
+ @Param("schemaId") Long schemaId,
+ @Param("topicName") String topicName) {
+ return getProvider()
+ .softDeleteTopicMetasByTopicId(topicId, currentVersion, catalogId, schemaId, topicName);
}
public static String softDeleteTopicMetasByCatalogId(@Param("catalogId") Long catalogId) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewMetaMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewMetaMapper.java
index a2d3bcf125..ebfe1a64f8 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewMetaMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewMetaMapper.java
@@ -154,15 +154,22 @@ public interface ViewMetaMapper {
@Param("newViewMeta") ViewPO newViewPO, @Param("oldViewMeta") ViewPO oldViewPO);
/**
- * Soft-deletes a view only if its version has not changed since the caller read it.
+ * Soft-deletes an observed view registration in the same catalog lifetime.
*
- * @param viewId the view ID
- * @param currentVersion the version observed by the caller
- * @return the number of deleted rows; zero means the view changed or disappeared
+ * @param viewId the stable external identity
+ * @param currentVersion the observed row version
+ * @param catalogId the observed parent catalog identity
+ * @param schemaId the observed parent schema identity
+ * @param viewName the observed view name
+ * @return the number of affected rows
*/
@UpdateProvider(type = ViewMetaSQLProviderFactory.class, method = "softDeleteViewMetasByViewId")
Integer softDeleteViewMetasByViewId(
- @Param("viewId") Long viewId, @Param("currentVersion") Long currentVersion);
+ @Param("viewId") Long viewId,
+ @Param("currentVersion") Long currentVersion,
+ @Param("catalogId") Long catalogId,
+ @Param("schemaId") Long schemaId,
+ @Param("viewName") String viewName);
@UpdateProvider(
type = ViewMetaSQLProviderFactory.class,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewMetaSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewMetaSQLProviderFactory.java
index 8531c2f748..971efd3805 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewMetaSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewMetaSQLProviderFactory.java
@@ -111,15 +111,23 @@ public class ViewMetaSQLProviderFactory {
}
/**
- * Returns SQL that soft-deletes a view with a version check.
+ * Soft-deletes an observed view registration in the same catalog lifetime.
*
- * @param viewId the view ID
- * @param currentVersion the version observed by the caller
- * @return the version-checked delete SQL
+ * @param viewId the stable external identity
+ * @param currentVersion the observed row version
+ * @param catalogId the observed parent catalog identity
+ * @param schemaId the observed parent schema identity
+ * @param viewName the observed view name
+ * @return the guarded soft-delete SQL
*/
public static String softDeleteViewMetasByViewId(
- @Param("viewId") Long viewId, @Param("currentVersion") Long currentVersion) {
- return getProvider().softDeleteViewMetasByViewId(viewId, currentVersion);
+ @Param("viewId") Long viewId,
+ @Param("currentVersion") Long currentVersion,
+ @Param("catalogId") Long catalogId,
+ @Param("schemaId") Long schemaId,
+ @Param("viewName") String viewName) {
+ return getProvider()
+ .softDeleteViewMetasByViewId(viewId, currentVersion, catalogId, schemaId, viewName);
}
public static String softDeleteViewMetasByMetalakeId(@Param("metalakeId") Long metalakeId) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/MetadataObjectSQL.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/MetadataObjectSQL.java
new file mode 100644
index 0000000000..422417781c
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/MetadataObjectSQL.java
@@ -0,0 +1,90 @@
+/*
+ * 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.storage.relational.mapper.provider;
+
+/**
+ * SQL predicates that keep historical entity rows from deleting another registration's metadata.
+ */
+public final class MetadataObjectSQL {
+ private MetadataObjectSQL() {}
+
+ /**
+ * Excludes identities that currently belong to another catalog.
+ *
+ * @param tableName the entity table name
+ * @param idColumn the stable identity column
+ * @param alias the historical entity row alias
+ * @return a predicate bound to the catalogId MyBatis parameter
+ */
+ public static String excludeOtherActiveCatalogs(String tableName, String idColumn, String alias) {
+ return " AND NOT EXISTS (SELECT 1 FROM "
+ + tableName
+ + " live WHERE live."
+ + idColumn
+ + " = "
+ + alias
+ + "."
+ + idColumn
+ + " AND live.deleted_at = 0 AND live.catalog_id != #{catalogId})";
+ }
+
+ /**
+ * Excludes identities that currently belong to another metalake.
+ *
+ * @param tableName the entity table name
+ * @param idColumn the stable identity column
+ * @param alias the historical entity row alias
+ * @return a predicate bound to the metalakeId MyBatis parameter
+ */
+ public static String excludeOtherActiveMetalakes(
+ String tableName, String idColumn, String alias) {
+ return " AND NOT EXISTS (SELECT 1 FROM "
+ + tableName
+ + " live WHERE live."
+ + idColumn
+ + " = "
+ + alias
+ + "."
+ + idColumn
+ + " AND live.deleted_at = 0 AND live.metalake_id != #{metalakeId})";
+ }
+
+ /**
+ * Excludes identities that currently belong to a schema outside the deletion scope.
+ *
+ * @param tableName the entity table name
+ * @param idColumn the stable identity column
+ * @param alias the historical entity row alias
+ * @return a predicate bound to the schemaIds MyBatis collection
+ */
+ public static String excludeOtherActiveSchemas(String tableName, String idColumn, String alias) {
+ return " AND NOT EXISTS (SELECT 1 FROM "
+ + tableName
+ + " live WHERE live."
+ + idColumn
+ + " = "
+ + alias
+ + "."
+ + idColumn
+ + " AND live.deleted_at = 0 AND live.schema_id NOT IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach>)";
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/OwnerMetaBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/OwnerMetaBaseSQLProvider.java
index 8ce23075c1..9003c80217 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/OwnerMetaBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/OwnerMetaBaseSQLProvider.java
@@ -28,11 +28,14 @@ import org.apache.gravitino.storage.relational.mapper.GroupMetaMapper;
import org.apache.gravitino.storage.relational.mapper.JobMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.TableColumnMapper;
import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
import org.apache.gravitino.storage.relational.mapper.UserMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.mapper.provider.MetadataObjectSQL;
import org.apache.gravitino.storage.relational.po.OwnerRelForDeletion;
import org.apache.gravitino.storage.relational.po.OwnerRelPO;
import org.apache.ibatis.annotations.Param;
@@ -252,36 +255,61 @@ public class OwnerMetaBaseSQLProvider {
+ SchemaMetaMapper.TABLE_NAME
+ " st WHERE st.catalog_id = #{catalogId} AND"
+ " st.schema_id = ot.metadata_object_id AND ot.metadata_object_type = 'SCHEMA'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SchemaMetaMapper.TABLE_NAME, "schema_id", "st")
+ " UNION"
+ " SELECT tt.catalog_id FROM "
+ TopicMetaMapper.TABLE_NAME
+ " tt WHERE tt.catalog_id = #{catalogId} AND"
+ " tt.topic_id = ot.metadata_object_id AND ot.metadata_object_type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.catalog_id FROM "
+ TableMetaMapper.TABLE_NAME
+ " tat WHERE tat.catalog_id = #{catalogId} AND"
+ " tat.table_id = ot.metadata_object_id AND ot.metadata_object_type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.catalog_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
+ " ft WHERE ft.catalog_id = #{catalogId} AND"
+ " ft.fileset_id = ot.metadata_object_id AND ot.metadata_object_type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT mt.catalog_id FROM "
+ ModelMetaMapper.TABLE_NAME
+ " mt WHERE mt.catalog_id = #{catalogId} AND"
+ " mt.model_id = ot.metadata_object_id AND ot.metadata_object_type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ " UNION"
+ " SELECT vt.catalog_id FROM "
+ ViewMetaMapper.TABLE_NAME
+ " vt WHERE vt.catalog_id = #{catalogId} AND"
+ " vt.view_id = ot.metadata_object_id AND ot.metadata_object_type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ " UNION"
+ " SELECT fnt.catalog_id FROM "
+ FunctionMetaMapper.TABLE_NAME
+ " fnt WHERE fnt.catalog_id = #{catalogId} AND"
+ " fnt.function_id = ot.metadata_object_id AND ot.metadata_object_type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ + " UNION"
+ + " SELECT cot.catalog_id FROM "
+ + TableColumnMapper.COLUMN_TABLE_NAME
+ + " cot WHERE cot.catalog_id = #{catalogId} AND"
+ + " cot.column_id = ot.metadata_object_id AND ot.metadata_object_type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ + " UNION"
+ + " SELECT smt.catalog_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.catalog_id = #{catalogId} AND"
+ + " smt.semantic_model_id = ot.metadata_object_id AND ot.metadata_object_type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ ")";
}
@@ -326,6 +354,7 @@ public class OwnerMetaBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND tt.topic_id = ot.metadata_object_id AND ot.metadata_object_type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.schema_id FROM "
+ TableMetaMapper.TABLE_NAME
@@ -334,6 +363,7 @@ public class OwnerMetaBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND tat.table_id = ot.metadata_object_id AND ot.metadata_object_type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.schema_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
@@ -342,6 +372,8 @@ public class OwnerMetaBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND ft.fileset_id = ot.metadata_object_id AND ot.metadata_object_type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT mt.schema_id FROM "
+ ModelMetaMapper.TABLE_NAME
@@ -350,6 +382,7 @@ public class OwnerMetaBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND mt.model_id = ot.metadata_object_id AND ot.metadata_object_type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ " UNION"
+ " SELECT vt.schema_id FROM "
+ ViewMetaMapper.TABLE_NAME
@@ -358,6 +391,7 @@ public class OwnerMetaBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND vt.view_id = ot.metadata_object_id AND ot.metadata_object_type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ " UNION"
+ " SELECT fnt.schema_id FROM "
+ FunctionMetaMapper.TABLE_NAME
@@ -366,6 +400,28 @@ public class OwnerMetaBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND fnt.function_id = ot.metadata_object_id AND ot.metadata_object_type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ + " UNION"
+ + " SELECT cot.schema_id FROM "
+ + TableColumnMapper.COLUMN_TABLE_NAME
+ + " cot WHERE cot.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " cot.column_id = ot.metadata_object_id AND ot.metadata_object_type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ + " UNION"
+ + " SELECT smt.schema_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " smt.semantic_model_id = ot.metadata_object_id AND ot.metadata_object_type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ ")"
+ "</script>";
}
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 380cf69790..41a815e1ef 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
@@ -193,16 +193,6 @@ public class SchemaMetaBaseSQLProvider {
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. */
public String selectActiveChildBySchemaId(@Param("schemaId") Long schemaId) {
// Each branch returns only the same literal, so UNION ALL avoids unnecessary duplicate
@@ -360,6 +350,7 @@ public class SchemaMetaBaseSQLProvider {
+ " last_version = #{newSchemaMeta.lastVersion},"
+ " deleted_at = #{newSchemaMeta.deletedAt}"
+ " WHERE schema_id = #{oldSchemaMeta.schemaId}"
+ + " AND catalog_id = #{oldSchemaMeta.catalogId}"
+ " AND current_version = #{oldSchemaMeta.currentVersion}"
+ " AND deleted_at = 0";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SecurableObjectBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SecurableObjectBaseSQLProvider.java
index 08a28134b4..5faa18d3ea 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SecurableObjectBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SecurableObjectBaseSQLProvider.java
@@ -27,10 +27,13 @@ import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.TableColumnMapper;
import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.mapper.provider.MetadataObjectSQL;
import org.apache.gravitino.storage.relational.po.SecurableObjectPO;
import org.apache.ibatis.annotations.Param;
@@ -117,36 +120,61 @@ public class SecurableObjectBaseSQLProvider {
+ SchemaMetaMapper.TABLE_NAME
+ " st WHERE st.catalog_id = #{catalogId} AND"
+ " st.schema_id = sect.metadata_object_id AND sect.type = 'SCHEMA'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SchemaMetaMapper.TABLE_NAME, "schema_id", "st")
+ " UNION"
+ " SELECT tt.catalog_id FROM "
+ TopicMetaMapper.TABLE_NAME
+ " tt WHERE tt.catalog_id = #{catalogId} AND"
+ " tt.topic_id = sect.metadata_object_id AND sect.type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.catalog_id FROM "
+ TableMetaMapper.TABLE_NAME
+ " tat WHERE tat.catalog_id = #{catalogId} AND"
+ " tat.table_id = sect.metadata_object_id AND sect.type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.catalog_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
+ " ft WHERE ft.catalog_id = #{catalogId} AND"
+ " ft.fileset_id = sect.metadata_object_id AND sect.type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT mt.catalog_id FROM "
+ ModelMetaMapper.TABLE_NAME
+ " mt WHERE mt.catalog_id = #{catalogId} AND"
+ " mt.model_id = sect.metadata_object_id AND sect.type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ " UNION"
+ " SELECT vt.catalog_id FROM "
+ ViewMetaMapper.TABLE_NAME
+ " vt WHERE vt.catalog_id = #{catalogId} AND"
+ " vt.view_id = sect.metadata_object_id AND sect.type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ " UNION"
+ " SELECT fnt.catalog_id FROM "
+ FunctionMetaMapper.TABLE_NAME
+ " fnt WHERE fnt.catalog_id = #{catalogId} AND"
+ " fnt.function_id = sect.metadata_object_id AND sect.type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ + " UNION"
+ + " SELECT cot.catalog_id FROM "
+ + TableColumnMapper.COLUMN_TABLE_NAME
+ + " cot WHERE cot.catalog_id = #{catalogId} AND"
+ + " cot.column_id = sect.metadata_object_id AND sect.type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ + " UNION"
+ + " SELECT smt.catalog_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.catalog_id = #{catalogId} AND"
+ + " smt.semantic_model_id = sect.metadata_object_id AND sect.type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ ")";
}
@@ -172,6 +200,7 @@ public class SecurableObjectBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND tt.topic_id = sect.metadata_object_id AND sect.type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.schema_id FROM "
+ TableMetaMapper.TABLE_NAME
@@ -180,6 +209,7 @@ public class SecurableObjectBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND tat.table_id = sect.metadata_object_id AND sect.type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.schema_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
@@ -188,6 +218,8 @@ public class SecurableObjectBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND ft.fileset_id = sect.metadata_object_id AND sect.type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT mt.schema_id FROM "
+ ModelMetaMapper.TABLE_NAME
@@ -196,6 +228,7 @@ public class SecurableObjectBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND mt.model_id = sect.metadata_object_id AND sect.type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ " UNION"
+ " SELECT vt.schema_id FROM "
+ ViewMetaMapper.TABLE_NAME
@@ -204,6 +237,7 @@ public class SecurableObjectBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND vt.view_id = sect.metadata_object_id AND sect.type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ " UNION"
+ " SELECT fnt.schema_id FROM "
+ FunctionMetaMapper.TABLE_NAME
@@ -212,6 +246,28 @@ public class SecurableObjectBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND fnt.function_id = sect.metadata_object_id AND sect.type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ + " UNION"
+ + " SELECT cot.schema_id FROM "
+ + TableColumnMapper.COLUMN_TABLE_NAME
+ + " cot WHERE cot.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " cot.column_id = sect.metadata_object_id AND sect.type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ + " UNION"
+ + " SELECT smt.schema_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " smt.semantic_model_id = sect.metadata_object_id AND sect.type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ ")"
+ "</script>";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/StatisticBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/StatisticBaseSQLProvider.java
index dd20247b89..e9fa741262 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/StatisticBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/StatisticBaseSQLProvider.java
@@ -23,11 +23,16 @@ import static org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper
import java.util.List;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.TableColumnMapper;
import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.mapper.provider.MetadataObjectSQL;
import org.apache.gravitino.storage.relational.po.StatisticPO;
import org.apache.ibatis.annotations.Param;
@@ -156,26 +161,61 @@ public class StatisticBaseSQLProvider {
+ SchemaMetaMapper.TABLE_NAME
+ " st WHERE st.catalog_id = #{catalogId} AND"
+ " st.schema_id = stat.metadata_object_id AND stat.metadata_object_type = 'SCHEMA'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SchemaMetaMapper.TABLE_NAME, "schema_id", "st")
+ " UNION"
+ " SELECT tt.catalog_id FROM "
+ TopicMetaMapper.TABLE_NAME
+ " tt WHERE tt.catalog_id = #{catalogId} AND"
+ " tt.topic_id = stat.metadata_object_id AND stat.metadata_object_type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.catalog_id FROM "
+ TableMetaMapper.TABLE_NAME
+ " tat WHERE tat.catalog_id = #{catalogId} AND"
+ " tat.table_id = stat.metadata_object_id AND stat.metadata_object_type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.catalog_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
+ " ft WHERE ft.catalog_id = #{catalogId} AND"
+ " ft.fileset_id = stat.metadata_object_id AND stat.metadata_object_type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT mt.catalog_id FROM "
+ ModelMetaMapper.TABLE_NAME
+ " mt WHERE mt.catalog_id = #{catalogId} AND"
+ " mt.model_id = stat.metadata_object_id AND stat.metadata_object_type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ + " UNION"
+ + " SELECT cot.catalog_id FROM "
+ + TableColumnMapper.COLUMN_TABLE_NAME
+ + " cot WHERE cot.catalog_id = #{catalogId} AND"
+ + " cot.column_id = stat.metadata_object_id AND stat.metadata_object_type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ + " UNION"
+ + " SELECT smt.catalog_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.catalog_id = #{catalogId} AND"
+ + " smt.semantic_model_id = stat.metadata_object_id AND stat.metadata_object_type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ + " UNION"
+ + " SELECT vt.catalog_id FROM "
+ + ViewMetaMapper.TABLE_NAME
+ + " vt WHERE vt.catalog_id = #{catalogId} AND"
+ + " vt.view_id = stat.metadata_object_id AND stat.metadata_object_type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ + " UNION"
+ + " SELECT fnt.catalog_id FROM "
+ + FunctionMetaMapper.TABLE_NAME
+ + " fnt WHERE fnt.catalog_id = #{catalogId} AND"
+ + " fnt.function_id = stat.metadata_object_id AND stat.metadata_object_type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ ")";
}
@@ -201,6 +241,7 @@ public class StatisticBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND tt.topic_id = stat.metadata_object_id AND stat.metadata_object_type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.schema_id FROM "
+ TableMetaMapper.TABLE_NAME
@@ -209,6 +250,7 @@ public class StatisticBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND tat.table_id = stat.metadata_object_id AND stat.metadata_object_type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.schema_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
@@ -217,6 +259,8 @@ public class StatisticBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND ft.fileset_id = stat.metadata_object_id AND stat.metadata_object_type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT mt.schema_id FROM "
+ ModelMetaMapper.TABLE_NAME
@@ -225,6 +269,46 @@ public class StatisticBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND mt.model_id = stat.metadata_object_id AND stat.metadata_object_type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ + " UNION"
+ + " SELECT cot.schema_id FROM "
+ + TableColumnMapper.COLUMN_TABLE_NAME
+ + " cot WHERE cot.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " cot.column_id = stat.metadata_object_id AND stat.metadata_object_type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ + " UNION"
+ + " SELECT smt.schema_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " smt.semantic_model_id = stat.metadata_object_id AND stat.metadata_object_type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ + " UNION"
+ + " SELECT vt.schema_id FROM "
+ + ViewMetaMapper.TABLE_NAME
+ + " vt WHERE vt.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " vt.view_id = stat.metadata_object_id AND stat.metadata_object_type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ + " UNION"
+ + " SELECT fnt.schema_id FROM "
+ + FunctionMetaMapper.TABLE_NAME
+ + " fnt WHERE fnt.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " fnt.function_id = stat.metadata_object_id AND stat.metadata_object_type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ ")"
+ "</script>";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TableMetaBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TableMetaBaseSQLProvider.java
index 0b31b3f239..be9c7c8f7e 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TableMetaBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TableMetaBaseSQLProvider.java
@@ -287,21 +287,28 @@ public class TableMetaBaseSQLProvider {
}
/**
- * Returns SQL that deletes only the table version observed by the caller.
+ * Soft-deletes an observed table registration in the same catalog lifetime.
*
- * <p>For example, a drop that read version 3 must not delete version 4 after a concurrent alter.
- *
- * @param tableId the table ID
- * @param currentVersion the version observed by the caller
- * @return the version-checked delete SQL
+ * @param tableId the stable external identity
+ * @param currentVersion the observed row version
+ * @param catalogId the observed parent catalog identity
+ * @param schemaId the observed parent schema identity
+ * @param tableName the observed table name
+ * @return the guarded soft-delete SQL
*/
public String softDeleteTableMetasByTableId(
- @Param("tableId") Long tableId, @Param("currentVersion") Long currentVersion) {
+ @Param("tableId") Long tableId,
+ @Param("currentVersion") Long currentVersion,
+ @Param("catalogId") Long catalogId,
+ @Param("schemaId") Long schemaId,
+ @Param("tableName") String tableName) {
return "UPDATE "
+ TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.MYSQL
+ " WHERE table_id = #{tableId}"
+ + " AND catalog_id = #{catalogId}"
+ + " AND schema_id = #{schemaId} AND table_name = #{tableName}"
+ " AND current_version = #{currentVersion} AND deleted_at = 0";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TableVersionBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TableVersionBaseSQLProvider.java
index 11dcc3a1be..9a71890efe 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TableVersionBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TableVersionBaseSQLProvider.java
@@ -24,6 +24,7 @@ import static org.apache.gravitino.storage.relational.mapper.TableVersionMapper.
import java.util.List;
import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.mapper.provider.MetadataObjectSQL;
import org.apache.gravitino.storage.relational.po.TablePO;
import org.apache.ibatis.annotations.Param;
@@ -93,7 +94,8 @@ public class TableVersionBaseSQLProvider {
* schema IDs. The table_version_info table has no schema_id column, so a sub-query joins
* table_meta to find the matching table_ids. The sub-query intentionally does not filter on
* table_meta.deleted_at because this method runs after softDeleteTableMetasBySchemaIds within the
- * same transaction; at that point the table_meta rows already have deleted_at set.
+ * same transaction; at that point the table_meta rows already have deleted_at set. IDs with an
+ * active registration outside these schemas are excluded.
*/
public String softDeleteTableVersionsBySchemaIds(@Param("schemaIds") List<Long> schemaIds) {
return "<script>"
@@ -101,13 +103,15 @@ public class TableVersionBaseSQLProvider {
+ TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.MYSQL
- + " WHERE table_id IN (SELECT table_id FROM "
+ + " WHERE table_id IN (SELECT tm.table_id FROM "
+ TableMetaMapper.TABLE_NAME
- + " WHERE schema_id IN ("
+ + " tm WHERE tm.schema_id IN ("
+ "<foreach collection='schemaIds' item='schemaId' separator=','>"
+ "#{schemaId}"
+ "</foreach>"
- + ")) AND deleted_at = 0"
+ + ")"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TableMetaMapper.TABLE_NAME, "table_id", "tm")
+ + ") AND deleted_at = 0"
+ "</script>";
}
@@ -115,32 +119,37 @@ public class TableVersionBaseSQLProvider {
* Soft-deletes active table version rows whose parent table belongs to the given catalog.
* table_version_info has no catalog_id column, so a sub-query on table_meta finds the table_ids.
* Runs after softDeleteTableMetasByCatalogId in the same transaction, so the sub-query does not
- * filter table_meta.deleted_at.
+ * filter table_meta.deleted_at. IDs with an active registration in another catalog are excluded.
*/
public String softDeleteTableVersionsByCatalogId(@Param("catalogId") Long catalogId) {
return "UPDATE "
+ TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.MYSQL
- + " WHERE table_id IN (SELECT table_id FROM "
+ + " WHERE table_id IN (SELECT tm.table_id FROM "
+ TableMetaMapper.TABLE_NAME
- + " WHERE catalog_id = #{catalogId}) AND deleted_at = 0";
+ + " tm WHERE tm.catalog_id = #{catalogId}"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(TableMetaMapper.TABLE_NAME, "table_id", "tm")
+ + ") AND deleted_at = 0";
}
/**
* Soft-deletes active table version rows whose parent table belongs to the given metalake.
* table_version_info has no metalake_id column, so a sub-query on table_meta finds the table_ids.
* Runs after softDeleteTableMetasByMetalakeId in the same transaction, so the sub-query does not
- * filter table_meta.deleted_at.
+ * filter table_meta.deleted_at. IDs with an active registration in another metalake are excluded.
*/
public String softDeleteTableVersionsByMetalakeId(@Param("metalakeId") Long metalakeId) {
return "UPDATE "
+ TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.MYSQL
- + " WHERE table_id IN (SELECT table_id FROM "
+ + " WHERE table_id IN (SELECT tm.table_id FROM "
+ TableMetaMapper.TABLE_NAME
- + " WHERE metalake_id = #{metalakeId}) AND deleted_at = 0";
+ + " tm WHERE tm.metalake_id = #{metalakeId}"
+ + MetadataObjectSQL.excludeOtherActiveMetalakes(
+ TableMetaMapper.TABLE_NAME, "table_id", "tm")
+ + ") AND deleted_at = 0";
}
public String deleteTableVersionByLegacyTimeline(
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TagMetadataObjectRelBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TagMetadataObjectRelBaseSQLProvider.java
index 0ff1846d21..bbf26fb078 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TagMetadataObjectRelBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TagMetadataObjectRelBaseSQLProvider.java
@@ -26,6 +26,7 @@ import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TableColumnMapper;
import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetaMapper;
@@ -33,6 +34,7 @@ import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper
import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.mapper.provider.MetadataObjectSQL;
import org.apache.gravitino.storage.relational.po.TagMetadataObjectRelPO;
import org.apache.ibatis.annotations.Param;
@@ -302,41 +304,61 @@ public class TagMetadataObjectRelBaseSQLProvider {
+ SchemaMetaMapper.TABLE_NAME
+ " st WHERE st.catalog_id = #{catalogId} AND"
+ " st.schema_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'SCHEMA'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SchemaMetaMapper.TABLE_NAME, "schema_id", "st")
+ " UNION"
+ " SELECT tt.catalog_id FROM "
+ TopicMetaMapper.TABLE_NAME
+ " tt WHERE tt.catalog_id = #{catalogId} AND"
+ " tt.topic_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.catalog_id FROM "
+ TableMetaMapper.TABLE_NAME
+ " tat WHERE tat.catalog_id = #{catalogId} AND"
+ " tat.table_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.catalog_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
+ " ft WHERE ft.catalog_id = #{catalogId} AND"
+ " ft.fileset_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT cot.catalog_id FROM "
+ TableColumnMapper.COLUMN_TABLE_NAME
+ " cot WHERE cot.catalog_id = #{catalogId} AND"
+ " cot.column_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ " UNION"
+ " SELECT mt.catalog_id FROM "
+ ModelMetaMapper.TABLE_NAME
+ " mt WHERE mt.catalog_id = #{catalogId} AND"
+ " mt.model_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ " UNION"
+ " SELECT vt.catalog_id FROM "
+ ViewMetaMapper.TABLE_NAME
+ " vt WHERE vt.catalog_id = #{catalogId} AND"
+ " vt.view_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ " UNION"
+ " SELECT fnt.catalog_id FROM "
+ FunctionMetaMapper.TABLE_NAME
+ " fnt WHERE fnt.catalog_id = #{catalogId} AND"
+ " fnt.function_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ + " UNION"
+ + " SELECT smt.catalog_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.catalog_id = #{catalogId} AND"
+ + " smt.semantic_model_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ ")";
}
@@ -363,6 +385,7 @@ public class TagMetadataObjectRelBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND tt.topic_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.schema_id FROM "
+ TableMetaMapper.TABLE_NAME
@@ -371,6 +394,7 @@ public class TagMetadataObjectRelBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND tat.table_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.schema_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
@@ -379,6 +403,8 @@ public class TagMetadataObjectRelBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND ft.fileset_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT cot.schema_id FROM "
+ TableColumnMapper.COLUMN_TABLE_NAME
@@ -387,6 +413,8 @@ public class TagMetadataObjectRelBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND cot.column_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ " UNION"
+ " SELECT mt.schema_id FROM "
+ ModelMetaMapper.TABLE_NAME
@@ -395,6 +423,7 @@ public class TagMetadataObjectRelBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND mt.model_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ " UNION"
+ " SELECT vt.schema_id FROM "
+ ViewMetaMapper.TABLE_NAME
@@ -403,6 +432,7 @@ public class TagMetadataObjectRelBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND vt.view_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ " UNION"
+ " SELECT fnt.schema_id FROM "
+ FunctionMetaMapper.TABLE_NAME
@@ -411,6 +441,18 @@ public class TagMetadataObjectRelBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND fnt.function_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ + " UNION"
+ + " SELECT smt.schema_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " smt.semantic_model_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ ")"
+ "</script>";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TopicMetaBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TopicMetaBaseSQLProvider.java
index ae87d060e0..1dd8366984 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TopicMetaBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TopicMetaBaseSQLProvider.java
@@ -270,19 +270,28 @@ public class TopicMetaBaseSQLProvider {
}
/**
- * Returns SQL that deletes only the topic version observed by the caller.
+ * Soft-deletes an observed topic registration in the same catalog lifetime.
*
- * @param topicId the topic ID
- * @param currentVersion the version observed by the caller
- * @return the version-checked delete SQL
+ * @param topicId the stable external identity
+ * @param currentVersion the observed row version
+ * @param catalogId the observed parent catalog identity
+ * @param schemaId the observed parent schema identity
+ * @param topicName the observed topic name
+ * @return the guarded soft-delete SQL
*/
public String softDeleteTopicMetasByTopicId(
- @Param("topicId") Long topicId, @Param("currentVersion") Long currentVersion) {
+ @Param("topicId") Long topicId,
+ @Param("currentVersion") Long currentVersion,
+ @Param("catalogId") Long catalogId,
+ @Param("schemaId") Long schemaId,
+ @Param("topicName") String topicName) {
return "UPDATE "
+ TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.MYSQL
+ " WHERE topic_id = #{topicId}"
+ + " AND catalog_id = #{catalogId}"
+ + " AND schema_id = #{schemaId} AND topic_name = #{topicName}"
+ " AND current_version = #{currentVersion} AND deleted_at = 0";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewMetaBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewMetaBaseSQLProvider.java
index 4f5ecbb04a..e793f4035b 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewMetaBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewMetaBaseSQLProvider.java
@@ -228,19 +228,28 @@ public class ViewMetaBaseSQLProvider {
}
/**
- * Returns SQL that deletes only the view version observed by the caller.
+ * Soft-deletes an observed view registration in the same catalog lifetime.
*
- * @param viewId the view ID
- * @param currentVersion the version observed by the caller
- * @return the version-checked delete SQL
+ * @param viewId the stable external identity
+ * @param currentVersion the observed row version
+ * @param catalogId the observed parent catalog identity
+ * @param schemaId the observed parent schema identity
+ * @param viewName the observed view name
+ * @return the guarded soft-delete SQL
*/
public String softDeleteViewMetasByViewId(
- @Param("viewId") Long viewId, @Param("currentVersion") Long currentVersion) {
+ @Param("viewId") Long viewId,
+ @Param("currentVersion") Long currentVersion,
+ @Param("catalogId") Long catalogId,
+ @Param("schemaId") Long schemaId,
+ @Param("viewName") String viewName) {
return "UPDATE "
+ TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.MYSQL
+ " WHERE view_id = #{viewId}"
+ + " AND catalog_id = #{catalogId}"
+ + " AND schema_id = #{schemaId} AND view_name = #{viewName}"
+ " AND current_version = #{currentVersion} AND deleted_at = 0";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewVersionInfoBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewVersionInfoBaseSQLProvider.java
index d3521749ad..79d3a21c76 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewVersionInfoBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewVersionInfoBaseSQLProvider.java
@@ -22,6 +22,7 @@ import java.util.List;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewVersionInfoMapper;
import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.mapper.provider.MetadataObjectSQL;
import org.apache.gravitino.storage.relational.po.ViewVersionInfoPO;
import org.apache.ibatis.annotations.Param;
@@ -71,13 +72,15 @@ public class ViewVersionInfoBaseSQLProvider {
+ DatabaseTimeSQL.MYSQL
// History follows the stable entity ID, not the parent recorded in each snapshot.
// Include deleted roots: cascade cleanup soft-deletes roots before their versions.
- + " WHERE view_id IN (SELECT view_id FROM "
+ + " WHERE view_id IN (SELECT vm.view_id FROM "
+ ViewMetaMapper.TABLE_NAME
- + " WHERE schema_id IN ("
+ + " vm WHERE vm.schema_id IN ("
+ "<foreach collection='schemaIds' item='schemaId' separator=','>"
+ "#{schemaId}"
+ "</foreach>"
- + ")) AND deleted_at = 0"
+ + ")"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ViewMetaMapper.TABLE_NAME, "view_id", "vm")
+ + ") AND deleted_at = 0"
+ "</script>";
}
@@ -86,9 +89,11 @@ public class ViewVersionInfoBaseSQLProvider {
+ ViewVersionInfoMapper.TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.MYSQL
- + " WHERE view_id IN (SELECT view_id FROM "
+ + " WHERE view_id IN (SELECT vm.view_id FROM "
+ ViewMetaMapper.TABLE_NAME
- + " WHERE catalog_id = #{catalogId}) AND deleted_at = 0";
+ + " vm WHERE vm.catalog_id = #{catalogId}"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ViewMetaMapper.TABLE_NAME, "view_id", "vm")
+ + ") AND deleted_at = 0";
}
public String softDeleteViewVersionsByMetalakeId(@Param("metalakeId") Long metalakeId) {
@@ -96,9 +101,11 @@ public class ViewVersionInfoBaseSQLProvider {
+ ViewVersionInfoMapper.TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.MYSQL
- + " WHERE view_id IN (SELECT view_id FROM "
+ + " WHERE view_id IN (SELECT vm.view_id FROM "
+ ViewMetaMapper.TABLE_NAME
- + " WHERE metalake_id = #{metalakeId}) AND deleted_at = 0";
+ + " vm WHERE vm.metalake_id = #{metalakeId}"
+ + MetadataObjectSQL.excludeOtherActiveMetalakes(ViewMetaMapper.TABLE_NAME, "view_id", "vm")
+ + ") AND deleted_at = 0";
}
public String deleteViewVersionsByLegacyTimeline(
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/OwnerMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/OwnerMetaPostgreSQLProvider.java
index e63a51714b..7cf1a43d04 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/OwnerMetaPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/OwnerMetaPostgreSQLProvider.java
@@ -26,10 +26,13 @@ import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.TableColumnMapper;
import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.mapper.provider.MetadataObjectSQL;
import org.apache.gravitino.storage.relational.mapper.provider.base.OwnerMetaBaseSQLProvider;
import org.apache.gravitino.storage.relational.po.OwnerRelForDeletion;
import org.apache.ibatis.annotations.Param;
@@ -114,36 +117,61 @@ public class OwnerMetaPostgreSQLProvider extends OwnerMetaBaseSQLProvider {
+ SchemaMetaMapper.TABLE_NAME
+ " st WHERE st.catalog_id = #{catalogId} AND"
+ " st.schema_id = ot.metadata_object_id AND ot.metadata_object_type = 'SCHEMA'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SchemaMetaMapper.TABLE_NAME, "schema_id", "st")
+ " UNION"
+ " SELECT tt.catalog_id FROM "
+ TopicMetaMapper.TABLE_NAME
+ " tt WHERE tt.catalog_id = #{catalogId} AND"
+ " tt.topic_id = ot.metadata_object_id AND ot.metadata_object_type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.catalog_id FROM "
+ TableMetaMapper.TABLE_NAME
+ " tat WHERE tat.catalog_id = #{catalogId} AND"
+ " tat.table_id = ot.metadata_object_id AND ot.metadata_object_type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.catalog_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
+ " ft WHERE ft.catalog_id = #{catalogId} AND"
+ " ft.fileset_id = ot.metadata_object_id AND ot.metadata_object_type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT mt.catalog_id FROM "
+ ModelMetaMapper.TABLE_NAME
+ " mt WHERE mt.catalog_id = #{catalogId} AND"
+ " mt.model_id = ot.metadata_object_id AND ot.metadata_object_type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ " UNION"
+ " SELECT vt.catalog_id FROM "
+ ViewMetaMapper.TABLE_NAME
+ " vt WHERE vt.catalog_id = #{catalogId} AND"
+ " vt.view_id = ot.metadata_object_id AND ot.metadata_object_type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ " UNION"
+ " SELECT fnt.catalog_id FROM "
+ FunctionMetaMapper.TABLE_NAME
+ " fnt WHERE fnt.catalog_id = #{catalogId} AND"
+ " fnt.function_id = ot.metadata_object_id AND ot.metadata_object_type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ + " UNION"
+ + " SELECT cot.catalog_id FROM "
+ + TableColumnMapper.COLUMN_TABLE_NAME
+ + " cot WHERE cot.catalog_id = #{catalogId} AND"
+ + " cot.column_id = ot.metadata_object_id AND ot.metadata_object_type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ + " UNION"
+ + " SELECT smt.catalog_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.catalog_id = #{catalogId} AND"
+ + " smt.semantic_model_id = ot.metadata_object_id AND ot.metadata_object_type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ ")";
}
@@ -173,6 +201,7 @@ public class OwnerMetaPostgreSQLProvider extends OwnerMetaBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND tt.topic_id = ot.metadata_object_id AND ot.metadata_object_type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.schema_id FROM "
+ TableMetaMapper.TABLE_NAME
@@ -181,6 +210,7 @@ public class OwnerMetaPostgreSQLProvider extends OwnerMetaBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND tat.table_id = ot.metadata_object_id AND ot.metadata_object_type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.schema_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
@@ -189,6 +219,8 @@ public class OwnerMetaPostgreSQLProvider extends OwnerMetaBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND ft.fileset_id = ot.metadata_object_id AND ot.metadata_object_type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT mt.schema_id FROM "
+ ModelMetaMapper.TABLE_NAME
@@ -197,6 +229,7 @@ public class OwnerMetaPostgreSQLProvider extends OwnerMetaBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND mt.model_id = ot.metadata_object_id AND ot.metadata_object_type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ " UNION"
+ " SELECT vt.schema_id FROM "
+ ViewMetaMapper.TABLE_NAME
@@ -205,6 +238,7 @@ public class OwnerMetaPostgreSQLProvider extends OwnerMetaBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND vt.view_id = ot.metadata_object_id AND ot.metadata_object_type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ " UNION"
+ " SELECT fnt.schema_id FROM "
+ FunctionMetaMapper.TABLE_NAME
@@ -213,6 +247,28 @@ public class OwnerMetaPostgreSQLProvider extends OwnerMetaBaseSQLProvider {
+ "#{schemaId}"
+ "</foreach>"
+ " AND fnt.function_id = ot.metadata_object_id AND ot.metadata_object_type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ + " UNION"
+ + " SELECT cot.schema_id FROM "
+ + TableColumnMapper.COLUMN_TABLE_NAME
+ + " cot WHERE cot.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " cot.column_id = ot.metadata_object_id AND ot.metadata_object_type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ + " UNION"
+ + " SELECT smt.schema_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " smt.semantic_model_id = ot.metadata_object_id AND ot.metadata_object_type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ ")"
+ "</script>";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SchemaMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SchemaMetaPostgreSQLProvider.java
index ecbb0e25b7..ce79cd3f7d 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SchemaMetaPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SchemaMetaPostgreSQLProvider.java
@@ -51,7 +51,7 @@ public class SchemaMetaPostgreSQLProvider extends SchemaMetaBaseSQLProvider {
+ " #{schemaMeta.lastVersion},"
+ " #{schemaMeta.deletedAt}"
+ " )"
- + " ON CONFLICT(schema_id) DO UPDATE SET"
+ + " ON CONFLICT(schema_id, deleted_at) DO UPDATE SET"
+ " schema_name = #{schemaMeta.schemaName},"
+ " metalake_id = #{schemaMeta.metalakeId},"
+ " catalog_id = #{schemaMeta.catalogId},"
@@ -85,7 +85,7 @@ public class SchemaMetaPostgreSQLProvider extends SchemaMetaBaseSQLProvider {
+ " #{po.schemaComment}, #{po.properties}, #{po.auditInfo},"
+ " #{po.currentVersion}, #{po.lastVersion}, #{po.deletedAt})"
+ "</foreach>"
- + " ON CONFLICT(schema_id) DO UPDATE SET"
+ + " ON CONFLICT(schema_id, deleted_at) DO UPDATE SET"
+ " schema_name = EXCLUDED.schema_name,"
+ " metalake_id = EXCLUDED.metalake_id,"
+ " catalog_id = EXCLUDED.catalog_id,"
@@ -122,6 +122,7 @@ public class SchemaMetaPostgreSQLProvider extends SchemaMetaBaseSQLProvider {
+ " last_version = #{newSchemaMeta.lastVersion},"
+ " deleted_at = #{newSchemaMeta.deletedAt}"
+ " WHERE schema_id = #{oldSchemaMeta.schemaId}"
+ + " AND catalog_id = #{oldSchemaMeta.catalogId}"
+ " AND current_version = #{oldSchemaMeta.currentVersion}"
+ " AND deleted_at = 0";
}
@@ -175,7 +176,7 @@ public class SchemaMetaPostgreSQLProvider extends SchemaMetaBaseSQLProvider {
@Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {
return "DELETE FROM "
+ TABLE_NAME
- + " WHERE schema_id IN (SELECT schema_id FROM "
+ + " WHERE ctid IN (SELECT ctid FROM "
+ TABLE_NAME
+ " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit})";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SecurableObjectPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SecurableObjectPostgreSQLProvider.java
index 2cd01ecb7c..ad1024a4dd 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SecurableObjectPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SecurableObjectPostgreSQLProvider.java
@@ -27,10 +27,13 @@ import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.TableColumnMapper;
import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.mapper.provider.MetadataObjectSQL;
import org.apache.gravitino.storage.relational.mapper.provider.base.SecurableObjectBaseSQLProvider;
import org.apache.gravitino.storage.relational.po.SecurableObjectPO;
import org.apache.ibatis.annotations.Param;
@@ -100,36 +103,61 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLPro
+ SchemaMetaMapper.TABLE_NAME
+ " st WHERE st.catalog_id = #{catalogId} AND"
+ " st.schema_id = sect.metadata_object_id AND sect.type = 'SCHEMA'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SchemaMetaMapper.TABLE_NAME, "schema_id", "st")
+ " UNION"
+ " SELECT tt.catalog_id FROM "
+ TopicMetaMapper.TABLE_NAME
+ " tt WHERE tt.catalog_id = #{catalogId} AND "
+ " tt.topic_id = sect.metadata_object_id AND sect.type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.catalog_id FROM "
+ TableMetaMapper.TABLE_NAME
+ " tat WHERE tat.catalog_id = #{catalogId} AND"
+ " tat.table_id = sect.metadata_object_id AND sect.type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.catalog_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
+ " ft WHERE ft.catalog_id = #{catalogId} AND"
+ " ft.fileset_id = sect.metadata_object_id AND sect.type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT mt.catalog_id FROM "
+ ModelMetaMapper.TABLE_NAME
+ " mt WHERE mt.catalog_id = #{catalogId} AND"
+ " mt.model_id = sect.metadata_object_id AND sect.type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ " UNION"
+ " SELECT vt.catalog_id FROM "
+ ViewMetaMapper.TABLE_NAME
+ " vt WHERE vt.catalog_id = #{catalogId} AND"
+ " vt.view_id = sect.metadata_object_id AND sect.type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ " UNION"
+ " SELECT fnt.catalog_id FROM "
+ FunctionMetaMapper.TABLE_NAME
+ " fnt WHERE fnt.catalog_id = #{catalogId} AND"
+ " fnt.function_id = sect.metadata_object_id AND sect.type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ + " UNION"
+ + " SELECT cot.catalog_id FROM "
+ + TableColumnMapper.COLUMN_TABLE_NAME
+ + " cot WHERE cot.catalog_id = #{catalogId} AND"
+ + " cot.column_id = sect.metadata_object_id AND sect.type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ + " UNION"
+ + " SELECT smt.catalog_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.catalog_id = #{catalogId} AND"
+ + " smt.semantic_model_id = sect.metadata_object_id AND sect.type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ ")";
}
@@ -156,6 +184,7 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLPro
+ "#{schemaId}"
+ "</foreach>"
+ " AND tt.topic_id = sect.metadata_object_id AND sect.type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.schema_id FROM "
+ TableMetaMapper.TABLE_NAME
@@ -164,6 +193,7 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLPro
+ "#{schemaId}"
+ "</foreach>"
+ " AND tat.table_id = sect.metadata_object_id AND sect.type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.schema_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
@@ -172,6 +202,8 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLPro
+ "#{schemaId}"
+ "</foreach>"
+ " AND ft.fileset_id = sect.metadata_object_id AND sect.type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT mt.schema_id FROM "
+ ModelMetaMapper.TABLE_NAME
@@ -180,6 +212,7 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLPro
+ "#{schemaId}"
+ "</foreach>"
+ " AND mt.model_id = sect.metadata_object_id AND sect.type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ " UNION"
+ " SELECT vt.schema_id FROM "
+ ViewMetaMapper.TABLE_NAME
@@ -188,6 +221,7 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLPro
+ "#{schemaId}"
+ "</foreach>"
+ " AND vt.view_id = sect.metadata_object_id AND sect.type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ " UNION"
+ " SELECT fnt.schema_id FROM "
+ FunctionMetaMapper.TABLE_NAME
@@ -196,6 +230,28 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLPro
+ "#{schemaId}"
+ "</foreach>"
+ " AND fnt.function_id = sect.metadata_object_id AND sect.type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ + " UNION"
+ + " SELECT cot.schema_id FROM "
+ + TableColumnMapper.COLUMN_TABLE_NAME
+ + " cot WHERE cot.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " cot.column_id = sect.metadata_object_id AND sect.type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ + " UNION"
+ + " SELECT smt.schema_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " smt.semantic_model_id = sect.metadata_object_id AND sect.type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ ")"
+ "</script>";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TableMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TableMetaPostgreSQLProvider.java
index f92a19fbe4..58bf78bd0d 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TableMetaPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TableMetaPostgreSQLProvider.java
@@ -45,7 +45,7 @@ public class TableMetaPostgreSQLProvider extends TableMetaBaseSQLProvider {
+ " #{tableMeta.lastVersion},"
+ " #{tableMeta.deletedAt}"
+ " )"
- + " ON CONFLICT (table_id) DO UPDATE SET"
+ + " ON CONFLICT (table_id, deleted_at) DO UPDATE SET"
+ " table_name = #{tableMeta.tableName},"
+ " metalake_id = #{tableMeta.metalakeId},"
+ " catalog_id = #{tableMeta.catalogId},"
@@ -62,13 +62,30 @@ public class TableMetaPostgreSQLProvider extends TableMetaBaseSQLProvider {
+ " deleted_at = #{tableMeta.deletedAt}";
}
+ /**
+ * Soft-deletes an observed table registration in the same catalog lifetime.
+ *
+ * @param tableId the stable external identity
+ * @param currentVersion the observed row version
+ * @param catalogId the observed parent catalog identity
+ * @param schemaId the observed parent schema identity
+ * @param tableName the observed table name
+ * @return the guarded soft-delete SQL
+ */
@Override
- public String softDeleteTableMetasByTableId(Long tableId, Long currentVersion) {
+ public String softDeleteTableMetasByTableId(
+ Long tableId,
+ Long currentVersion,
+ Long catalogId,
+ @Param("schemaId") Long schemaId,
+ @Param("tableName") String tableName) {
return "UPDATE "
+ TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.POSTGRESQL
+ " WHERE table_id = #{tableId}"
+ + " AND catalog_id = #{catalogId}"
+ + " AND schema_id = #{schemaId} AND table_name = #{tableName}"
+ " AND current_version = #{currentVersion} AND deleted_at = 0";
}
@@ -110,7 +127,7 @@ public class TableMetaPostgreSQLProvider extends TableMetaBaseSQLProvider {
@Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {
return "DELETE FROM "
+ TABLE_NAME
- + " WHERE table_id IN (SELECT table_id FROM "
+ + " WHERE ctid IN (SELECT ctid FROM "
+ TABLE_NAME
+ " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit})";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TableVersionPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TableVersionPostgreSQLProvider.java
index 6a8a5a7854..84ae1f7386 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TableVersionPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TableVersionPostgreSQLProvider.java
@@ -24,6 +24,7 @@ import static org.apache.gravitino.storage.relational.mapper.TableVersionMapper.
import java.util.List;
import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.mapper.provider.MetadataObjectSQL;
import org.apache.gravitino.storage.relational.mapper.provider.base.TableVersionBaseSQLProvider;
import org.apache.gravitino.storage.relational.po.TablePO;
import org.apache.ibatis.annotations.Param;
@@ -76,13 +77,15 @@ public class TableVersionPostgreSQLProvider extends TableVersionBaseSQLProvider
+ TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.POSTGRESQL
- + " WHERE table_id IN (SELECT table_id FROM "
+ + " WHERE table_id IN (SELECT tm.table_id FROM "
+ TableMetaMapper.TABLE_NAME
- + " WHERE schema_id IN ("
+ + " tm WHERE tm.schema_id IN ("
+ "<foreach collection='schemaIds' item='schemaId' separator=','>"
+ "#{schemaId}"
+ "</foreach>"
- + ")) AND deleted_at = 0"
+ + ")"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TableMetaMapper.TABLE_NAME, "table_id", "tm")
+ + ") AND deleted_at = 0"
+ "</script>";
}
@@ -92,9 +95,11 @@ public class TableVersionPostgreSQLProvider extends TableVersionBaseSQLProvider
+ TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.POSTGRESQL
- + " WHERE table_id IN (SELECT table_id FROM "
+ + " WHERE table_id IN (SELECT tm.table_id FROM "
+ TableMetaMapper.TABLE_NAME
- + " WHERE catalog_id = #{catalogId}) AND deleted_at = 0";
+ + " tm WHERE tm.catalog_id = #{catalogId}"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(TableMetaMapper.TABLE_NAME, "table_id", "tm")
+ + ") AND deleted_at = 0";
}
@Override
@@ -103,9 +108,12 @@ public class TableVersionPostgreSQLProvider extends TableVersionBaseSQLProvider
+ TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.POSTGRESQL
- + " WHERE table_id IN (SELECT table_id FROM "
+ + " WHERE table_id IN (SELECT tm.table_id FROM "
+ TableMetaMapper.TABLE_NAME
- + " WHERE metalake_id = #{metalakeId}) AND deleted_at = 0";
+ + " tm WHERE tm.metalake_id = #{metalakeId}"
+ + MetadataObjectSQL.excludeOtherActiveMetalakes(
+ TableMetaMapper.TABLE_NAME, "table_id", "tm")
+ + ") AND deleted_at = 0";
}
@Override
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TagMetadataObjectRelPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TagMetadataObjectRelPostgreSQLProvider.java
index c60b6e7695..e4af7b9fab 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TagMetadataObjectRelPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TagMetadataObjectRelPostgreSQLProvider.java
@@ -27,6 +27,7 @@ import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TableColumnMapper;
import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetaMapper;
@@ -34,6 +35,7 @@ import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper
import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.mapper.provider.MetadataObjectSQL;
import org.apache.gravitino.storage.relational.mapper.provider.base.TagMetadataObjectRelBaseSQLProvider;
import org.apache.gravitino.storage.relational.po.TagMetadataObjectRelPO;
import org.apache.ibatis.annotations.Param;
@@ -138,41 +140,61 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRel
+ SchemaMetaMapper.TABLE_NAME
+ " st WHERE st.catalog_id = #{catalogId} AND"
+ " st.schema_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'SCHEMA'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SchemaMetaMapper.TABLE_NAME, "schema_id", "st")
+ " UNION"
+ " SELECT tt.catalog_id FROM "
+ TopicMetaMapper.TABLE_NAME
+ " tt WHERE tt.catalog_id = #{catalogId} AND"
+ " tt.topic_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.catalog_id FROM "
+ TableMetaMapper.TABLE_NAME
+ " tat WHERE tat.catalog_id = #{catalogId} AND"
+ " tat.table_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.catalog_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
+ " ft WHERE ft.catalog_id = #{catalogId} AND"
+ " ft.fileset_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT cot.catalog_id FROM "
+ TableColumnMapper.COLUMN_TABLE_NAME
+ " cot WHERE cot.catalog_id = #{catalogId} AND"
+ " cot.column_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ " UNION"
+ " SELECT mt.catalog_id FROM "
+ ModelMetaMapper.TABLE_NAME
+ " mt WHERE mt.catalog_id = #{catalogId} AND"
+ " mt.model_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ " UNION"
+ " SELECT vt.catalog_id FROM "
+ ViewMetaMapper.TABLE_NAME
+ " vt WHERE vt.catalog_id = #{catalogId} AND"
+ " vt.view_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ " UNION"
+ " SELECT fnt.catalog_id FROM "
+ FunctionMetaMapper.TABLE_NAME
+ " fnt WHERE fnt.catalog_id = #{catalogId} AND"
+ " fnt.function_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ + " UNION"
+ + " SELECT smt.catalog_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.catalog_id = #{catalogId} AND"
+ + " smt.semantic_model_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ ")";
}
@@ -200,6 +222,7 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRel
+ "#{schemaId}"
+ "</foreach>"
+ " AND tt.topic_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'TOPIC'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TopicMetaMapper.TABLE_NAME, "topic_id", "tt")
+ " UNION"
+ " SELECT tat.schema_id FROM "
+ TableMetaMapper.TABLE_NAME
@@ -208,6 +231,7 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRel
+ "#{schemaId}"
+ "</foreach>"
+ " AND tat.table_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'TABLE'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(TableMetaMapper.TABLE_NAME, "table_id", "tat")
+ " UNION"
+ " SELECT ft.schema_id FROM "
+ FilesetMetaMapper.META_TABLE_NAME
@@ -216,6 +240,8 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRel
+ "#{schemaId}"
+ "</foreach>"
+ " AND ft.fileset_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'FILESET'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FilesetMetaMapper.META_TABLE_NAME, "fileset_id", "ft")
+ " UNION"
+ " SELECT cot.schema_id FROM "
+ TableColumnMapper.COLUMN_TABLE_NAME
@@ -224,6 +250,8 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRel
+ "#{schemaId}"
+ "</foreach>"
+ " AND cot.column_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'COLUMN'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ TableColumnMapper.COLUMN_TABLE_NAME, "column_id", "cot")
+ " UNION"
+ " SELECT mt.schema_id FROM "
+ ModelMetaMapper.TABLE_NAME
@@ -232,6 +260,7 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRel
+ "#{schemaId}"
+ "</foreach>"
+ " AND mt.model_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ModelMetaMapper.TABLE_NAME, "model_id", "mt")
+ " UNION"
+ " SELECT vt.schema_id FROM "
+ ViewMetaMapper.TABLE_NAME
@@ -240,6 +269,7 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRel
+ "#{schemaId}"
+ "</foreach>"
+ " AND vt.view_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'VIEW'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ViewMetaMapper.TABLE_NAME, "view_id", "vt")
+ " UNION"
+ " SELECT fnt.schema_id FROM "
+ FunctionMetaMapper.TABLE_NAME
@@ -248,6 +278,18 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRel
+ "#{schemaId}"
+ "</foreach>"
+ " AND fnt.function_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'FUNCTION'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ FunctionMetaMapper.TABLE_NAME, "function_id", "fnt")
+ + " UNION"
+ + " SELECT smt.schema_id FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smt WHERE smt.schema_id IN "
+ + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+ + "#{schemaId}"
+ + "</foreach> AND"
+ + " smt.semantic_model_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'SEMANTIC_MODEL'"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(
+ SemanticModelMetaMapper.TABLE_NAME, "semantic_model_id", "smt")
+ ")"
+ "</script>";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TopicMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TopicMetaPostgreSQLProvider.java
index d44ca42a1a..787e4a11ad 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TopicMetaPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TopicMetaPostgreSQLProvider.java
@@ -27,13 +27,30 @@ import org.apache.gravitino.storage.relational.po.TopicPO;
import org.apache.ibatis.annotations.Param;
public class TopicMetaPostgreSQLProvider extends TopicMetaBaseSQLProvider {
+ /**
+ * Soft-deletes an observed topic registration in the same catalog lifetime.
+ *
+ * @param topicId the stable external identity
+ * @param currentVersion the observed row version
+ * @param catalogId the observed parent catalog identity
+ * @param schemaId the observed parent schema identity
+ * @param topicName the observed topic name
+ * @return the guarded soft-delete SQL
+ */
@Override
- public String softDeleteTopicMetasByTopicId(Long topicId, Long currentVersion) {
+ public String softDeleteTopicMetasByTopicId(
+ Long topicId,
+ Long currentVersion,
+ Long catalogId,
+ @Param("schemaId") Long schemaId,
+ @Param("topicName") String topicName) {
return "UPDATE "
+ TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.POSTGRESQL
+ " WHERE topic_id = #{topicId}"
+ + " AND catalog_id = #{catalogId}"
+ + " AND schema_id = #{schemaId} AND topic_name = #{topicName}"
+ " AND current_version = #{currentVersion} AND deleted_at = 0";
}
@@ -124,7 +141,7 @@ public class TopicMetaPostgreSQLProvider extends TopicMetaBaseSQLProvider {
@Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {
return "DELETE FROM "
+ TABLE_NAME
- + " WHERE topic_id IN (SELECT topic_id FROM "
+ + " WHERE ctid IN (SELECT ctid FROM "
+ TABLE_NAME
+ " WHERE deleted_at != 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit})";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewMetaPostgreSQLProvider.java
index 058e431736..500db3fc40 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewMetaPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewMetaPostgreSQLProvider.java
@@ -64,14 +64,30 @@ public class ViewMetaPostgreSQLProvider extends ViewMetaBaseSQLProvider {
+ " AND vm.deleted_at = 0 AND vi.deleted_at = 0";
}
+ /**
+ * Soft-deletes an observed view registration in the same catalog lifetime.
+ *
+ * @param viewId the stable external identity
+ * @param currentVersion the observed row version
+ * @param catalogId the observed parent catalog identity
+ * @param schemaId the observed parent schema identity
+ * @param viewName the observed view name
+ * @return the guarded soft-delete SQL
+ */
@Override
public String softDeleteViewMetasByViewId(
- @Param("viewId") Long viewId, @Param("currentVersion") Long currentVersion) {
+ @Param("viewId") Long viewId,
+ @Param("currentVersion") Long currentVersion,
+ @Param("catalogId") Long catalogId,
+ @Param("schemaId") Long schemaId,
+ @Param("viewName") String viewName) {
return "UPDATE "
+ TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.POSTGRESQL
+ " WHERE view_id = #{viewId}"
+ + " AND catalog_id = #{catalogId}"
+ + " AND schema_id = #{schemaId} AND view_name = #{viewName}"
+ " AND current_version = #{currentVersion} AND deleted_at = 0";
}
@@ -113,7 +129,7 @@ public class ViewMetaPostgreSQLProvider extends ViewMetaBaseSQLProvider {
@Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {
return "DELETE FROM "
+ TABLE_NAME
- + " WHERE view_id IN (SELECT view_id FROM "
+ + " WHERE ctid IN (SELECT ctid FROM "
+ TABLE_NAME
+ " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit})";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewVersionInfoPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewVersionInfoPostgreSQLProvider.java
index 3b0a8307ee..d7b3fba27c 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewVersionInfoPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewVersionInfoPostgreSQLProvider.java
@@ -22,6 +22,7 @@ import java.util.List;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewVersionInfoMapper;
import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.mapper.provider.MetadataObjectSQL;
import org.apache.gravitino.storage.relational.mapper.provider.base.ViewVersionInfoBaseSQLProvider;
import org.apache.ibatis.annotations.Param;
@@ -43,13 +44,15 @@ public class ViewVersionInfoPostgreSQLProvider extends ViewVersionInfoBaseSQLPro
+ ViewVersionInfoMapper.TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.POSTGRESQL
- + " WHERE view_id IN (SELECT view_id FROM "
+ + " WHERE view_id IN (SELECT vm.view_id FROM "
+ ViewMetaMapper.TABLE_NAME
- + " WHERE schema_id IN ("
+ + " vm WHERE vm.schema_id IN ("
+ "<foreach collection='schemaIds' item='schemaId' separator=','>"
+ "#{schemaId}"
+ "</foreach>"
- + ")) AND deleted_at = 0"
+ + ")"
+ + MetadataObjectSQL.excludeOtherActiveSchemas(ViewMetaMapper.TABLE_NAME, "view_id", "vm")
+ + ") AND deleted_at = 0"
+ "</script>";
}
@@ -59,9 +62,11 @@ public class ViewVersionInfoPostgreSQLProvider extends ViewVersionInfoBaseSQLPro
+ ViewVersionInfoMapper.TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.POSTGRESQL
- + " WHERE view_id IN (SELECT view_id FROM "
+ + " WHERE view_id IN (SELECT vm.view_id FROM "
+ ViewMetaMapper.TABLE_NAME
- + " WHERE catalog_id = #{catalogId}) AND deleted_at = 0";
+ + " vm WHERE vm.catalog_id = #{catalogId}"
+ + MetadataObjectSQL.excludeOtherActiveCatalogs(ViewMetaMapper.TABLE_NAME, "view_id", "vm")
+ + ") AND deleted_at = 0";
}
@Override
@@ -70,9 +75,11 @@ public class ViewVersionInfoPostgreSQLProvider extends ViewVersionInfoBaseSQLPro
+ ViewVersionInfoMapper.TABLE_NAME
+ " SET deleted_at = "
+ DatabaseTimeSQL.POSTGRESQL
- + " WHERE view_id IN (SELECT view_id FROM "
+ + " WHERE view_id IN (SELECT vm.view_id FROM "
+ ViewMetaMapper.TABLE_NAME
- + " WHERE metalake_id = #{metalakeId}) AND deleted_at = 0";
+ + " vm WHERE vm.metalake_id = #{metalakeId}"
+ + MetadataObjectSQL.excludeOtherActiveMetalakes(ViewMetaMapper.TABLE_NAME, "view_id", "vm")
+ + ") AND deleted_at = 0";
}
@Override
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 6fd9532d04..0b1068fdf3 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
@@ -154,7 +154,7 @@ public class SchemaMetaService {
* 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
+ * @param overwrite whether to update the same active 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
@@ -525,9 +525,9 @@ public class SchemaMetaService {
// 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());
+ // Revalidate the active identity under its row lock. A retired identity is imported with a
+ // plain insert, so the composite primary key arbitrates concurrent registrations.
+ registeredId = mapper.selectSchemaMetaByIdForUpdate(incoming.getSchemaId());
rejectForeignSchemaIdentity(identifier, incoming, registeredId);
SchemaPO stored =
ops.listPOs(mapper, identifier.namespace(), List.of(identifier.name())).stream()
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java
index f50680a537..32b7af9934 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/TableMetaService.java
@@ -368,7 +368,11 @@ public class TableMetaService {
TableMetaMapper.class,
mapper ->
mapper.softDeleteTableMetasByTableId(
- observedTablePO.getTableId(), observedTablePO.getCurrentVersion())),
+ observedTablePO.getTableId(),
+ observedTablePO.getCurrentVersion(),
+ observedTablePO.getCatalogId(),
+ observedTablePO.getSchemaId(),
+ observedTablePO.getTableName())),
() -> tableWriteFailure(identifier, observedTablePO));
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java
index 0b4072d85c..ad3c28e033 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/TopicMetaService.java
@@ -355,7 +355,11 @@ public class TopicMetaService {
TopicMetaMapper.class,
mapper ->
mapper.softDeleteTopicMetasByTopicId(
- observedTopicPO.getTopicId(), observedTopicPO.getCurrentVersion())),
+ observedTopicPO.getTopicId(),
+ observedTopicPO.getCurrentVersion(),
+ observedTopicPO.getCatalogId(),
+ observedTopicPO.getSchemaId(),
+ observedTopicPO.getTopicName())),
() -> topicWriteFailure(identifier, observedTopicPO)),
() -> deleteTopicDependents(observedTopicPO.getTopicId()));
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java
index afdc379db8..605a338348 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java
@@ -245,7 +245,11 @@ public class ViewMetaService {
ViewMetaMapper.class,
mapper ->
mapper.softDeleteViewMetasByViewId(
- observedViewPO.getViewId(), observedViewPO.getCurrentVersion())),
+ observedViewPO.getViewId(),
+ observedViewPO.getCurrentVersion(),
+ observedViewPO.getCatalogId(),
+ observedViewPO.getSchemaId(),
+ observedViewPO.getViewName())),
() -> viewWriteFailure(identifier, observedViewPO)),
() -> deleteViewDependents(observedViewPO.getViewId()));
}
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 1ae5ed1140..708f0a84b3 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSchemaOperationDispatcher.java
@@ -496,6 +496,22 @@ public class TestSchemaOperationDispatcher extends TestOperationDispatcher {
Schema loadedSchema = Assertions.assertDoesNotThrow(() -> dispatcher.loadSchema(schemaIdent));
Assertions.assertEquals(schemaIdent.name(), loadedSchema.name());
Assertions.assertEquals("comment", loadedSchema.comment());
+ verify(entityStore).put(any(SchemaEntity.class), eq(false));
+ }
+
+ @Test
+ void testImportSchemaAfterRegistrationDeletionReusesIdentifier() throws IOException {
+ NameIdentifier schemaIdent =
+ NameIdentifier.of(metalake, catalog, "schema_soft_deleted_identifier");
+ dispatcher.createSchema(schemaIdent, "comment", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ SchemaEntity schemaEntity = entityStore.get(schemaIdent, SCHEMA, SchemaEntity.class);
+ entityStore.delete(schemaIdent, SCHEMA);
+
+ reset(entityStore);
+ Assertions.assertDoesNotThrow(() -> dispatcher.loadSchema(schemaIdent));
+ Assertions.assertEquals(
+ schemaEntity.id(), entityStore.get(schemaIdent, SCHEMA, SchemaEntity.class).id());
+ verify(entityStore).put(any(SchemaEntity.class), eq(false));
}
@Test
@@ -534,7 +550,13 @@ public class TestSchemaOperationDispatcher extends TestOperationDispatcher {
UnsupportedOperationException exception =
Assertions.assertThrows(
UnsupportedOperationException.class, () -> dispatcher.loadSchema(schemaIdent));
- Assertions.assertTrue(exception.getMessage().contains("Schema managed by multiple catalogs"));
+ Assertions.assertTrue(
+ exception
+ .getMessage()
+ .contains(
+ "does not automatically reconcile conflicting external schema registrations"));
+ Assertions.assertTrue(exception.getMessage().contains("catalog-specific recovery guidance"));
+ verify(entityStore).put(any(SchemaEntity.class), eq(false));
}
@Test
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 e967ba1258..a755eaa3d5 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestTableOperationDispatcher.java
@@ -900,9 +900,10 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
// Audit info is gotten from the catalog, not from the entity store
Assertions.assertEquals("test", loadedTable3.auditInfo().creator());
- // Case 4: Test if the table entity is not matched
+ // Case 4: An external rename or conflicting path must not overwrite the stored identity.
reset(entityStore);
- TableEntity tableEntity =
+ TableEntity storedBeforeConflict = entityStore.get(tableIdent1, TABLE, TableEntity.class);
+ TableEntity mismatchedEntity =
TableEntity.builder()
.withId(1L)
.withName("table11")
@@ -910,14 +911,30 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
.withAuditInfo(
AuditInfo.builder().withCreator("gravitino").withCreateTime(Instant.now()).build())
.build();
- doReturn(tableEntity).when(entityStore).get(any(), eq(Entity.EntityType.TABLE), any());
- Table loadedTable4 = tableOperationDispatcher.loadTable(tableIdent1);
- // Succeed to import the topic entity
+ doReturn(mismatchedEntity).when(entityStore).get(any(), eq(Entity.EntityType.TABLE), any());
+ UnsupportedOperationException exception =
+ Assertions.assertThrows(
+ UnsupportedOperationException.class,
+ () -> tableOperationDispatcher.loadTable(tableIdent1));
+ Assertions.assertTrue(
+ exception
+ .getMessage()
+ .contains("does not automatically reconcile conflicting external table registrations"));
+ Assertions.assertTrue(
+ exception
+ .getMessage()
+ .contains("metadata-only unregister of an individual external table"));
+ Assertions.assertTrue(exception.getMessage().contains("force-drop and recreate"));
+ Assertions.assertTrue(
+ exception.getMessage().contains("privileges, tags, and other relationships"));
+ Assertions.assertTrue(exception.getMessage().contains("catalog-specific recovery guidance"));
+ verify(entityStore).put(any(TableEntity.class), eq(false));
+
+ // The rejected import leaves the existing entity and its identity unchanged.
reset(entityStore);
- TableEntity tableImportedEntity = entityStore.get(tableIdent1, TABLE, TableEntity.class);
- Assertions.assertEquals("test", tableImportedEntity.auditInfo().creator());
- // Audit info is gotten from the catalog, not from the entity store
- Assertions.assertEquals("test", loadedTable4.auditInfo().creator());
+ TableEntity storedAfterConflict = entityStore.get(tableIdent1, TABLE, TableEntity.class);
+ Assertions.assertEquals(storedBeforeConflict.id(), storedAfterConflict.id());
+ Assertions.assertEquals(storedBeforeConflict.name(), storedAfterConflict.name());
}
@Test
@@ -929,6 +946,34 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
catalogManager, entityStore, idGenerator, null, secretManager));
}
+ @Test
+ void testImportTableAfterRegistrationDeletionReusesIdentifier() throws IOException {
+ Namespace tableNs = Namespace.of(metalake, catalog, "schema_soft_deleted_table_identifier");
+ schemaOperationDispatcher.createSchema(
+ NameIdentifier.of(tableNs.levels()), "comment", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ NameIdentifier tableIdent = NameIdentifier.of(tableNs, "table_soft_deleted_identifier");
+ tableOperationDispatcher.createTable(
+ tableIdent,
+ new Column[] {
+ TestColumn.builder()
+ .withName("col1")
+ .withPosition(0)
+ .withType(Types.StringType.get())
+ .build()
+ },
+ "comment",
+ ImmutableMap.of("k1", "v1"),
+ new Transform[0]);
+ TableEntity tableEntity = entityStore.get(tableIdent, TABLE, TableEntity.class);
+ entityStore.delete(tableIdent, TABLE);
+
+ reset(entityStore);
+ Assertions.assertDoesNotThrow(() -> tableOperationDispatcher.loadTable(tableIdent));
+ Assertions.assertEquals(
+ tableEntity.id(), entityStore.get(tableIdent, TABLE, TableEntity.class).id());
+ verify(entityStore).put(any(TableEntity.class), eq(false));
+ }
+
@Test
public void testCreateTableFailsFastWhenSchemaDispatcherSupplierReturnsNull() throws IOException {
Namespace tableNs = Namespace.of(metalake, catalog, "schema-null-dispatcher");
@@ -1271,6 +1316,7 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
Assertions.assertDoesNotThrow(() -> tableOperationDispatcher.loadTable(tableIdent));
Assertions.assertEquals(tableIdent.name(), loadedTable.name());
Assertions.assertEquals("comment", loadedTable.comment());
+ verify(entityStore).put(any(TableEntity.class), eq(false));
}
@Test
@@ -1376,7 +1422,12 @@ public class TestTableOperationDispatcher extends TestOperationDispatcher {
Assertions.assertThrows(
UnsupportedOperationException.class,
() -> tableOperationDispatcher.loadTable(tableIdent));
- Assertions.assertTrue(exception.getMessage().contains("Table managed by multiple catalogs"));
+ Assertions.assertTrue(
+ exception
+ .getMessage()
+ .contains("does not automatically reconcile conflicting external table registrations"));
+ Assertions.assertTrue(exception.getMessage().contains("catalog-specific recovery guidance"));
+ verify(entityStore).put(any(TableEntity.class), eq(false));
}
@Test
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestTopicOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestTopicOperationDispatcher.java
index c1da8293f2..db93534a1d 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestTopicOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestTopicOperationDispatcher.java
@@ -22,6 +22,7 @@ import static org.apache.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;
import static org.apache.gravitino.Configs.TREE_LOCK_MAX_NODE_IN_MEMORY;
import static org.apache.gravitino.Configs.TREE_LOCK_MIN_NODE_IN_MEMORY;
import static org.apache.gravitino.Entity.EntityType.SCHEMA;
+import static org.apache.gravitino.Entity.EntityType.TOPIC;
import static org.apache.gravitino.StringIdentifier.ID_KEY;
import static org.apache.gravitino.TestBasePropertiesMetadata.COMMENT_KEY;
import static org.apache.gravitino.TestCatalog.PROPERTY_KEY1;
@@ -33,6 +34,7 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
@@ -42,6 +44,7 @@ import java.util.Map;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Config;
import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.EntityFieldLimits;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
@@ -168,14 +171,64 @@ public class TestTopicOperationDispatcher extends TestOperationDispatcher {
AuditInfo.builder().withCreator("gravitino").withCreateTime(Instant.now()).build())
.build();
doReturn(unmatchedEntity).when(entityStore).get(any(), eq(Entity.EntityType.TOPIC), any());
- Topic loadedTopic4 = topicOperationDispatcher.loadTopic(topicIdent1);
- // Succeed to import the topic entity
+ UnsupportedOperationException exception =
+ Assertions.assertThrows(
+ UnsupportedOperationException.class,
+ () -> topicOperationDispatcher.loadTopic(topicIdent1));
+ Assertions.assertTrue(exception.getMessage().contains("topic " + topicIdent1));
+ Assertions.assertTrue(
+ exception
+ .getMessage()
+ .contains("metadata-only unregister of an individual external topic"));
+ Assertions.assertTrue(exception.getMessage().contains("catalog-specific recovery guidance"));
+ verify(entityStore).put(any(TopicEntity.class), eq(false));
reset(entityStore);
TopicEntity topicEntity =
entityStore.get(topicIdent1, Entity.EntityType.TOPIC, TopicEntity.class);
Assertions.assertEquals("test", topicEntity.auditInfo().creator());
- // Audit info is gotten from the catalog, not from the entity store
- Assertions.assertEquals("test", loadedTopic4.auditInfo().creator());
+ }
+
+ @Test
+ public void testConcurrentImportTopicReusesExistingEntity() throws IOException {
+ Namespace topicNs = Namespace.of(metalake, catalog, "schema_topic_concurrent_import");
+ NameIdentifier schemaIdent = NameIdentifier.of(topicNs.levels());
+ schemaOperationDispatcher.createSchema(
+ schemaIdent, "comment", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ NameIdentifier topicIdent = NameIdentifier.of(topicNs, "topic_concurrent_import");
+ createTopicForLockTest(topicIdent);
+ TopicEntity importedTopicEntity = entityStore.get(topicIdent, TOPIC, TopicEntity.class);
+
+ reset(entityStore);
+ doThrow(new NoSuchEntityException("mock error"))
+ .doThrow(new NoSuchEntityException("mock error"))
+ .doReturn(importedTopicEntity)
+ .when(entityStore)
+ .get(any(), eq(TOPIC), any());
+ doThrow(new EntityAlreadyExistsException("mock conflict"))
+ .when(entityStore)
+ .put(any(TopicEntity.class), eq(false));
+
+ Topic loadedTopic =
+ Assertions.assertDoesNotThrow(() -> topicOperationDispatcher.loadTopic(topicIdent));
+ Assertions.assertEquals(topicIdent.name(), loadedTopic.name());
+ }
+
+ @Test
+ void testImportTopicAfterRegistrationDeletionReusesIdentifier() throws IOException {
+ Namespace topicNs = Namespace.of(metalake, catalog, "schema_reimport_topic_identifier");
+ NameIdentifier schemaIdent = NameIdentifier.of(topicNs.levels());
+ schemaOperationDispatcher.createSchema(
+ schemaIdent, "comment", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ NameIdentifier topicIdent = NameIdentifier.of(topicNs, "topic_reimport_identifier");
+ createTopicForLockTest(topicIdent);
+ TopicEntity topicEntity = entityStore.get(topicIdent, TOPIC, TopicEntity.class);
+ entityStore.delete(topicIdent, TOPIC);
+
+ reset(entityStore);
+ Assertions.assertDoesNotThrow(() -> topicOperationDispatcher.loadTopic(topicIdent));
+ Assertions.assertEquals(
+ topicEntity.id(), entityStore.get(topicIdent, TOPIC, TopicEntity.class).id());
+ verify(entityStore).put(any(TopicEntity.class), eq(false));
}
@Test
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java
index 2a8bbaee02..d3f0f96bc6 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java
@@ -54,6 +54,7 @@ import java.util.function.Supplier;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Config;
import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
@@ -244,7 +245,7 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {
verify(entityStore, never()).put(any(ViewEntity.class), anyBoolean());
verify(entityStore).update(eq(identifier), eq(ViewEntity.class), eq(VIEW), any());
} else {
- verify(entityStore).put(any(ViewEntity.class), eq(true));
+ verify(entityStore).put(any(ViewEntity.class), eq(false));
verify(entityStore, never()).update(any(), any(), any(), any());
}
@@ -466,6 +467,111 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {
Assertions.assertEquals(1L, retrievedEntity.id(), "Entity ID should remain 1L (no new import)");
}
+ @Test
+ public void testConcurrentImportViewReusesExistingEntity() throws IOException {
+ Namespace viewNs = Namespace.of(metalake, catalog, "schema_view_concurrent_import");
+ schemaOperationDispatcher.createSchema(
+ NameIdentifier.of(viewNs.levels()), "comment", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ NameIdentifier viewIdent = NameIdentifier.of(viewNs, "view_concurrent_import");
+ View createdView = createViewForLockTest(viewIdent);
+ ViewEntity importedViewEntity = entityStore.get(viewIdent, VIEW, ViewEntity.class);
+
+ ViewEntity concurrentViewEntity =
+ ViewEntity.builder()
+ .withId(importedViewEntity.id())
+ .withName(viewIdent.name())
+ .withNamespace(viewIdent.namespace())
+ .withComment(createdView.comment())
+ .withColumns(createdView.columns())
+ .withRepresentations(createdView.representations())
+ .withProperties(createdView.properties())
+ .withAuditInfo(AuditInfo.EMPTY)
+ .build();
+
+ // Simulate an HA race: the pre-import checks miss, the create-only write conflicts, and the
+ // reload observes the entity imported by the winning node.
+ reset(entityStore);
+ doThrow(new NoSuchEntityException("mock error"))
+ .doThrow(new NoSuchEntityException("mock error"))
+ .doReturn(concurrentViewEntity)
+ .when(entityStore)
+ .get(any(), eq(Entity.EntityType.VIEW), any());
+ doThrow(new EntityAlreadyExistsException("mock conflict"))
+ .when(entityStore)
+ .put(any(), anyBoolean());
+
+ View loadedView =
+ Assertions.assertDoesNotThrow(() -> viewOperationDispatcher.loadView(viewIdent));
+ Assertions.assertEquals(viewIdent.name(), loadedView.name());
+ verify(entityStore).put(any(ViewEntity.class), eq(false));
+ }
+
+ @Test
+ public void testConcurrentImportViewFailsOnMismatchedIdentifier() throws IOException {
+ Namespace viewNs = Namespace.of(metalake, catalog, "schema_view_import_conflict");
+ schemaOperationDispatcher.createSchema(
+ NameIdentifier.of(viewNs.levels()), "comment", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ NameIdentifier viewIdent = NameIdentifier.of(viewNs, "view_import_conflict");
+ View createdView = createViewForLockTest(viewIdent);
+ ViewEntity importedViewEntity = entityStore.get(viewIdent, VIEW, ViewEntity.class);
+
+ ViewEntity mismatchedViewEntity =
+ ViewEntity.builder()
+ .withId(importedViewEntity.id() + 1)
+ .withName(viewIdent.name())
+ .withNamespace(viewIdent.namespace())
+ .withComment(createdView.comment())
+ .withColumns(createdView.columns())
+ .withRepresentations(createdView.representations())
+ .withProperties(createdView.properties())
+ .withAuditInfo(AuditInfo.EMPTY)
+ .build();
+
+ // Simulate an external rename or multi-path conflict: the create-only write fails, and the
+ // entity found during reload has a different stable ID.
+ reset(entityStore);
+ doThrow(new NoSuchEntityException("mock error"))
+ .doThrow(new NoSuchEntityException("mock error"))
+ .doReturn(mismatchedViewEntity)
+ .when(entityStore)
+ .get(any(), eq(Entity.EntityType.VIEW), any());
+ doThrow(new EntityAlreadyExistsException("mock conflict"))
+ .when(entityStore)
+ .put(any(), anyBoolean());
+
+ UnsupportedOperationException exception =
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> viewOperationDispatcher.loadView(viewIdent));
+ Assertions.assertTrue(
+ exception
+ .getMessage()
+ .contains("does not automatically reconcile conflicting external view registrations"));
+ Assertions.assertTrue(
+ exception.getMessage().contains("metadata-only unregister of an individual external view"));
+ Assertions.assertTrue(exception.getMessage().contains("force-drop and recreate"));
+ Assertions.assertTrue(
+ exception.getMessage().contains("privileges, tags, and other relationships"));
+ Assertions.assertTrue(exception.getMessage().contains("catalog-specific recovery guidance"));
+ verify(entityStore).put(any(ViewEntity.class), eq(false));
+ }
+
+ @Test
+ void testImportViewAfterRegistrationDeletionReusesIdentifier() throws IOException {
+ Namespace viewNs = Namespace.of(metalake, catalog, "schema_soft_deleted_view_identifier");
+ schemaOperationDispatcher.createSchema(
+ NameIdentifier.of(viewNs.levels()), "comment", ImmutableMap.of("k1", "v1", "k2", "v2"));
+ NameIdentifier viewIdent = NameIdentifier.of(viewNs, "view_soft_deleted_identifier");
+ createViewForLockTest(viewIdent);
+ ViewEntity viewEntity = entityStore.get(viewIdent, VIEW, ViewEntity.class);
+ entityStore.delete(viewIdent, VIEW);
+
+ reset(entityStore);
+ Assertions.assertDoesNotThrow(() -> viewOperationDispatcher.loadView(viewIdent));
+ Assertions.assertEquals(
+ viewEntity.id(), entityStore.get(viewIdent, VIEW, ViewEntity.class).id());
+ verify(entityStore).put(any(ViewEntity.class), eq(false));
+ }
+
@Test
public void testLoadViewAutoImportWithMultipleConcurrentLoads() throws Exception {
Namespace viewNs = Namespace.of(metalake, catalog, "schema66");
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 f9910aab05..01c6a4e719 100644
--- a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
+++ b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
@@ -52,6 +52,126 @@ import org.opentest4j.AssertionFailedError;
@DatabaseFixture(resetStrategy = ResetStrategy.FRESH_DATABASE)
public class TestSQLScripts extends TestJDBCBackend {
+ @TestTemplate
+ void testReimportedIdentifiersWithFreshAndUpgradedSchemas() throws SQLException, IOException {
+ Path scripts = upgradeScriptDirectory();
+ String suffix = "-" + backendType.toLowerCase(Locale.ROOT) + ".sql";
+ File upgrade = scripts.resolve("upgrade-1.3.0-to-2.0.0" + suffix).toFile();
+ List<String> inserts = externalEntityInsertStatements();
+ for (String initialVersion : List.of("1.3.0", "2.0.0")) {
+ dropAllTables();
+ executeScript(scripts.resolve("schema-" + initialVersion + suffix).toFile());
+ executeStatements(inserts, "initial registrations");
+ if (initialVersion.equals("1.3.0")) {
+ executeScript(upgrade);
+ }
+ for (int generation = 1; generation <= 2; generation++) {
+ for (String entity : List.of("schema", "table", "topic", "view")) {
+ executeStatements(
+ List.of(
+ "UPDATE "
+ + entity
+ + "_meta SET deleted_at = "
+ + generation
+ + " WHERE deleted_at = 0"),
+ "retire registration");
+ }
+ executeStatements(inserts, "reimport the same external IDs");
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = session.getConnection();
+ Statement statement = connection.createStatement()) {
+ for (String insert : inserts) {
+ String conflictingPath =
+ insert
+ .replace("'schema'", "'other_schema'")
+ .replace("'table'", "'other_table'")
+ .replace("'topic'", "'other_topic'")
+ .replace("'view'", "'other_view'")
+ .replace(", 2,", ", 3,");
+ Assertions.assertThrows(
+ SQLException.class,
+ () -> statement.executeUpdate(conflictingPath),
+ "A duplicate active identity must still fail");
+ }
+ }
+ if (initialVersion.equals("1.3.0")) {
+ executeScript(upgrade);
+ }
+ for (String entity : List.of("schema", "table", "topic", "view")) {
+ String table = entity + "_meta";
+ assertExternalIdentityPrimaryKey(table, entity + "_id");
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = session.getConnection();
+ Statement statement = connection.createStatement();
+ ResultSet result =
+ statement.executeQuery(
+ "SELECT COUNT(*), SUM(CASE WHEN deleted_at = 0 THEN 1 ELSE 0 END) FROM "
+ + table)) {
+ Assertions.assertTrue(result.next());
+ Assertions.assertEquals(
+ generation + 1, result.getInt(1), "History must remain after a migration retry");
+ Assertions.assertEquals(1, result.getInt(2), "Only one registration can be active");
+ }
+ }
+ }
+ }
+ }
+
+ @TestTemplate
+ void testUpgradeEarlierTwoZeroIdentifierKeys() throws SQLException, IOException {
+ Path scripts = upgradeScriptDirectory();
+ String suffix = "-" + backendType.toLowerCase(Locale.ROOT) + ".sql";
+ File upgrade = scripts.resolve("upgrade-1.3.0-to-2.0.0" + suffix).toFile();
+ dropAllTables();
+ executeScript(scripts.resolve("schema-2.0.0" + suffix).toFile());
+ for (String entity : List.of("schema", "table", "topic", "view")) {
+ String table = entity + "_meta";
+ String dropPrimaryKey =
+ backendType.equalsIgnoreCase("postgresql")
+ ? " DROP CONSTRAINT " + table + "_pkey"
+ : " DROP PRIMARY KEY";
+ executeStatements(
+ List.of(
+ "ALTER TABLE " + table + dropPrimaryKey,
+ "ALTER TABLE " + table + " ADD PRIMARY KEY (" + entity + "_id)"),
+ "simulate the earlier 2.0 identifier-only primary keys");
+ }
+ executeStatements(externalEntityInsertStatements(), "live 2.0 registrations");
+ seedExternalGovernance(1);
+ for (int attempt = 0; attempt < 2; attempt++) {
+ executeScript(upgrade);
+ assertExternalGovernanceCount(4);
+ for (String entity : List.of("schema", "table", "topic", "view")) {
+ assertExternalIdentityPrimaryKey(entity + "_meta", entity + "_id");
+ }
+ }
+ }
+
+ @TestTemplate
+ void testUpgradeClearsRetiredGovernanceAndPreservesReimportedGovernance()
+ throws SQLException, IOException {
+ Path scripts = upgradeScriptDirectory();
+ String suffix = "-" + backendType.toLowerCase(Locale.ROOT) + ".sql";
+ File upgrade = scripts.resolve("upgrade-1.3.0-to-2.0.0" + suffix).toFile();
+ dropAllTables();
+ executeScript(scripts.resolve("schema-1.3.0" + suffix).toFile());
+ executeStatements(externalEntityInsertStatements(), "legacy registrations");
+ seedExternalGovernance(1);
+ for (String entity : List.of("schema", "table", "topic", "view")) {
+ executeStatements(
+ List.of("UPDATE " + entity + "_meta SET deleted_at = 42"), "retire legacy registrations");
+ }
+ executeScript(upgrade);
+ assertExternalGovernanceCount(0);
+
+ executeStatements(externalEntityInsertStatements(), "reimport external IDs");
+ seedExternalGovernance(2);
+ executeScript(upgrade);
+ assertExternalGovernanceCount(4);
+ }
+
@TestTemplate
public void testSQLScripts() throws SQLException, IOException {
String gravitinoHome = System.getenv("GRAVITINO_HOME");
@@ -607,6 +727,86 @@ public class TestSQLScripts extends TestJDBCBackend {
}
}
+ private void seedExternalGovernance(int generation) throws SQLException {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = session.getConnection();
+ Statement statement = connection.createStatement()) {
+ Map<Long, String> objects = Map.of(11L, "SCHEMA", 12L, "TABLE", 13L, "TOPIC", 14L, "VIEW");
+ for (Map.Entry<Long, String> object : objects.entrySet()) {
+ long id = object.getKey();
+ String type = object.getValue();
+ statement.executeUpdate(
+ String.format(
+ "INSERT INTO owner_meta (metalake_id, owner_id, owner_type, metadata_object_id, metadata_object_type, audit_info) VALUES (1, 101, 'USER', %d, '%s', '{}')",
+ id, type));
+ statement.executeUpdate(
+ String.format(
+ "INSERT INTO role_meta_securable_object (role_id, metadata_object_id, type, privilege_names, privilege_conditions) VALUES (101, %d, '%s', '[]', '[]')",
+ id, type));
+ statement.executeUpdate(
+ String.format(
+ "INSERT INTO tag_relation_meta (tag_id, metadata_object_id, metadata_object_type, audit_info) VALUES (102, %d, '%s', '{}')",
+ id, type));
+ statement.executeUpdate(
+ String.format(
+ "INSERT INTO statistic_meta (statistic_id, statistic_name, metalake_id, statistic_value, metadata_object_id, metadata_object_type, audit_info) VALUES (%d, 'row_count', 1, '{}', %d, '%s', '{}')",
+ id + generation * 1000L, id, type));
+ }
+ }
+ }
+
+ private void assertExternalGovernanceCount(int expected) throws SQLException {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = session.getConnection();
+ Statement statement = connection.createStatement()) {
+ for (String table :
+ List.of(
+ "owner_meta", "role_meta_securable_object", "tag_relation_meta", "statistic_meta")) {
+ try (ResultSet result =
+ statement.executeQuery(
+ "SELECT COUNT(*) FROM "
+ + table
+ + " WHERE deleted_at = 0 AND metadata_object_id IN (11, 12, 13, 14)")) {
+ Assertions.assertTrue(result.next());
+ Assertions.assertEquals(expected, result.getInt(1), table);
+ }
+ }
+ }
+ }
+
+ private List<String> externalEntityInsertStatements() {
+ return List.of(
+ "INSERT INTO schema_meta (schema_id, schema_name, metalake_id, catalog_id, audit_info) VALUES (11, 'schema', 1, 2, '{}')",
+ "INSERT INTO table_meta (table_id, table_name, metalake_id, catalog_id, schema_id, audit_info) VALUES (12, 'table', 1, 2, 11, '{}')",
+ "INSERT INTO topic_meta (topic_id, topic_name, metalake_id, catalog_id, schema_id, audit_info) VALUES (13, 'topic', 1, 2, 11, '{}')",
+ "INSERT INTO view_meta (view_id, view_name, metalake_id, catalog_id, schema_id, audit_info) VALUES (14, 'view', 1, 2, 11, '{}')");
+ }
+
+ private void assertExternalIdentityPrimaryKey(String table, String idColumn) throws SQLException {
+ String actualTable =
+ readSchemaColumns().keySet().stream()
+ .filter(name -> name.equalsIgnoreCase(table))
+ .findFirst()
+ .orElseThrow();
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = session.getConnection();
+ ResultSet keys =
+ connection
+ .getMetaData()
+ .getPrimaryKeys(connection.getCatalog(), connection.getSchema(), actualTable)) {
+ Map<Short, String> columns = new TreeMap<>();
+ while (keys.next()) {
+ columns.put(
+ keys.getShort("KEY_SEQ"), keys.getString("COLUMN_NAME").toLowerCase(Locale.ROOT));
+ }
+ Assertions.assertEquals(
+ List.of(idColumn, "deleted_at"), new ArrayList<>(columns.values()), table);
+ }
+ }
+
/**
* Verifies the fileset storage location name and model version URI name columns are 256
* characters wide on every backend, both on a fresh install and after the 2.0.0 upgrade.
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestTableMetaBaseSQLProvider.java b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestTableMetaBaseSQLProvider.java
index 4bd55ccc73..6276ce4205 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestTableMetaBaseSQLProvider.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestTableMetaBaseSQLProvider.java
@@ -18,6 +18,8 @@
*/
package org.apache.gravitino.storage.relational.mapper.provider.base;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -50,7 +52,9 @@ class TestTableMetaBaseSQLProvider {
@Test
void testDirectDeleteUsesVersionCas() {
- String sql = PROVIDER.softDeleteTableMetasByTableId(null, null);
+ String sql = PROVIDER.softDeleteTableMetasByTableId(null, null, null, null, null);
+ assertTrue(sql.contains("AND schema_id = #{schemaId}"));
+ assertTrue(sql.contains("AND table_name = #{tableName}"));
Assertions.assertTrue(sql.contains("AND current_version = #{currentVersion}"));
Assertions.assertTrue(sql.endsWith("AND deleted_at = 0"));
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestTopicMetaBaseSQLProvider.java b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestTopicMetaBaseSQLProvider.java
index 7a4e98ea2e..237ca0a9e4 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestTopicMetaBaseSQLProvider.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestTopicMetaBaseSQLProvider.java
@@ -18,6 +18,8 @@
*/
package org.apache.gravitino.storage.relational.mapper.provider.base;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -53,7 +55,9 @@ class TestTopicMetaBaseSQLProvider {
@Test
void testDirectDeleteUsesVersionCas() {
- String sql = PROVIDER.softDeleteTopicMetasByTopicId(null, null);
+ String sql = PROVIDER.softDeleteTopicMetasByTopicId(null, null, null, null, null);
+ assertTrue(sql.contains("AND schema_id = #{schemaId}"));
+ assertTrue(sql.contains("AND topic_name = #{topicName}"));
Assertions.assertTrue(sql.contains("AND current_version = #{currentVersion}"));
Assertions.assertTrue(sql.endsWith("AND deleted_at = 0"));
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestViewMetaBaseSQLProvider.java b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestViewMetaBaseSQLProvider.java
index 36fd8eca23..88e18ea114 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestViewMetaBaseSQLProvider.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestViewMetaBaseSQLProvider.java
@@ -18,6 +18,8 @@
*/
package org.apache.gravitino.storage.relational.mapper.provider.base;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -41,7 +43,9 @@ class TestViewMetaBaseSQLProvider {
@Test
void testDirectDeleteUsesVersionCas() {
- String sql = PROVIDER.softDeleteViewMetasByViewId(null, null);
+ String sql = PROVIDER.softDeleteViewMetasByViewId(null, null, null, null, null);
+ assertTrue(sql.contains("AND schema_id = #{schemaId}"));
+ assertTrue(sql.contains("AND view_name = #{viewName}"));
Assertions.assertTrue(sql.contains("AND current_version = #{currentVersion}"));
Assertions.assertTrue(sql.endsWith("AND deleted_at = 0"));
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestTableMetaPostgreSQLProvider.java b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestTableMetaPostgreSQLProvider.java
index f6c3492a7b..906affd828 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestTableMetaPostgreSQLProvider.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestTableMetaPostgreSQLProvider.java
@@ -18,6 +18,8 @@
*/
package org.apache.gravitino.storage.relational.mapper.provider.postgresql;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -48,7 +50,11 @@ class TestTableMetaPostgreSQLProvider {
@Test
void testDirectDeleteUsesVersionCas() {
- String sql = new TableMetaPostgreSQLProvider().softDeleteTableMetasByTableId(null, null);
+ String sql =
+ new TableMetaPostgreSQLProvider()
+ .softDeleteTableMetasByTableId(null, null, null, null, null);
+ assertTrue(sql.contains("AND schema_id = #{schemaId}"));
+ assertTrue(sql.contains("AND table_name = #{tableName}"));
Assertions.assertTrue(sql.contains("AND current_version = #{currentVersion}"));
Assertions.assertTrue(sql.endsWith("AND deleted_at = 0"));
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestTopicMetaPostgreSQLProvider.java b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestTopicMetaPostgreSQLProvider.java
index 10c5b44c31..66e19af41b 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestTopicMetaPostgreSQLProvider.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestTopicMetaPostgreSQLProvider.java
@@ -18,6 +18,8 @@
*/
package org.apache.gravitino.storage.relational.mapper.provider.postgresql;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -59,7 +61,9 @@ class TestTopicMetaPostgreSQLProvider {
@Test
void testDirectDeleteUsesVersionCas() {
- String sql = PROVIDER.softDeleteTopicMetasByTopicId(null, null);
+ String sql = PROVIDER.softDeleteTopicMetasByTopicId(null, null, null, null, null);
+ assertTrue(sql.contains("AND schema_id = #{schemaId}"));
+ assertTrue(sql.contains("AND topic_name = #{topicName}"));
Assertions.assertTrue(sql.contains("AND current_version = #{currentVersion}"));
Assertions.assertTrue(sql.endsWith("AND deleted_at = 0"));
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestViewMetaPostgreSQLProvider.java b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestViewMetaPostgreSQLProvider.java
index dc036ea419..80468ecfa5 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestViewMetaPostgreSQLProvider.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TestViewMetaPostgreSQLProvider.java
@@ -18,6 +18,8 @@
*/
package org.apache.gravitino.storage.relational.mapper.provider.postgresql;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -25,7 +27,10 @@ class TestViewMetaPostgreSQLProvider {
@Test
void testDirectDeleteUsesVersionCas() {
- String sql = new ViewMetaPostgreSQLProvider().softDeleteViewMetasByViewId(null, null);
+ String sql =
+ new ViewMetaPostgreSQLProvider().softDeleteViewMetasByViewId(null, null, null, null, null);
+ assertTrue(sql.contains("AND schema_id = #{schemaId}"));
+ assertTrue(sql.contains("AND view_name = #{viewName}"));
Assertions.assertTrue(sql.contains("AND current_version = #{currentVersion}"));
Assertions.assertTrue(sql.endsWith("AND deleted_at = 0"));
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestCatalogReregistration.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestCatalogReregistration.java
new file mode 100644
index 0000000000..beb81e3152
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestCatalogReregistration.java
@@ -0,0 +1,596 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.IntSupplier;
+import javax.annotation.Nullable;
+import org.apache.gravitino.Entity.EntityType;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.ColumnEntity;
+import org.apache.gravitino.meta.FilesetEntity;
+import org.apache.gravitino.meta.FunctionEntity;
+import org.apache.gravitino.meta.ModelEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.TagEntity;
+import org.apache.gravitino.meta.TopicEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.meta.ViewEntity;
+import org.apache.gravitino.rel.types.Types;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.TableColumnMapper;
+import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.TableVersionMapper;
+import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.ViewVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.TablePO;
+import org.apache.gravitino.storage.relational.po.TopicPO;
+import org.apache.gravitino.storage.relational.po.ViewPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.TestTemplate;
+
+/**
+ * Verifies identity reuse after catalog deletion without restoring or moving governance metadata.
+ */
+public class TestCatalogReregistration extends TestJDBCBackend {
+ private static final String METALAKE = "catalog_reregistration";
+
+ private long metalakeId;
+ private UserEntity owner;
+ private RoleEntity role;
+ private TagEntity tag;
+
+ @BeforeEach
+ void createGovernanceDefinitions() throws IOException {
+ metalakeId = createAndInsertMakeLake(METALAKE).id();
+ owner = createUserEntity(nextId(), NamespaceUtil.ofUser(METALAKE), "owner", AUDIT_INFO);
+ backend.insert(owner, false);
+ role =
+ RoleEntity.builder()
+ .withId(nextId())
+ .withName("role")
+ .withNamespace(NamespaceUtil.ofRole(METALAKE))
+ .withAuditInfo(AUDIT_INFO)
+ .withSecurableObjects(List.of())
+ .build();
+ backend.insert(role, false);
+ tag = createAndInsertTagEntity("governed", "tag definition", METALAKE);
+ }
+
+ @TestTemplate
+ void testCatalogReregistrationDoesNotRestoreGovernance() throws Exception {
+ Registration original = createRegistration("source", null, true);
+ Map<Long, String> originalObjects = new LinkedHashMap<>(original.objects());
+ addOtherGovernedObjects(original, originalObjects);
+ seedGovernance(originalObjects);
+ assertGovernance(originalObjects, 1);
+
+ backend.delete(original.catalog().nameIdentifier(), EntityType.CATALOG, true);
+ assertGovernance(originalObjects, 0);
+ Registration reimported = createRegistration("source", original, true);
+ assertGovernance(reimported.objects(), 0);
+ assertEquals(original.schema().id(), reimported.schema().id());
+ assertEquals(original.table().id(), reimported.table().id());
+ assertEquals(original.topic().id(), reimported.topic().id());
+ assertEquals(original.view().id(), reimported.view().id());
+
+ seedGovernance(reimported.objects());
+ assertGovernance(reimported.objects(), 1);
+ backend.delete(reimported.catalog().nameIdentifier(), EntityType.CATALOG, true);
+ assertGovernance(reimported.objects(), 0);
+ assertEquals(1, countLive("user_meta", "user_id", owner.id(), null, null));
+ assertEquals(1, countLive("role_meta", "role_id", role.id(), null, null));
+ assertEquals(1, countLive("tag_meta", "tag_id", tag.id(), null, null));
+ }
+
+ @TestTemplate
+ void testCatalogDropDoesNotDeleteGovernanceOfIdsReusedInAnotherCatalog() throws Exception {
+ Registration original = createRegistration("original", null, true);
+ backend.delete(original.schema().nameIdentifier(), EntityType.SCHEMA, true);
+ Registration current = createRegistration("current", original, true);
+ seedGovernance(current.objects());
+
+ backend.delete(original.catalog().nameIdentifier(), EntityType.CATALOG, true);
+ assertGovernance(current.objects(), 1);
+ assertLiveTableData(current.table().id());
+ assertEquals(1, countLive("view_version_info", "view_id", current.view().id(), null, null));
+ assertTrue(backend.exists(current.table().nameIdentifier(), EntityType.TABLE));
+ backend.delete(current.catalog().nameIdentifier(), EntityType.CATALOG, true);
+ assertGovernance(current.objects(), 0);
+ }
+
+ @TestTemplate
+ void testSchemaDropDoesNotDeleteGovernanceOfIdsReusedInAnotherSchema() throws Exception {
+ Registration original = createRegistration("original", null, true);
+ backend.delete(original.table().nameIdentifier(), EntityType.TABLE, false);
+ backend.delete(original.topic().nameIdentifier(), EntityType.TOPIC, false);
+ backend.delete(original.view().nameIdentifier(), EntityType.VIEW, false);
+ Registration current = createRegistration("current", original, false);
+ seedGovernance(current.objects());
+
+ backend.delete(original.schema().nameIdentifier(), EntityType.SCHEMA, true);
+ assertGovernance(current.objects(), 1);
+ assertLiveTableData(current.table().id());
+ assertEquals(1, countLive("view_version_info", "view_id", current.view().id(), null, null));
+ backend.delete(current.schema().nameIdentifier(), EntityType.SCHEMA, true);
+ Map<Long, String> children = new LinkedHashMap<>(current.objects());
+ children.remove(current.catalog().id());
+ assertGovernance(children, 0);
+ }
+
+ @TestTemplate
+ void testStaleDropsDoNotDeleteReregisteredEntitiesOrGovernance() throws Exception {
+ Registration original = createRegistration("source", null, true);
+ TablePO oldTable =
+ SessionUtils.getWithoutCommit(
+ TableMetaMapper.class,
+ mapper -> mapper.selectTableMetaByIdForUpdate(original.table().id()));
+ TopicPO oldTopic =
+ SessionUtils.getWithoutCommit(
+ TopicMetaMapper.class, mapper -> mapper.selectTopicMetaById(original.topic().id()));
+ ViewPO oldView =
+ ViewMetaService.getInstance().getViewPOByIdentifier(original.view().nameIdentifier());
+ backend.delete(original.catalog().nameIdentifier(), EntityType.CATALOG, true);
+ Registration current = createRegistration("source", original, true);
+ seedGovernance(current.objects());
+
+ assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ TableMetaService.getInstance()
+ .deleteTableWithVersion(original.table().nameIdentifier(), oldTable)));
+ assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ TopicMetaService.getInstance()
+ .deleteTopicWithVersion(original.topic().nameIdentifier(), oldTopic));
+ assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ ViewMetaService.getInstance()
+ .deleteViewWithVersion(original.view().nameIdentifier(), oldView));
+ assertGovernance(current.objects(), 1);
+ assertTrue(backend.exists(current.table().nameIdentifier(), EntityType.TABLE));
+ assertTrue(backend.exists(current.topic().nameIdentifier(), EntityType.TOPIC));
+ assertTrue(backend.exists(current.view().nameIdentifier(), EntityType.VIEW));
+ }
+
+ @TestTemplate
+ void testStaleDropsDoNotDeleteIdsReimportedAtAnotherPath() throws Exception {
+ for (boolean sameSchema : List.of(false, true)) {
+ Registration original = createRegistration("reimport_" + sameSchema, null, true);
+ TablePO oldTable =
+ SessionUtils.getWithoutCommit(
+ TableMetaMapper.class,
+ mapper -> mapper.selectTableMetaByIdForUpdate(original.table().id()));
+ TopicPO oldTopic =
+ SessionUtils.getWithoutCommit(
+ TopicMetaMapper.class, mapper -> mapper.selectTopicMetaById(original.topic().id()));
+ ViewPO oldView =
+ ViewMetaService.getInstance().getViewPOByIdentifier(original.view().nameIdentifier());
+ backend.delete(original.table().nameIdentifier(), EntityType.TABLE, false);
+ backend.delete(original.topic().nameIdentifier(), EntityType.TOPIC, false);
+ backend.delete(original.view().nameIdentifier(), EntityType.VIEW, false);
+
+ SchemaEntity schema = original.schema();
+ if (!sameSchema) {
+ schema =
+ createSchemaEntity(
+ nextId(), original.schema().namespace(), "replacement_schema", AUDIT_INFO);
+ backend.insert(schema, false);
+ }
+ Namespace namespace = Namespace.of(METALAKE, original.catalog().name(), schema.name());
+ String suffix = sameSchema ? "_replacement" : "";
+ TableEntity table =
+ TableEntity.builder()
+ .withId(original.table().id())
+ .withName("table" + suffix)
+ .withNamespace(namespace)
+ .withColumns(List.of(original.column()))
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ TopicEntity topic =
+ createTopicEntity(original.topic().id(), namespace, "topic" + suffix, AUDIT_INFO);
+ ViewEntity view = createViewEntity(original.view().id(), namespace, "view" + suffix);
+ backend.insert(table, false);
+ backend.insert(topic, false);
+ backend.insert(view, false);
+ Map<Long, String> objects =
+ Map.of(
+ table.id(), "TABLE",
+ original.column().id(), "COLUMN",
+ topic.id(), "TOPIC",
+ view.id(), "VIEW");
+ seedGovernance(objects);
+
+ assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ TableMetaService.getInstance()
+ .deleteTableWithVersion(original.table().nameIdentifier(), oldTable)));
+ assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ TopicMetaService.getInstance()
+ .deleteTopicWithVersion(original.topic().nameIdentifier(), oldTopic));
+ assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ ViewMetaService.getInstance()
+ .deleteViewWithVersion(original.view().nameIdentifier(), oldView));
+ assertGovernance(objects, 1);
+ assertLiveTableData(table.id());
+ assertEquals(1, countLive("view_version_info", "view_id", view.id(), null, null));
+ assertTrue(backend.exists(table.nameIdentifier(), EntityType.TABLE));
+ assertTrue(backend.exists(topic.nameIdentifier(), EntityType.TOPIC));
+ assertTrue(backend.exists(view.nameIdentifier(), EntityType.VIEW));
+ }
+ }
+
+ @TestTemplate
+ void testStaleSchemaAlterDoesNotUpdateReregisteredSchema() throws Exception {
+ Registration original = createRegistration("source", null, true);
+ AtomicReference<Registration> replacement = new AtomicReference<>();
+ assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ SchemaMetaService.getInstance()
+ .updateSchema(
+ original.schema().nameIdentifier(),
+ entity -> {
+ Registration current =
+ assertDoesNotThrow(
+ () -> {
+ backend.delete(
+ original.catalog().nameIdentifier(), EntityType.CATALOG, true);
+ Registration registered =
+ createRegistration("source", original, true);
+ seedGovernance(registered.objects());
+ return registered;
+ });
+ replacement.set(current);
+ return entity;
+ }));
+ assertGovernance(replacement.get().objects(), 1);
+ assertTrue(backend.exists(replacement.get().schema().nameIdentifier(), EntityType.SCHEMA));
+ }
+
+ @TestTemplate
+ void testMetalakeDropKeepsVersionsOfIdsReusedInAnotherMetalake() throws Exception {
+ Registration original = createRegistration("original", null, true);
+ backend.delete(original.schema().nameIdentifier(), EntityType.SCHEMA, true);
+ String otherMetalake = "other_metalake";
+ createAndInsertMakeLake(otherMetalake);
+ createAndInsertCatalog(otherMetalake, "current");
+ SchemaEntity schema =
+ createSchemaEntity(
+ original.schema().id(), Namespace.of(otherMetalake, "current"), "schema", AUDIT_INFO);
+ backend.insert(schema, false);
+ TableEntity table =
+ TableEntity.builder()
+ .withId(original.table().id())
+ .withName("table")
+ .withNamespace(Namespace.of(otherMetalake, "current", schema.name()))
+ .withColumns(List.of(original.column()))
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ backend.insert(table, false);
+ ViewEntity view = createViewEntity(original.view().id(), table.namespace(), "view");
+ backend.insert(view, false);
+
+ backend.delete(NameIdentifier.of(METALAKE), EntityType.METALAKE, true);
+ assertTrue(backend.exists(table.nameIdentifier(), EntityType.TABLE));
+ assertLiveTableData(table.id());
+ assertEquals(1, countLive("view_version_info", "view_id", view.id(), null, null));
+ }
+
+ @TestTemplate
+ void testLegacyGcPreservesActiveRegistrationsAndTheirChildren() throws Exception {
+ Registration current = createRegistration("source", null, true);
+ for (int generation = 0; generation < 2; generation++) {
+ backend.delete(current.catalog().nameIdentifier(), EntityType.CATALOG, true);
+ current = createRegistration("source", current, true);
+ }
+ seedGovernance(current.objects());
+ Map<String, Long> activeIds =
+ Map.of(
+ "schema",
+ current.schema().id(),
+ "table",
+ current.table().id(),
+ "topic",
+ current.topic().id(),
+ "view",
+ current.view().id());
+ Map<String, IntSupplier> rootGc =
+ Map.of(
+ "schema",
+ () ->
+ SessionUtils.doWithCommitAndFetchResult(
+ SchemaMetaMapper.class,
+ mapper -> mapper.deleteSchemaMetasByLegacyTimeline(Long.MAX_VALUE, 1)),
+ "table",
+ () ->
+ SessionUtils.doWithCommitAndFetchResult(
+ TableMetaMapper.class,
+ mapper -> mapper.deleteTableMetasByLegacyTimeline(Long.MAX_VALUE, 1)),
+ "topic",
+ () ->
+ SessionUtils.doWithCommitAndFetchResult(
+ TopicMetaMapper.class,
+ mapper -> mapper.deleteTopicMetasByLegacyTimeline(Long.MAX_VALUE, 1)),
+ "view",
+ () ->
+ SessionUtils.doWithCommitAndFetchResult(
+ ViewMetaMapper.class,
+ mapper -> mapper.deleteViewMetasByLegacyTimeline(Long.MAX_VALUE, 1)));
+ for (Map.Entry<String, IntSupplier> gc : rootGc.entrySet()) {
+ assertEquals(1, gc.getValue().getAsInt(), gc.getKey() + " first GC batch");
+ assertEquals(1, gc.getValue().getAsInt(), gc.getKey() + " second GC batch");
+ assertEquals(0, gc.getValue().getAsInt(), gc.getKey() + " exhausted history");
+ assertEquals(
+ 1,
+ countLive(
+ gc.getKey() + "_meta", gc.getKey() + "_id", activeIds.get(gc.getKey()), null, null));
+ }
+ for (int generation = 0; generation < 2; generation++) {
+ assertEquals(
+ 1,
+ SessionUtils.doWithCommitAndFetchResult(
+ TableVersionMapper.class,
+ mapper -> mapper.deleteTableVersionByLegacyTimeline(Long.MAX_VALUE, 1))
+ .intValue());
+ assertEquals(
+ 1,
+ SessionUtils.doWithCommitAndFetchResult(
+ TableColumnMapper.class,
+ mapper -> mapper.deleteColumnPOsByLegacyTimeline(Long.MAX_VALUE, 1))
+ .intValue());
+ assertEquals(
+ 1,
+ SessionUtils.doWithCommitAndFetchResult(
+ ViewVersionInfoMapper.class,
+ mapper -> mapper.deleteViewVersionsByLegacyTimeline(Long.MAX_VALUE, 1))
+ .intValue());
+ }
+ assertGovernance(current.objects(), 1);
+ assertLiveTableData(current.table().id());
+ assertTrue(backend.exists(current.schema().nameIdentifier(), EntityType.SCHEMA));
+ assertTrue(backend.exists(current.table().nameIdentifier(), EntityType.TABLE));
+ assertTrue(backend.exists(current.topic().nameIdentifier(), EntityType.TOPIC));
+ assertTrue(backend.exists(current.view().nameIdentifier(), EntityType.VIEW));
+ assertEquals(1, countLive("view_version_info", "view_id", current.view().id(), null, null));
+ }
+
+ private Registration createRegistration(
+ String name, @Nullable Registration previous, boolean reuseSchemaId) throws IOException {
+ CatalogEntity catalog = createAndInsertCatalog(METALAKE, name);
+ Namespace schemaNamespace = Namespace.of(METALAKE, name);
+ SchemaEntity schema =
+ createSchemaEntity(
+ previous != null && reuseSchemaId ? previous.schema().id() : nextId(),
+ schemaNamespace,
+ "schema",
+ AUDIT_INFO);
+ backend.insert(schema, false);
+ Namespace namespace = Namespace.of(METALAKE, name, schema.name());
+ ColumnEntity column =
+ ColumnEntity.builder()
+ .withId(previous == null ? nextId() : previous.column().id())
+ .withName("column")
+ .withPosition(0)
+ .withDataType(Types.IntegerType.get())
+ .withNullable(false)
+ .withAutoIncrement(false)
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ TableEntity table =
+ TableEntity.builder()
+ .withId(previous == null ? nextId() : previous.table().id())
+ .withName("table")
+ .withNamespace(namespace)
+ .withColumns(List.of(column))
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ TopicEntity topic =
+ createTopicEntity(
+ previous == null ? nextId() : previous.topic().id(), namespace, "topic", AUDIT_INFO);
+ ViewEntity view =
+ createViewEntity(previous == null ? nextId() : previous.view().id(), namespace, "view");
+ backend.insert(table, false);
+ backend.insert(topic, false);
+ backend.insert(view, false);
+ return new Registration(catalog, schema, table, column, topic, view);
+ }
+
+ private void addOtherGovernedObjects(Registration registration, Map<Long, String> objects)
+ throws IOException {
+ Namespace namespace = registration.table().namespace();
+ FilesetEntity fileset = createFilesetEntity(nextId(), namespace, "fileset", AUDIT_INFO);
+ ModelEntity model =
+ createModelEntity(nextId(), namespace, "model", "comment", 1, null, AUDIT_INFO);
+ FunctionEntity function = createFunctionEntity(nextId(), namespace, "function", AUDIT_INFO);
+ SemanticModelEntity semantic =
+ SemanticModelEntity.builder()
+ .withId(nextId())
+ .withName("semantic")
+ .withNamespace(namespace)
+ .withAuditInfo(AUDIT_INFO)
+ .withDefinition(
+ SemanticModelDefinition.builder()
+ .withDatasets(
+ new Dataset[] {
+ Dataset.builder()
+ .withName("source")
+ .withSource(NameIdentifier.of("source", "schema", "table"))
+ .build()
+ })
+ .build())
+ .build();
+ backend.insert(fileset, false);
+ backend.insert(model, false);
+ backend.insert(function, false);
+ backend.insert(semantic, false);
+ objects.put(fileset.id(), "FILESET");
+ objects.put(model.id(), "MODEL");
+ objects.put(function.id(), "FUNCTION");
+ objects.put(semantic.id(), "SEMANTIC_MODEL");
+ }
+
+ private void seedGovernance(Map<Long, String> objects) throws SQLException {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = session.getConnection();
+ Statement statement = connection.createStatement()) {
+ for (Map.Entry<Long, String> object : objects.entrySet()) {
+ long id = object.getKey();
+ String type = object.getValue();
+ statement.executeUpdate(
+ String.format(
+ "INSERT INTO owner_meta (metalake_id, owner_id, owner_type, metadata_object_id, metadata_object_type, audit_info) VALUES (%d, %d, 'USER', %d, '%s', '{}')",
+ metalakeId, owner.id(), id, type));
+ statement.executeUpdate(
+ String.format(
+ "INSERT INTO role_meta_securable_object (role_id, metadata_object_id, type, privilege_names, privilege_conditions) VALUES (%d, %d, '%s', '[]', '[]')",
+ role.id(), id, type));
+ statement.executeUpdate(
+ String.format(
+ "INSERT INTO tag_relation_meta (tag_id, metadata_object_id, metadata_object_type, audit_info) VALUES (%d, %d, '%s', '{}')",
+ tag.id(), id, type));
+ statement.executeUpdate(
+ String.format(
+ "INSERT INTO statistic_meta (statistic_id, statistic_name, metalake_id, statistic_value, metadata_object_id, metadata_object_type, audit_info) VALUES (%d, 'row_count', %d, '{}', %d, '%s', '{}')",
+ nextId(), metalakeId, id, type));
+ }
+ }
+ }
+
+ private void assertLiveTableData(long tableId) throws SQLException {
+ assertEquals(
+ 1,
+ countLive("table_version_info", "table_id", tableId, null, null),
+ "The active table version must survive cleanup of a previous registration");
+ assertEquals(
+ 1,
+ countLive("table_column_version_info", "table_id", tableId, null, null),
+ "The active table columns must survive cleanup of a previous registration");
+ }
+
+ private void assertGovernance(Map<Long, String> objects, int expected) throws SQLException {
+ for (Map.Entry<Long, String> object : objects.entrySet()) {
+ for (String table :
+ List.of(
+ "owner_meta", "role_meta_securable_object", "tag_relation_meta", "statistic_meta")) {
+ String typeColumn =
+ table.equals("role_meta_securable_object") ? "type" : "metadata_object_type";
+ assertEquals(
+ expected,
+ countLive(table, "metadata_object_id", object.getKey(), typeColumn, object.getValue()),
+ table + " for " + object.getValue() + " " + object.getKey());
+ }
+ }
+ }
+
+ private int countLive(
+ String table, String idColumn, long id, @Nullable String typeColumn, @Nullable String type)
+ throws SQLException {
+ String sql =
+ "SELECT COUNT(*) FROM "
+ + table
+ + " WHERE "
+ + idColumn
+ + " = ? AND deleted_at = 0"
+ + (typeColumn == null ? "" : " AND " + typeColumn + " = ?");
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = session.getConnection();
+ PreparedStatement statement = connection.prepareStatement(sql)) {
+ statement.setLong(1, id);
+ if (typeColumn != null) {
+ statement.setString(2, type);
+ }
+ try (ResultSet result = statement.executeQuery()) {
+ assertTrue(result.next());
+ return result.getInt(1);
+ }
+ }
+ }
+
+ private static long nextId() {
+ return RandomIdGenerator.INSTANCE.nextId();
+ }
+
+ @SuppressWarnings("UnusedVariable") // Error Prone does not recognize record component accessors.
+ private record Registration(
+ CatalogEntity catalog,
+ SchemaEntity schema,
+ TableEntity table,
+ ColumnEntity column,
+ TopicEntity topic,
+ ViewEntity view) {
+ private Map<Long, String> objects() {
+ return Map.of(
+ catalog.id(),
+ "CATALOG",
+ schema.id(),
+ "SCHEMA",
+ table.id(),
+ "TABLE",
+ column.id(),
+ "COLUMN",
+ topic.id(),
+ "TOPIC",
+ view.id(),
+ "VIEW");
+ }
+ }
+}
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 506973a73d..eda6ae46ad 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
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.storage.relational.service;
+import static org.apache.gravitino.storage.relational.utils.ExceptionUtils.hasSqlException;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -47,6 +48,7 @@ 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.exception.ExceptionUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityAlreadyExistsException;
@@ -83,7 +85,6 @@ 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;
@@ -91,7 +92,6 @@ 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;
@@ -206,7 +206,7 @@ public class TestSchemaMetaService extends TestJDBCBackend {
}
@TestTemplate
- void testConcurrentRevivalOfRetiredSchemaIdKeepsOneOwner() throws Exception {
+ void testConcurrentImportsOfRetiredSchemaIdKeepOneOwner() throws Exception {
createAndInsertMakeLake(metalakeName);
createAndInsertCatalog(metalakeName, catalogName);
createAndInsertCatalog(metalakeName, "first_revival_catalog");
@@ -230,30 +230,23 @@ public class TestSchemaMetaService extends TestJDBCBackend {
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();
- }
+ firstResult = executor.submit(() -> importSchemaAfterBarrier(first, lockingReadsStarted));
+ secondResult = executor.submit(() -> importSchemaAfterBarrier(second, lockingReadsStarted));
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);
+ Throwable losingFailure = firstFailure == null ? secondFailure : firstFailure;
+ if (!hasSqlException(losingFailure, Collections.emptySet(), Set.of(1213))) {
+ Assertions.assertInstanceOf(
+ EntityAlreadyExistsException.class,
+ losingFailure,
+ () -> ExceptionUtils.getStackTrace(losingFailure));
+ }
SchemaEntity winner = firstFailure == null ? first : second;
SchemaEntity loser = firstFailure == null ? second : first;
+ // MySQL can roll back the competing insert as a deadlock victim (error 1213). Both
+ // transactions have now finished, so retrying the loser must report the existing ID.
+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(loser, false));
Assertions.assertEquals(
retired.id(),
backend.<SchemaEntity>get(winner.nameIdentifier(), Entity.EntityType.SCHEMA).id());
@@ -545,6 +538,45 @@ public class TestSchemaMetaService extends TestJDBCBackend {
assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(schemaCopy, false));
}
+ @TestTemplate
+ void testCatalogReregistrationReimportsExternalIdentifiers() throws IOException {
+ createAndInsertMakeLake(metalakeName);
+ createAndInsertCatalog(metalakeName, catalogName);
+ SchemaEntity schema = createAndInsertSchema(metalakeName, catalogName, "schema_reregister");
+ Namespace namespace = NamespaceUtil.ofTable(metalakeName, catalogName, schema.name());
+ TableEntity table = createAndInsertTableEntity(namespace, "table_reregister");
+ ViewEntity view =
+ createViewEntity(RandomIdGenerator.INSTANCE.nextId(), namespace, "view_reregister");
+ TopicEntity topic =
+ createTopicEntity(
+ RandomIdGenerator.INSTANCE.nextId(), namespace, "topic_reregister", AUDIT_INFO);
+ backend.insert(view, false);
+ backend.insert(topic, false);
+ for (int attempt = 0; attempt < 3; attempt++) {
+ backend.delete(NameIdentifier.of(metalakeName, catalogName), Entity.EntityType.CATALOG, true);
+ createAndInsertCatalog(metalakeName, catalogName);
+ backend.insert(schema, false);
+ backend.insert(table, false);
+ backend.insert(view, false);
+ backend.insert(topic, false);
+ Assertions.assertEquals(
+ schema.id(),
+ backend.<SchemaEntity>get(schema.nameIdentifier(), Entity.EntityType.SCHEMA).id());
+ Assertions.assertEquals(
+ table.id(),
+ backend.<TableEntity>get(table.nameIdentifier(), Entity.EntityType.TABLE).id());
+ Assertions.assertEquals(
+ view.id(), backend.<ViewEntity>get(view.nameIdentifier(), Entity.EntityType.VIEW).id());
+ Assertions.assertEquals(
+ topic.id(),
+ backend.<TopicEntity>get(topic.nameIdentifier(), Entity.EntityType.TOPIC).id());
+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(schema, false));
+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(table, false));
+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(view, false));
+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(topic, false));
+ }
+ }
+
@TestTemplate
public void testInsertSchemaLocksCatalogWithoutChangingVersion() throws IOException {
createAndInsertMakeLake(metalakeName);
@@ -2679,32 +2711,11 @@ public class TestSchemaMetaService extends TestJDBCBackend {
}
@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);
+ private Throwable importSchemaAfterBarrier(SchemaEntity schema, CountDownLatch writersStarted) {
+ try {
+ writersStarted.countDown();
+ assertTrue(writersStarted.await(30, TimeUnit.SECONDS));
+ backend.insert(schema, false);
return null;
} catch (Throwable failure) {
return failure;
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTopicMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTopicMetaService.java
index 45c6c97313..caf7e78fc2 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTopicMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTopicMetaService.java
@@ -90,6 +90,23 @@ public class TestTopicMetaService extends TestJDBCBackend {
assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(topicCopy, false));
}
+ @TestTemplate
+ void testReregisteredCatalogImportsTopicWithoutOverwritingHistory() throws IOException {
+ TopicEntity topic = createTopic("topic_reregistered", "original");
+ backend.insert(topic, false);
+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(topic, false));
+
+ backend.delete(NameIdentifier.of(metalakeName, catalogName), Entity.EntityType.CATALOG, true);
+ createAndInsertCatalog(metalakeName, catalogName);
+ createAndInsertSchema(metalakeName, catalogName, schemaName);
+ TopicEntity replacement = copyTopic(topic, topic.name(), "new registration");
+ backend.insert(replacement, false);
+ Assertions.assertEquals(
+ "new registration",
+ TopicMetaService.getInstance().getTopicByIdentifier(topic.nameIdentifier()).comment());
+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(replacement, false));
+ }
+
@TestTemplate
public void testInsertWaitsForConcurrentSchemaDelete() throws Exception {
SchemaPO observedSchemaPO =
diff --git a/docs/apache-hive-catalog.md b/docs/apache-hive-catalog.md
index 7ce0da6265..d26597f8d6 100644
--- a/docs/apache-hive-catalog.md
+++ b/docs/apache-hive-catalog.md
@@ -78,6 +78,27 @@ When using Gravitino with Spark, pass the Spark Hive connector configuration usi
When using Gravitino authorization for Hive with Apache Ranger, see the [Authorization Hive with Ranger properties](security/authorization-pushdown.md#configure-the-ranger-hadoop-sql-plugin)
+### Identifier Case Behavior
+
+Schema, table, and view identifiers are case-insensitive; you can use any casing. Column identifiers
+remain case-sensitive.
+
+:::caution
+After upgrading, if loading an existing mixed-case object reports a retained identifier conflict,
+Gravitino does not support metadata-only unregister of an individual external object. Use this
+catalog-wide recovery procedure:
+
+1. Have an administrator [force-drop the Gravitino catalog](./manage-catalogs-and-schemas.md#drop-a-catalog).
+ This deletes every Gravitino registration and its privileges, tags, and other relationships in
+ the catalog. It does not drop the Hive Metastore databases, tables, views, or physical data.
+2. Recreate the Gravitino catalog and load the objects again. Keep the existing
+ `gravitino.identifier` properties; deleted registrations do not block new imports.
+3. Reapply any privileges, tags, or other governance relationships that the new registrations need.
+
+A source identifier can have only one active Gravitino registration. Coordinate with other
+Gravitino catalogs that share the external source before resetting a catalog.
+:::
+
### Catalog Operations
Refer to [Manage Catalogs and Schemas](./manage-catalogs-and-schemas.md#catalog-operations) for more details.
diff --git a/docs/lakehouse-hudi-catalog.md b/docs/lakehouse-hudi-catalog.md
index c40c0e905c..291f3a0f91 100644
--- a/docs/lakehouse-hudi-catalog.md
+++ b/docs/lakehouse-hudi-catalog.md
@@ -55,6 +55,26 @@ Users can use the following properties to configure the security of the catalog
Property name with this prefix passed down to the underlying backend client for use. Such as `gravitino.bypass.hive.metastore.kerberos.principal=XXXX`、`gravitino.bypass.hadoop.security.authentication=kerberos`、`gravitino.bypass.hive.metastore.sasl.enabled=ture` And so on.
+#### Identifier Case Behavior
+
+Schema and table identifiers are case-insensitive; you can use any casing. Column identifiers remain
+case-sensitive.
+
+:::caution
+After upgrading, if loading an existing mixed-case object reports a retained identifier conflict,
+Gravitino does not support metadata-only unregister of an individual external object. Use this
+catalog-wide recovery procedure:
+
+1. Have an administrator [force-drop the Gravitino catalog](./manage-catalogs-and-schemas.md#drop-a-catalog).
+ This deletes every Gravitino registration and its privileges, tags, and other relationships in
+ the catalog. It does not drop the Hudi schemas, tables, or physical data in the Hive Metastore.
+2. Recreate the Gravitino catalog and load the objects again. Keep the existing
+ `gravitino.identifier` properties; deleted registrations do not block new imports.
+3. Reapply any privileges, tags, or other governance relationships that the new registrations need.
+
+A source identifier can have only one active Gravitino registration. Coordinate with other
+Gravitino catalogs that share the external source before resetting a catalog.
+:::
### Catalog Operations
diff --git a/docs/lakehouse-iceberg-catalog.md b/docs/lakehouse-iceberg-catalog.md
index 5e7a610bbf..33daff931c 100644
--- a/docs/lakehouse-iceberg-catalog.md
+++ b/docs/lakehouse-iceberg-catalog.md
@@ -57,6 +57,27 @@ If you are using the Gravitino with Trino, you can pass the Trino Iceberg connec
If you are using the Gravitino with Spark, you can pass the Spark Iceberg connector configuration using prefix `spark.bypass.`. For example, using `spark.bypass.io-impl` to pass the `io-impl` to the Spark Iceberg connector in Spark runtime.
+#### Identifier Case Behavior
+
+For `catalog-backend=hive`, schema, table, and view identifiers are case-insensitive; you can use any casing.
+
+For `catalog-backend=rest`, always use the same identifier casing that was used when the object was first registered. Loading the same object with different casing is rejected.
+
+:::caution
+After upgrading, if loading an existing mixed-case object reports a retained identifier conflict,
+Gravitino does not support metadata-only unregister of an individual external object. Use this
+catalog-wide recovery procedure:
+
+1. Have an administrator [force-drop the Gravitino catalog](./manage-catalogs-and-schemas.md#drop-a-catalog).
+ This deletes every Gravitino registration and its privileges, tags, and other relationships in
+ the catalog. It does not drop the Iceberg namespaces, tables, views, or physical data.
+2. Recreate the Gravitino catalog and load the objects again. Keep the existing
+ `gravitino.identifier` properties; deleted registrations do not block new imports.
+3. Reapply any privileges, tags, or other governance relationships that the new registrations need.
+
+A source identifier can have only one active Gravitino registration. Coordinate with other
+Gravitino catalogs that share the external source before resetting a catalog.
+:::
#### JDBC Backend
diff --git a/docs/lakehouse-paimon-catalog.md b/docs/lakehouse-paimon-catalog.md
index fd7fee8cac..0b7c9f9fb0 100644
--- a/docs/lakehouse-paimon-catalog.md
+++ b/docs/lakehouse-paimon-catalog.md
@@ -80,6 +80,28 @@ connect to Aliyun DLF, more information can be found in the [Paimon REST Catalog
Any properties not defined by Gravitino with `gravitino.bypass.` prefix will pass to Paimon catalog properties and HDFS configuration. For example, if specify `gravitino.bypass.table.type`, `table.type` will pass to Paimon catalog properties.
+#### Identifier Case Behavior
+
+For `catalog-backend=hive`, schema, table, and view identifiers are case-insensitive; you can use any casing.
+
+For `catalog-backend=rest`, always use the same identifier casing that was used when the object was first registered. Loading the same object with different casing is rejected.
+
+:::caution
+After upgrading, if loading an existing mixed-case object reports a retained identifier conflict,
+Gravitino does not support metadata-only unregister of an individual external object. Use this
+catalog-wide recovery procedure:
+
+1. Have an administrator [force-drop the Gravitino catalog](./manage-catalogs-and-schemas.md#drop-a-catalog).
+ This deletes every Gravitino registration and its privileges, tags, and other relationships in
+ the catalog. It does not drop the Paimon databases, tables, views, or physical data.
+2. Recreate the Gravitino catalog and load the objects again. Keep the existing
+ `gravitino.identifier` properties; deleted registrations do not block new imports.
+3. Reapply any privileges, tags, or other governance relationships that the new registrations need.
+
+A source identifier can have only one active Gravitino registration. Coordinate with other
+Gravitino catalogs that share the external source before resetting a catalog.
+:::
+
#### Hadoop S3A (optional)
Paimon's native S3 filesystem uses an `s3://` warehouse and the `paimon-s3` dependency. As an
diff --git a/docs/manage-catalogs-and-schemas.md b/docs/manage-catalogs-and-schemas.md
index 09730c0eb3..9dd8fbb237 100644
--- a/docs/manage-catalogs-and-schemas.md
+++ b/docs/manage-catalogs-and-schemas.md
@@ -318,12 +318,16 @@ creation. External schema creation now checks the entity store before calling th
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.
+renamed. Loading a renamed schema within the same catalog preserves its registered identity only
+after confirming that the old source path no longer exists. If the old path still exists, the
+copied identifier is rejected; imports cannot move an identity from another catalog.
+Gravitino does not support metadata-only unregister of an individual external schema.
+Follow the catalog-specific recovery guidance before resetting a catalog;
+catalog re-registration clears all of its stored registrations and governance associations, which
+must be reapplied as described in the [migration guide](./migration-guide.md#external-catalog-re-registration).
+Conflicting registrations are never automatically cascade-deleted by an overwrite. 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/migration-guide.md b/docs/migration-guide.md
index 3f24482b98..c499c61307 100644
--- a/docs/migration-guide.md
+++ b/docs/migration-guide.md
@@ -11,6 +11,35 @@ existing deployments. For database backup, schema scripts, and rollback commands
## Upgrading from Gravitino 1.3 to 2.0
+### External catalog re-registration
+
+Apply the 1.3.0-to-2.0.0 database upgrade before starting the new server. The upgrade changes
+schema, table, topic, and view primary keys to `(entity_id, deleted_at)`, allowing deleted
+registrations and a new active registration to retain the same external identifier.
+Each external identifier can have only one active registration; importing it through another
+catalog or schema is rejected.
+
+Earlier 2.0.0 snapshots with identifier-only primary keys also require these primary-key changes.
+Apply the updated 1.3.0-to-2.0.0 upgrade script using the backup and shutdown procedure below;
+the existing 2.0.0 version label does not mean the database already has composite primary keys.
+
+Table and view imports do not automatically move registrations after an external rename.
+Schema imports retain the existing same-catalog rename handling: a registration can move only
+after confirming that its old source path no longer exists. An ID active in another catalog
+cannot be moved by an import. There is no per-object metadata-only unregister API; recovery from
+unresolved identity conflicts requires catalog re-registration as described below.
+
+Dropping a catalog clears owner, privilege, tag, and statistic associations for the catalog
+and its descendants. The upgrade also soft-deletes orphaned associations for retained schema,
+table, topic, and view IDs that have no active registration. Associations for IDs with an
+active registration are preserved. Metalake-level user, role, tag, and policy definitions
+are retained.
+
+After dropping and recreating an external catalog, its objects can be imported again without
+removing their external identifiers. Their deleted governance associations are not restored;
+explicitly reapply the associations needed by the new registration. Follow the database backup
+and shutdown steps in [Upgrade Gravitino](./how-to-upgrade.md) before applying the migration.
+
### Domains
- Domains add business groupings within a metalake, backed by explicit tag bindings. Existing tags
diff --git a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/integration/test/jdbc/FlinkJdbcMysqlCatalogIT.java b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/integration/test/jdbc/FlinkJdbcMysqlCatalogIT.java
index d265bffe23..089c64ebe4 100644
--- a/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/integration/test/jdbc/FlinkJdbcMysqlCatalogIT.java
+++ b/flink-connector/flink-common/src/test/java/org/apache/gravitino/flink/connector/integration/test/jdbc/FlinkJdbcMysqlCatalogIT.java
@@ -23,9 +23,13 @@ import static org.apache.gravitino.integration.test.util.TestDatabaseName.MYSQL_
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.Statement;
import java.util.Map;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.types.Row;
+import org.apache.flink.util.CloseableIterator;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.credential.CredentialConstants;
@@ -206,9 +210,14 @@ public abstract class FlinkJdbcMysqlCatalogIT extends FlinkCommonIT {
try {
catalog.asSchemas().createSchema(schemaName, null, ImmutableMap.of());
tableEnv.useCatalog(CATALOG_NAME);
- tableEnv.useDatabase(schemaName);
- tableEnv.executeSql("CREATE TABLE " + tableName + " (id INT)");
- tableEnv.executeSql("INSERT INTO " + tableName + " VALUES (1)");
+ // Prepare an external table without registering its ID under a different Gravitino catalog.
+ try (Connection connection =
+ DriverManager.getConnection(mysqlUrl, mysqlUsername, mysqlPassword);
+ Statement statement = connection.createStatement()) {
+ String mysqlTableName = schemaName + "." + tableName;
+ statement.execute("CREATE TABLE " + mysqlTableName + " (id INT)");
+ statement.executeUpdate("INSERT INTO " + mysqlTableName + " VALUES (1)");
+ }
catalogWithoutDefaultDatabase =
metalake.createCatalog(
@@ -226,12 +235,13 @@ public abstract class FlinkJdbcMysqlCatalogIT extends FlinkCommonIT {
JdbcPropertiesConstants.GRAVITINO_JDBC_DRIVER,
mysqlDriver));
- Assertions.assertEquals(
- Row.of(1),
+ try (CloseableIterator<Row> rows =
tableEnv
.executeSql("SELECT * FROM " + catalogName + "." + schemaName + "." + tableName)
- .collect()
- .next());
+ .collect()) {
+ Assertions.assertEquals(Row.of(1), rows.next());
+ Assertions.assertFalse(rows.hasNext());
+ }
} finally {
if (catalogWithoutDefaultDatabase != null) {
metalake.dropCatalog(catalogName, true);
diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sql
index 41a8136a13..cdc64526bf 100644
--- a/scripts/h2/schema-2.0.0-h2.sql
+++ b/scripts/h2/schema-2.0.0-h2.sql
@@ -60,7 +60,7 @@ CREATE TABLE IF NOT EXISTS `schema_meta` (
`current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'schema current version',
`last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'schema last version',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'schema deleted at',
- PRIMARY KEY (schema_id),
+ PRIMARY KEY (schema_id, deleted_at),
CONSTRAINT uk_cid_sn_del UNIQUE (catalog_id, schema_name, deleted_at),
-- Aliases are used here, and indexes with the same name in H2 can only be created once.
KEY idx_smid (metalake_id)
@@ -76,7 +76,7 @@ CREATE TABLE IF NOT EXISTS `table_meta` (
`current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'table current version',
`last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'table last version',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'table deleted at',
- PRIMARY KEY (table_id),
+ PRIMARY KEY (table_id, deleted_at),
CONSTRAINT uk_sid_tn_del UNIQUE (schema_id, table_name, deleted_at),
-- Aliases are used here, and indexes with the same name in H2 can only be created once.
KEY idx_tmid (metalake_id),
@@ -161,7 +161,7 @@ CREATE TABLE IF NOT EXISTS `topic_meta` (
`current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'topic current version',
`last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'topic last version',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'topic deleted at',
- PRIMARY KEY (topic_id),
+ PRIMARY KEY (topic_id, deleted_at),
CONSTRAINT uk_cid_tn_del UNIQUE (schema_id, topic_name, deleted_at),
-- Aliases are used here, and indexes with the same name in H2 can only be created once.
KEY idx_tvmid (metalake_id),
@@ -545,7 +545,7 @@ CREATE TABLE IF NOT EXISTS `view_meta` (
`current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'view current version',
`last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'view last version',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'view deleted at',
- PRIMARY KEY (`view_id`),
+ PRIMARY KEY (view_id, deleted_at),
UNIQUE KEY `uk_sid_vn_del` (`schema_id`, `view_name`, `deleted_at`),
KEY `idx_vemid` (`metalake_id`),
KEY `idx_vecid` (`catalog_id`)
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 919ec1da96..bedb91a308 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
@@ -18,6 +18,33 @@
--
+-- Preserve retired registrations while keeping each external ID unique among active rows.
+EXECUTE IMMEDIATE 'ALTER TABLE `schema_meta` DROP CONSTRAINT IF EXISTS "' ||
+ COALESCE((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
+ WHERE TABLE_SCHEMA = CURRENT_SCHEMA AND UPPER(TABLE_NAME) = UPPER('schema_meta')
+ AND CONSTRAINT_TYPE = 'PRIMARY KEY'), 'schema_meta_pkey') || '"';
+ALTER TABLE `schema_meta` ADD PRIMARY KEY (`schema_id`, `deleted_at`);
+
+EXECUTE IMMEDIATE 'ALTER TABLE `table_meta` DROP CONSTRAINT IF EXISTS "' ||
+ COALESCE((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
+ WHERE TABLE_SCHEMA = CURRENT_SCHEMA AND UPPER(TABLE_NAME) = UPPER('table_meta')
+ AND CONSTRAINT_TYPE = 'PRIMARY KEY'), 'table_meta_pkey') || '"';
+ALTER TABLE `table_meta` ADD PRIMARY KEY (`table_id`, `deleted_at`);
+
+EXECUTE IMMEDIATE 'ALTER TABLE `topic_meta` DROP CONSTRAINT IF EXISTS "' ||
+ COALESCE((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
+ WHERE TABLE_SCHEMA = CURRENT_SCHEMA AND UPPER(TABLE_NAME) = UPPER('topic_meta')
+ AND CONSTRAINT_TYPE = 'PRIMARY KEY'), 'topic_meta_pkey') || '"';
+ALTER TABLE `topic_meta` ADD PRIMARY KEY (`topic_id`, `deleted_at`);
+
+EXECUTE IMMEDIATE 'ALTER TABLE `view_meta` DROP CONSTRAINT IF EXISTS "' ||
+ COALESCE((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
+ WHERE TABLE_SCHEMA = CURRENT_SCHEMA AND UPPER(TABLE_NAME) = UPPER('view_meta')
+ AND CONSTRAINT_TYPE = 'PRIMARY KEY'), 'view_meta_pkey') || '"';
+ALTER TABLE `view_meta` ADD PRIMARY KEY (`view_id`, `deleted_at`);
+
+
+
-- Preserve policy_relation_meta from pre-2.0 installations, including its existing data.
@@ -247,6 +274,121 @@ CREATE INDEX IF NOT EXISTS `idx_smsr_model` ON `semantic_model_source_rel` (`sem
CREATE INDEX IF NOT EXISTS `idx_smsr_source` ON `semantic_model_source_rel` (`metalake_id`, `source_type`, `source_id`, `deleted_at`);
CREATE INDEX IF NOT EXISTS `idx_smsr_deleted_at` ON `semantic_model_source_rel` (`deleted_at`);
+-- Clear governance attached to retired external registrations before their IDs can be reused.
+-- A retry must preserve relationships attached to a new active registration of the same ID.
+UPDATE owner_meta r
+SET deleted_at = ((UNIX_TIMESTAMP() * 1000.0) + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000),
+ updated_at = ((UNIX_TIMESTAMP() * 1000.0) + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000)
+WHERE r.deleted_at = 0 AND EXISTS (
+ SELECT 1 FROM schema_meta retired
+ WHERE r.metadata_object_type = 'SCHEMA' AND retired.schema_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM schema_meta live
+ WHERE live.schema_id = retired.schema_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM table_meta retired
+ WHERE r.metadata_object_type = 'TABLE' AND retired.table_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM table_meta live
+ WHERE live.table_id = retired.table_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM topic_meta retired
+ WHERE r.metadata_object_type = 'TOPIC' AND retired.topic_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM topic_meta live
+ WHERE live.topic_id = retired.topic_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM view_meta retired
+ WHERE r.metadata_object_type = 'VIEW' AND retired.view_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM view_meta live
+ WHERE live.view_id = retired.view_id AND live.deleted_at = 0)
+);
+
+UPDATE role_meta_securable_object r
+SET deleted_at = ((UNIX_TIMESTAMP() * 1000.0) + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000)
+WHERE r.deleted_at = 0 AND EXISTS (
+ SELECT 1 FROM schema_meta retired
+ WHERE r.type = 'SCHEMA' AND retired.schema_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM schema_meta live
+ WHERE live.schema_id = retired.schema_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM table_meta retired
+ WHERE r.type = 'TABLE' AND retired.table_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM table_meta live
+ WHERE live.table_id = retired.table_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM topic_meta retired
+ WHERE r.type = 'TOPIC' AND retired.topic_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM topic_meta live
+ WHERE live.topic_id = retired.topic_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM view_meta retired
+ WHERE r.type = 'VIEW' AND retired.view_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM view_meta live
+ WHERE live.view_id = retired.view_id AND live.deleted_at = 0)
+);
+
+UPDATE tag_relation_meta r
+SET deleted_at = ((UNIX_TIMESTAMP() * 1000.0) + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000)
+WHERE r.deleted_at = 0 AND EXISTS (
+ SELECT 1 FROM schema_meta retired
+ WHERE r.metadata_object_type = 'SCHEMA' AND retired.schema_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM schema_meta live
+ WHERE live.schema_id = retired.schema_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM table_meta retired
+ WHERE r.metadata_object_type = 'TABLE' AND retired.table_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM table_meta live
+ WHERE live.table_id = retired.table_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM topic_meta retired
+ WHERE r.metadata_object_type = 'TOPIC' AND retired.topic_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM topic_meta live
+ WHERE live.topic_id = retired.topic_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM view_meta retired
+ WHERE r.metadata_object_type = 'VIEW' AND retired.view_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM view_meta live
+ WHERE live.view_id = retired.view_id AND live.deleted_at = 0)
+);
+
+UPDATE statistic_meta r
+SET deleted_at = ((UNIX_TIMESTAMP() * 1000.0) + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000)
+WHERE r.deleted_at = 0 AND EXISTS (
+ SELECT 1 FROM schema_meta retired
+ WHERE r.metadata_object_type = 'SCHEMA' AND retired.schema_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM schema_meta live
+ WHERE live.schema_id = retired.schema_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM table_meta retired
+ WHERE r.metadata_object_type = 'TABLE' AND retired.table_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM table_meta live
+ WHERE live.table_id = retired.table_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM topic_meta retired
+ WHERE r.metadata_object_type = 'TOPIC' AND retired.topic_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM topic_meta live
+ WHERE live.topic_id = retired.topic_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM view_meta retired
+ WHERE r.metadata_object_type = 'VIEW' AND retired.view_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM view_meta live
+ WHERE live.view_id = retired.view_id AND live.deleted_at = 0)
+);
+
-- Align the location and uri name widths with the MySQL and PostgreSQL schemas.
ALTER TABLE `fileset_version_info` ALTER COLUMN `storage_location_name` VARCHAR(256) NOT NULL DEFAULT 'default';
ALTER TABLE `model_version_info` ALTER COLUMN `model_version_uri_name` VARCHAR(256) NOT NULL;
diff --git a/scripts/mysql/schema-2.0.0-mysql.sql b/scripts/mysql/schema-2.0.0-mysql.sql
index ecbda7e839..c95284821d 100644
--- a/scripts/mysql/schema-2.0.0-mysql.sql
+++ b/scripts/mysql/schema-2.0.0-mysql.sql
@@ -58,7 +58,7 @@ CREATE TABLE IF NOT EXISTS `schema_meta` (
`current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'schema current version',
`last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'schema last version',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'schema deleted at',
- PRIMARY KEY (`schema_id`),
+ PRIMARY KEY (`schema_id`, `deleted_at`),
UNIQUE KEY `uk_cid_sn_del` (`catalog_id`, `schema_name`, `deleted_at`),
KEY `schema_meta_idx_mid` (`metalake_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'schema metadata';
@@ -73,7 +73,7 @@ CREATE TABLE IF NOT EXISTS `table_meta` (
`current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'table current version',
`last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'table last version',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'table deleted at',
- PRIMARY KEY (`table_id`),
+ PRIMARY KEY (`table_id`, `deleted_at`),
UNIQUE KEY `table_meta_uk_sid_tn_del` (`schema_id`, `table_name`, `deleted_at`),
KEY `table_meta_idx_mid` (`metalake_id`),
KEY `table_meta_idx_cid` (`catalog_id`)
@@ -153,7 +153,7 @@ CREATE TABLE IF NOT EXISTS `topic_meta` (
`current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'topic current version',
`last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'topic last version',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'topic deleted at',
- PRIMARY KEY (`topic_id`),
+ PRIMARY KEY (`topic_id`, `deleted_at`),
UNIQUE KEY `topic_meta_uk_sid_tn_del` (`schema_id`, `topic_name`, `deleted_at`),
KEY `topic_meta_idx_mid` (`metalake_id`),
KEY `topic_meta_idx_cid` (`catalog_id`)
@@ -536,7 +536,7 @@ CREATE TABLE IF NOT EXISTS `view_meta` (
`current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'view current version',
`last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'view last version',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'view deleted at',
- PRIMARY KEY (`view_id`),
+ PRIMARY KEY (`view_id`, `deleted_at`),
UNIQUE KEY `uk_sid_vn_del` (`schema_id`, `view_name`, `deleted_at`),
KEY `idx_vemid` (`metalake_id`),
KEY `idx_vecid` (`catalog_id`)
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 705f0fdef9..39214079cc 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
@@ -17,6 +17,69 @@
-- under the License.
--
+
+-- Preserve retired registrations while keeping each external ID unique among active rows.
+SET @ddl = IF((SELECT COUNT(*) = 2 AND SUM(
+ (seq_in_index = 1 AND column_name = 'schema_id') OR
+ (seq_in_index = 2 AND column_name = 'deleted_at')) = 2
+ FROM information_schema.statistics
+ WHERE table_schema = DATABASE() AND table_name = 'schema_meta' AND index_name = 'PRIMARY'),
+ 'SELECT 1',
+ IF((SELECT COUNT(*) = 1 AND MAX(column_name) = 'schema_id'
+ FROM information_schema.statistics
+ WHERE table_schema = DATABASE() AND table_name = 'schema_meta' AND index_name = 'PRIMARY'),
+ 'ALTER TABLE `schema_meta` DROP PRIMARY KEY, ADD PRIMARY KEY (`schema_id`, `deleted_at`)',
+ 'ALTER TABLE `schema_meta` ADD PRIMARY KEY (`schema_id`, `deleted_at`)'));
+PREPARE stmt FROM @ddl;
+EXECUTE stmt;
+DEALLOCATE PREPARE stmt;
+
+SET @ddl = IF((SELECT COUNT(*) = 2 AND SUM(
+ (seq_in_index = 1 AND column_name = 'table_id') OR
+ (seq_in_index = 2 AND column_name = 'deleted_at')) = 2
+ FROM information_schema.statistics
+ WHERE table_schema = DATABASE() AND table_name = 'table_meta' AND index_name = 'PRIMARY'),
+ 'SELECT 1',
+ IF((SELECT COUNT(*) = 1 AND MAX(column_name) = 'table_id'
+ FROM information_schema.statistics
+ WHERE table_schema = DATABASE() AND table_name = 'table_meta' AND index_name = 'PRIMARY'),
+ 'ALTER TABLE `table_meta` DROP PRIMARY KEY, ADD PRIMARY KEY (`table_id`, `deleted_at`)',
+ 'ALTER TABLE `table_meta` ADD PRIMARY KEY (`table_id`, `deleted_at`)'));
+PREPARE stmt FROM @ddl;
+EXECUTE stmt;
+DEALLOCATE PREPARE stmt;
+
+SET @ddl = IF((SELECT COUNT(*) = 2 AND SUM(
+ (seq_in_index = 1 AND column_name = 'topic_id') OR
+ (seq_in_index = 2 AND column_name = 'deleted_at')) = 2
+ FROM information_schema.statistics
+ WHERE table_schema = DATABASE() AND table_name = 'topic_meta' AND index_name = 'PRIMARY'),
+ 'SELECT 1',
+ IF((SELECT COUNT(*) = 1 AND MAX(column_name) = 'topic_id'
+ FROM information_schema.statistics
+ WHERE table_schema = DATABASE() AND table_name = 'topic_meta' AND index_name = 'PRIMARY'),
+ 'ALTER TABLE `topic_meta` DROP PRIMARY KEY, ADD PRIMARY KEY (`topic_id`, `deleted_at`)',
+ 'ALTER TABLE `topic_meta` ADD PRIMARY KEY (`topic_id`, `deleted_at`)'));
+PREPARE stmt FROM @ddl;
+EXECUTE stmt;
+DEALLOCATE PREPARE stmt;
+
+SET @ddl = IF((SELECT COUNT(*) = 2 AND SUM(
+ (seq_in_index = 1 AND column_name = 'view_id') OR
+ (seq_in_index = 2 AND column_name = 'deleted_at')) = 2
+ FROM information_schema.statistics
+ WHERE table_schema = DATABASE() AND table_name = 'view_meta' AND index_name = 'PRIMARY'),
+ 'SELECT 1',
+ IF((SELECT COUNT(*) = 1 AND MAX(column_name) = 'view_id'
+ FROM information_schema.statistics
+ WHERE table_schema = DATABASE() AND table_name = 'view_meta' AND index_name = 'PRIMARY'),
+ 'ALTER TABLE `view_meta` DROP PRIMARY KEY, ADD PRIMARY KEY (`view_id`, `deleted_at`)',
+ 'ALTER TABLE `view_meta` ADD PRIMARY KEY (`view_id`, `deleted_at`)'));
+PREPARE stmt FROM @ddl;
+EXECUTE stmt;
+DEALLOCATE PREPARE stmt;
+
+
-- MySQL has no ADD COLUMN / CREATE INDEX IF NOT EXISTS. Guard completed DDL
-- so a failed upgrade can be restarted from the beginning without --force.
-- Keep each operation in this session; no stored routines or extra privileges are required.
@@ -713,6 +776,121 @@ CREATE TABLE IF NOT EXISTS `semantic_model_source_rel` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
COMMENT 'current semantic model dataset source associations';
+-- Clear governance attached to retired external registrations before their IDs can be reused.
+-- A retry must preserve relationships attached to a new active registration of the same ID.
+UPDATE owner_meta r
+SET deleted_at = ((UNIX_TIMESTAMP() * 1000.0) + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000),
+ updated_at = ((UNIX_TIMESTAMP() * 1000.0) + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000)
+WHERE r.deleted_at = 0 AND EXISTS (
+ SELECT 1 FROM schema_meta retired
+ WHERE r.metadata_object_type = 'SCHEMA' AND retired.schema_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM schema_meta live
+ WHERE live.schema_id = retired.schema_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM table_meta retired
+ WHERE r.metadata_object_type = 'TABLE' AND retired.table_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM table_meta live
+ WHERE live.table_id = retired.table_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM topic_meta retired
+ WHERE r.metadata_object_type = 'TOPIC' AND retired.topic_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM topic_meta live
+ WHERE live.topic_id = retired.topic_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM view_meta retired
+ WHERE r.metadata_object_type = 'VIEW' AND retired.view_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM view_meta live
+ WHERE live.view_id = retired.view_id AND live.deleted_at = 0)
+);
+
+UPDATE role_meta_securable_object r
+SET deleted_at = ((UNIX_TIMESTAMP() * 1000.0) + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000)
+WHERE r.deleted_at = 0 AND EXISTS (
+ SELECT 1 FROM schema_meta retired
+ WHERE r.type = 'SCHEMA' AND retired.schema_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM schema_meta live
+ WHERE live.schema_id = retired.schema_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM table_meta retired
+ WHERE r.type = 'TABLE' AND retired.table_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM table_meta live
+ WHERE live.table_id = retired.table_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM topic_meta retired
+ WHERE r.type = 'TOPIC' AND retired.topic_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM topic_meta live
+ WHERE live.topic_id = retired.topic_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM view_meta retired
+ WHERE r.type = 'VIEW' AND retired.view_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM view_meta live
+ WHERE live.view_id = retired.view_id AND live.deleted_at = 0)
+);
+
+UPDATE tag_relation_meta r
+SET deleted_at = ((UNIX_TIMESTAMP() * 1000.0) + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000)
+WHERE r.deleted_at = 0 AND EXISTS (
+ SELECT 1 FROM schema_meta retired
+ WHERE r.metadata_object_type = 'SCHEMA' AND retired.schema_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM schema_meta live
+ WHERE live.schema_id = retired.schema_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM table_meta retired
+ WHERE r.metadata_object_type = 'TABLE' AND retired.table_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM table_meta live
+ WHERE live.table_id = retired.table_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM topic_meta retired
+ WHERE r.metadata_object_type = 'TOPIC' AND retired.topic_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM topic_meta live
+ WHERE live.topic_id = retired.topic_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM view_meta retired
+ WHERE r.metadata_object_type = 'VIEW' AND retired.view_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM view_meta live
+ WHERE live.view_id = retired.view_id AND live.deleted_at = 0)
+);
+
+UPDATE statistic_meta r
+SET deleted_at = ((UNIX_TIMESTAMP() * 1000.0) + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000)
+WHERE r.deleted_at = 0 AND EXISTS (
+ SELECT 1 FROM schema_meta retired
+ WHERE r.metadata_object_type = 'SCHEMA' AND retired.schema_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM schema_meta live
+ WHERE live.schema_id = retired.schema_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM table_meta retired
+ WHERE r.metadata_object_type = 'TABLE' AND retired.table_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM table_meta live
+ WHERE live.table_id = retired.table_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM topic_meta retired
+ WHERE r.metadata_object_type = 'TOPIC' AND retired.topic_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM topic_meta live
+ WHERE live.topic_id = retired.topic_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM view_meta retired
+ WHERE r.metadata_object_type = 'VIEW' AND retired.view_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM view_meta live
+ WHERE live.view_id = retired.view_id AND live.deleted_at = 0)
+);
+
CREATE TABLE IF NOT EXISTS `domain_meta` (
`domain_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'domain id',
`domain_name` VARCHAR(128) NOT NULL COMMENT 'domain name',
diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql b/scripts/postgresql/schema-2.0.0-postgresql.sql
index afc1ba6333..6c4d8c92a0 100644
--- a/scripts/postgresql/schema-2.0.0-postgresql.sql
+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql
@@ -92,7 +92,7 @@ CREATE TABLE IF NOT EXISTS schema_meta (
current_version INT NOT NULL DEFAULT 1,
last_version INT NOT NULL DEFAULT 1,
deleted_at BIGINT NOT NULL DEFAULT 0,
- PRIMARY KEY (schema_id),
+ PRIMARY KEY (schema_id, deleted_at),
UNIQUE (catalog_id, schema_name, deleted_at)
);
@@ -121,7 +121,7 @@ CREATE TABLE IF NOT EXISTS table_meta (
current_version INT NOT NULL DEFAULT 1,
last_version INT NOT NULL DEFAULT 1,
deleted_at BIGINT NOT NULL DEFAULT 0,
- PRIMARY KEY (table_id),
+ PRIMARY KEY (table_id, deleted_at),
UNIQUE (schema_id, table_name, deleted_at)
);
@@ -263,7 +263,7 @@ CREATE TABLE IF NOT EXISTS topic_meta (
current_version INT NOT NULL DEFAULT 1,
last_version INT NOT NULL DEFAULT 1,
deleted_at BIGINT NOT NULL DEFAULT 0,
- PRIMARY KEY (topic_id),
+ PRIMARY KEY (topic_id, deleted_at),
UNIQUE (schema_id, topic_name, deleted_at)
);
@@ -944,7 +944,7 @@ CREATE TABLE IF NOT EXISTS view_meta (
current_version INT NOT NULL DEFAULT 1,
last_version INT NOT NULL DEFAULT 1,
deleted_at BIGINT NOT NULL DEFAULT 0,
- PRIMARY KEY (view_id),
+ PRIMARY KEY (view_id, deleted_at),
UNIQUE (schema_id, view_name, deleted_at)
);
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 e027c8e864..c4c1fb651d 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
@@ -18,6 +18,25 @@
--
+-- Preserve retired registrations while keeping each external ID unique among active rows.
+ALTER TABLE schema_meta
+ DROP CONSTRAINT IF EXISTS schema_meta_pkey,
+ ADD CONSTRAINT schema_meta_pkey PRIMARY KEY (schema_id, deleted_at);
+
+ALTER TABLE table_meta
+ DROP CONSTRAINT IF EXISTS table_meta_pkey,
+ ADD CONSTRAINT table_meta_pkey PRIMARY KEY (table_id, deleted_at);
+
+ALTER TABLE topic_meta
+ DROP CONSTRAINT IF EXISTS topic_meta_pkey,
+ ADD CONSTRAINT topic_meta_pkey PRIMARY KEY (topic_id, deleted_at);
+
+ALTER TABLE view_meta
+ DROP CONSTRAINT IF EXISTS view_meta_pkey,
+ ADD CONSTRAINT view_meta_pkey PRIMARY KEY (view_id, deleted_at);
+
+
+
@@ -366,6 +385,121 @@ COMMENT ON COLUMN semantic_model_source_rel.source_type IS 'TABLE or VIEW';
COMMENT ON COLUMN semantic_model_source_rel.source_id IS 'resolved source object id';
COMMENT ON COLUMN semantic_model_source_rel.deleted_at IS 'association retired at';
+-- Clear governance attached to retired external registrations before their IDs can be reused.
+-- A retry must preserve relationships attached to a new active registration of the same ID.
+UPDATE owner_meta r
+SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT),
+ updated_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)
+WHERE r.deleted_at = 0 AND EXISTS (
+ SELECT 1 FROM schema_meta retired
+ WHERE r.metadata_object_type = 'SCHEMA' AND retired.schema_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM schema_meta live
+ WHERE live.schema_id = retired.schema_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM table_meta retired
+ WHERE r.metadata_object_type = 'TABLE' AND retired.table_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM table_meta live
+ WHERE live.table_id = retired.table_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM topic_meta retired
+ WHERE r.metadata_object_type = 'TOPIC' AND retired.topic_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM topic_meta live
+ WHERE live.topic_id = retired.topic_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM view_meta retired
+ WHERE r.metadata_object_type = 'VIEW' AND retired.view_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM view_meta live
+ WHERE live.view_id = retired.view_id AND live.deleted_at = 0)
+);
+
+UPDATE role_meta_securable_object r
+SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)
+WHERE r.deleted_at = 0 AND EXISTS (
+ SELECT 1 FROM schema_meta retired
+ WHERE r.type = 'SCHEMA' AND retired.schema_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM schema_meta live
+ WHERE live.schema_id = retired.schema_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM table_meta retired
+ WHERE r.type = 'TABLE' AND retired.table_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM table_meta live
+ WHERE live.table_id = retired.table_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM topic_meta retired
+ WHERE r.type = 'TOPIC' AND retired.topic_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM topic_meta live
+ WHERE live.topic_id = retired.topic_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM view_meta retired
+ WHERE r.type = 'VIEW' AND retired.view_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM view_meta live
+ WHERE live.view_id = retired.view_id AND live.deleted_at = 0)
+);
+
+UPDATE tag_relation_meta r
+SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)
+WHERE r.deleted_at = 0 AND EXISTS (
+ SELECT 1 FROM schema_meta retired
+ WHERE r.metadata_object_type = 'SCHEMA' AND retired.schema_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM schema_meta live
+ WHERE live.schema_id = retired.schema_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM table_meta retired
+ WHERE r.metadata_object_type = 'TABLE' AND retired.table_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM table_meta live
+ WHERE live.table_id = retired.table_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM topic_meta retired
+ WHERE r.metadata_object_type = 'TOPIC' AND retired.topic_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM topic_meta live
+ WHERE live.topic_id = retired.topic_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM view_meta retired
+ WHERE r.metadata_object_type = 'VIEW' AND retired.view_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM view_meta live
+ WHERE live.view_id = retired.view_id AND live.deleted_at = 0)
+);
+
+UPDATE statistic_meta r
+SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)
+WHERE r.deleted_at = 0 AND EXISTS (
+ SELECT 1 FROM schema_meta retired
+ WHERE r.metadata_object_type = 'SCHEMA' AND retired.schema_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM schema_meta live
+ WHERE live.schema_id = retired.schema_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM table_meta retired
+ WHERE r.metadata_object_type = 'TABLE' AND retired.table_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM table_meta live
+ WHERE live.table_id = retired.table_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM topic_meta retired
+ WHERE r.metadata_object_type = 'TOPIC' AND retired.topic_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM topic_meta live
+ WHERE live.topic_id = retired.topic_id AND live.deleted_at = 0)
+ UNION ALL
+ SELECT 1 FROM view_meta retired
+ WHERE r.metadata_object_type = 'VIEW' AND retired.view_id = r.metadata_object_id
+ AND retired.deleted_at > 0
+ AND NOT EXISTS (SELECT 1 FROM view_meta live
+ WHERE live.view_id = retired.view_id AND live.deleted_at = 0)
+);
+
CREATE TABLE IF NOT EXISTS domain_meta (
domain_id BIGINT NOT NULL,
domain_name VARCHAR(128) NOT NULL,
diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/SparkCommonIT.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/SparkCommonIT.java
index b743787498..c9e25e4a2c 100644
--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/SparkCommonIT.java
+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/SparkCommonIT.java
@@ -25,6 +25,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@@ -606,7 +607,17 @@ public abstract class SparkCommonIT extends SparkEnvIT {
@Test
@EnabledIf("supportsReplaceColumns")
protected void testAlterTableReplaceColumns() {
+ runAlterTableReplaceColumnsTest(true);
+ }
+
+ /**
+ * Tests replacing columns and accessing the resulting table.
+ *
+ * @param useUppercaseTableName whether to use an uppercase table name after replacing columns
+ */
+ protected void runAlterTableReplaceColumnsTest(boolean useUppercaseTableName) {
String tableName = "test_replace_columns_table";
+ String accessTableName = useUppercaseTableName ? tableName.toUpperCase(Locale.ROOT) : tableName;
dropTableIfExists(tableName);
createSimpleTable(tableName);
@@ -630,7 +641,10 @@ public abstract class SparkCommonIT extends SparkEnvIT {
tableInfo = getTableInfo(tableName);
checkTableColumns(tableName, updateColumns, tableInfo);
- sql(String.format("INSERT INTO %S VALUES(3, 'name2', 10)", tableName));
+ sql(
+ String.format(
+ "CREATE TABLE IF NOT EXISTS %s (id int, name2 string, age long)", accessTableName));
+ sql(String.format("INSERT INTO %s VALUES(3, 'name2', 10)", accessTableName));
List<String> data = getQueryData(String.format("SELECT * from %s ORDER BY id", tableName));
Assertions.assertEquals(2, data.size());
if (supportsSchemaEvolution()) {
diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/iceberg/SparkIcebergCatalogHiveBackendIT.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/iceberg/SparkIcebergCatalogHiveBackendIT.java
index fd1edd6784..ecaa411a91 100644
--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/iceberg/SparkIcebergCatalogHiveBackendIT.java
+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/iceberg/SparkIcebergCatalogHiveBackendIT.java
@@ -29,7 +29,6 @@ import org.junit.jupiter.api.Tag;
/** This class use Apache Iceberg HiveCatalog for backend catalog. */
@Tag("gravitino-docker-test")
public abstract class SparkIcebergCatalogHiveBackendIT extends SparkIcebergCatalogIT {
-
@Override
protected Map<String, String> getExtraSparkConfigs() {
// This class deliberately exercises the legacy Hive backend without a discoverable Iceberg
diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/iceberg/SparkIcebergCatalogRestBackendIT.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/iceberg/SparkIcebergCatalogRestBackendIT.java
index 6962cfbbda..22c44d0bf5 100644
--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/iceberg/SparkIcebergCatalogRestBackendIT.java
+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/iceberg/SparkIcebergCatalogRestBackendIT.java
@@ -22,7 +22,9 @@ import com.google.common.collect.Maps;
import java.util.Map;
import org.apache.gravitino.spark.connector.iceberg.IcebergPropertiesConstants;
import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIf;
+import org.junit.jupiter.api.condition.EnabledIf;
/**
* This class use Apache Iceberg RESTCatalog for test, and the real backend catalog is HiveCatalog.
@@ -33,6 +35,17 @@ import org.junit.jupiter.api.condition.DisabledIf;
@DisabledIf("org.apache.gravitino.integration.test.util.ITUtils#isEmbedded")
public abstract class SparkIcebergCatalogRestBackendIT extends SparkIcebergCatalogIT {
+ /**
+ * Tests replacing columns without assuming the case-sensitivity of the catalog behind the REST
+ * service. Gravitino cannot infer that backend capability through the REST protocol.
+ */
+ @Override
+ @Test
+ @EnabledIf("supportsReplaceColumns")
+ protected void testAlterTableReplaceColumns() {
+ runAlterTableReplaceColumnsTest(false);
+ }
+
@Override
protected Map<String, String> getCatalogConfigs() {
Map<String, String> catalogProperties = Maps.newHashMap();