Skip to content

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

[#10916] feat(cache): Add entity change log mapper (#10914)

Qi Yu7de28b554794
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogMapper.java
new file mode 100644
index 0000000000..ada263b359
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogMapper.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.storage.relational.mapper;
+
+import java.util.List;
+import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
+import org.apache.ibatis.annotations.DeleteProvider;
+import org.apache.ibatis.annotations.InsertProvider;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.SelectProvider;
+
+/**
+ * A MyBatis Mapper for entity_change_log table operations.
+ *
+ * <p>This append-only log tracks structural changes to entities (alter, drop) and is used by the
+ * entity change poller to drive targeted invalidation of the metadataIdCache on HA peer nodes.
+ */
+public interface EntityChangeLogMapper {
+
+ String ENTITY_CHANGE_LOG_TABLE_NAME = "entity_change_log";
+
+ @SelectProvider(type = EntityChangeLogSQLProviderFactory.class, method = "selectEntityChanges")
+ List<EntityChangeRecord> selectEntityChanges(
+ @Param("createdAtFrom") long createdAtFrom, @Param("maxRows") int maxRows);
+
+ @InsertProvider(type = EntityChangeLogSQLProviderFactory.class, method = "insertEntityChange")
+ void insertEntityChange(
+ @Param("metalakeName") String metalakeName,
+ @Param("entityType") String entityType,
+ @Param("fullName") String fullName,
+ @Param("operateType") OperateType operateType);
+
+ @DeleteProvider(type = EntityChangeLogSQLProviderFactory.class, method = "pruneOldEntityChanges")
+ void pruneOldEntityChanges(@Param("before") long before);
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogSQLProviderFactory.java
new file mode 100644
index 0000000000..4ee8e43156
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/EntityChangeLogSQLProviderFactory.java
@@ -0,0 +1,69 @@
+/*
+ * 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;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.Map;
+import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;
+import org.apache.gravitino.storage.relational.mapper.provider.base.EntityChangeLogBaseSQLProvider;
+import org.apache.gravitino.storage.relational.mapper.provider.postgresql.EntityChangeLogPostgreSQLProvider;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.ibatis.annotations.Param;
+
+public class EntityChangeLogSQLProviderFactory {
+
+ private static final Map<JDBCBackendType, EntityChangeLogBaseSQLProvider>
+ ENTITY_CHANGE_LOG_SQL_PROVIDER_MAP =
+ ImmutableMap.of(
+ JDBCBackendType.MYSQL, new EntityChangeLogMySQLProvider(),
+ JDBCBackendType.H2, new EntityChangeLogH2Provider(),
+ JDBCBackendType.POSTGRESQL, new EntityChangeLogPostgreSQLProvider());
+
+ public static EntityChangeLogBaseSQLProvider getProvider() {
+ String databaseId =
+ SqlSessionFactoryHelper.getInstance()
+ .getSqlSessionFactory()
+ .getConfiguration()
+ .getDatabaseId();
+ JDBCBackendType jdbcBackendType = JDBCBackendType.fromString(databaseId);
+ return ENTITY_CHANGE_LOG_SQL_PROVIDER_MAP.get(jdbcBackendType);
+ }
+
+ static class EntityChangeLogMySQLProvider extends EntityChangeLogBaseSQLProvider {}
+
+ static class EntityChangeLogH2Provider extends EntityChangeLogBaseSQLProvider {}
+
+ public static String selectEntityChanges(
+ @Param("createdAtFrom") long createdAtFrom, @Param("maxRows") int maxRows) {
+ return getProvider().selectEntityChanges(createdAtFrom, maxRows);
+ }
+
+ public static String insertEntityChange(
+ @Param("metalakeName") String metalakeName,
+ @Param("entityType") String entityType,
+ @Param("fullName") String fullName,
+ @Param("operateType") OperateType operateType) {
+ return getProvider().insertEntityChange(metalakeName, entityType, fullName, operateType);
+ }
+
+ public static String pruneOldEntityChanges(@Param("before") long before) {
+ return getProvider().pruneOldEntityChanges(before);
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OperateTypeHandler.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OperateTypeHandler.java
new file mode 100644
index 0000000000..9e582ebed0
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OperateTypeHandler.java
@@ -0,0 +1,60 @@
+/*
+ * 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;
+
+import java.sql.CallableStatement;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
+import org.apache.ibatis.type.BaseTypeHandler;
+import org.apache.ibatis.type.JdbcType;
+import org.apache.ibatis.type.MappedTypes;
+
+/**
+ * MyBatis type handler that maps {@link OperateType} to its stable numeric code stored in the
+ * {@code entity_change_log.operate_type} column.
+ */
+@MappedTypes(OperateType.class)
+public class OperateTypeHandler extends BaseTypeHandler<OperateType> {
+
+ @Override
+ public void setNonNullParameter(
+ PreparedStatement ps, int i, OperateType parameter, JdbcType jdbcType) throws SQLException {
+ ps.setInt(i, parameter.getCode());
+ }
+
+ @Override
+ public OperateType getNullableResult(ResultSet rs, String columnName) throws SQLException {
+ int code = rs.getInt(columnName);
+ return rs.wasNull() ? null : OperateType.fromCode(code);
+ }
+
+ @Override
+ public OperateType getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
+ int code = rs.getInt(columnIndex);
+ return rs.wasNull() ? null : OperateType.fromCode(code);
+ }
+
+ @Override
+ public OperateType getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
+ int code = cs.getInt(columnIndex);
+ return cs.wasNull() ? null : OperateType.fromCode(code);
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
index 394da706de..d4ead5df7a 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.storage.relational.mapper.provider;
import com.google.common.collect.ImmutableList;
import java.util.List;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
@@ -59,6 +60,7 @@ public class DefaultMapperPackageProvider implements MapperPackageProvider {
public List<Class<?>> getMapperClasses() {
return ImmutableList.of(
CatalogMetaMapper.class,
+ EntityChangeLogMapper.class,
FilesetMetaMapper.class,
FilesetVersionMapper.class,
FunctionMetaMapper.class,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/EntityChangeLogBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/EntityChangeLogBaseSQLProvider.java
new file mode 100644
index 0000000000..6193263c5e
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/EntityChangeLogBaseSQLProvider.java
@@ -0,0 +1,75 @@
+/*
+ * 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.base;
+
+import static org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper.ENTITY_CHANGE_LOG_TABLE_NAME;
+
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
+import org.apache.ibatis.annotations.Param;
+
+public class EntityChangeLogBaseSQLProvider {
+
+ /**
+ * Cursor-advance contract for the entity change poller:
+ *
+ * <p>The {@code created_at >= #{createdAtFrom}} predicate is <b>inclusive</b>. Combined with
+ * {@code ORDER BY created_at, id}, callers must remember the {@code (lastCreatedAt, lastId)} of
+ * the last consumed row and on the next poll: pass {@code createdAtFrom = lastCreatedAt} and
+ * client-side skip rows whose {@code id <= lastId} until they encounter a row with {@code
+ * created_at > lastCreatedAt}. Naively advancing by {@code lastCreatedAt + 1} would miss rows
+ * sharing the same millisecond boundary; advancing by {@code lastCreatedAt} re-reads the boundary
+ * row and relies on the client-side id filter.
+ */
+ public String selectEntityChanges(
+ @Param("createdAtFrom") long createdAtFrom, @Param("maxRows") int maxRows) {
+ return "SELECT id, metalake_name as metalakeName, entity_type as entityType,"
+ + " entity_full_name as fullName, operate_type as operateType, created_at as createdAt"
+ + " FROM "
+ + ENTITY_CHANGE_LOG_TABLE_NAME
+ + " WHERE created_at >= #{createdAtFrom} ORDER BY created_at, id LIMIT #{maxRows}";
+ }
+
+ /**
+ * The {@code (UNIX_TIMESTAMP() * 1000.0) + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000}
+ * expression is the established codebase convention for DB-generated millisecond timestamps,
+ * shared with 27+ other base providers (TableMetaBaseSQLProvider, FilesetVersionBaseSQLProvider,
+ * etc.). It works on MySQL natively and on H2 in {@code MODE=MYSQL}; PostgreSQL overrides this
+ * method in its own provider. Round-trip behaviour is verified by {@code
+ * TestEntityChangeLogMapper#testEntityChangeLogInsertAndSelect}, which asserts the persisted
+ * value is within 1 s of the JVM clock.
+ */
+ public String insertEntityChange(
+ @Param("metalakeName") String metalakeName,
+ @Param("entityType") String entityType,
+ @Param("fullName") String fullName,
+ @Param("operateType") OperateType operateType) {
+ return "INSERT INTO "
+ + ENTITY_CHANGE_LOG_TABLE_NAME
+ + " (metalake_name, entity_type, entity_full_name, operate_type, created_at)"
+ + " VALUES (#{metalakeName}, #{entityType}, #{fullName}, #{operateType},"
+ + " (UNIX_TIMESTAMP() * 1000.0)"
+ + " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000)";
+ }
+
+ public String pruneOldEntityChanges(@Param("before") long before) {
+ return "DELETE FROM "
+ + ENTITY_CHANGE_LOG_TABLE_NAME
+ + " WHERE created_at < #{before} LIMIT 1000";
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/EntityChangeLogPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/EntityChangeLogPostgreSQLProvider.java
new file mode 100644
index 0000000000..d6cdbc5851
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/EntityChangeLogPostgreSQLProvider.java
@@ -0,0 +1,50 @@
+/*
+ * 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.postgresql;
+
+import static org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper.ENTITY_CHANGE_LOG_TABLE_NAME;
+
+import org.apache.gravitino.storage.relational.mapper.provider.base.EntityChangeLogBaseSQLProvider;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
+import org.apache.ibatis.annotations.Param;
+
+public class EntityChangeLogPostgreSQLProvider extends EntityChangeLogBaseSQLProvider {
+
+ @Override
+ public String insertEntityChange(
+ @Param("metalakeName") String metalakeName,
+ @Param("entityType") String entityType,
+ @Param("fullName") String fullName,
+ @Param("operateType") OperateType operateType) {
+ return "INSERT INTO "
+ + ENTITY_CHANGE_LOG_TABLE_NAME
+ + " (metalake_name, entity_type, entity_full_name, operate_type, created_at)"
+ + " VALUES (#{metalakeName}, #{entityType}, #{fullName}, #{operateType},"
+ + " CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT))";
+ }
+
+ @Override
+ public String pruneOldEntityChanges(@Param("before") long before) {
+ return "DELETE FROM "
+ + ENTITY_CHANGE_LOG_TABLE_NAME
+ + " WHERE id IN (SELECT id FROM "
+ + ENTITY_CHANGE_LOG_TABLE_NAME
+ + " WHERE created_at < #{before} ORDER BY created_at LIMIT 1000)";
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/cache/EntityChangeRecord.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/cache/EntityChangeRecord.java
new file mode 100644
index 0000000000..5c65699df6
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/cache/EntityChangeRecord.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.storage.relational.po.cache;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+/** Entity change poller result -- one row per entity_change_log entry. */
+@Getter
+@Setter
+@NoArgsConstructor
+@AllArgsConstructor
+public class EntityChangeRecord {
+ private long id;
+ private String metalakeName;
+ private String entityType;
+ private String fullName;
+ private OperateType operateType;
+ private long createdAt;
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/cache/OperateType.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/cache/OperateType.java
new file mode 100644
index 0000000000..943ad80d5c
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/cache/OperateType.java
@@ -0,0 +1,58 @@
+/*
+ * 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.po.cache;
+
+import java.util.Arrays;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/**
+ * Operate type emitted into {@code entity_change_log.operate_type}.
+ *
+ * <p>The numeric {@code code} is what is persisted in the database. Codes are stable forever and
+ * must never be reused: removing a value from this enum is allowed, but the same numeric code
+ * cannot subsequently be assigned to a different meaning, otherwise old log rows would be
+ * misinterpreted by readers.
+ */
+public enum OperateType {
+ ALTER(1),
+ DROP(2);
+
+ private static final Map<Integer, OperateType> BY_CODE =
+ Arrays.stream(values()).collect(Collectors.toMap(OperateType::getCode, Function.identity()));
+
+ private final int code;
+
+ OperateType(int code) {
+ this.code = code;
+ }
+
+ public int getCode() {
+ return code;
+ }
+
+ public static OperateType fromCode(int code) {
+ OperateType type = BY_CODE.get(code);
+ if (type == null) {
+ throw new IllegalArgumentException("Unknown OperateType code: " + code);
+ }
+ return type;
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java
index 6733227b62..34e8ca13db 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/CatalogMetaService.java
@@ -24,6 +24,7 @@ import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.gravitino.Entity;
@@ -38,6 +39,7 @@ import org.apache.gravitino.meta.SchemaEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.helper.CatalogIds;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
@@ -56,6 +58,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.po.CatalogPO;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -219,23 +222,43 @@ public class CatalogMetaService {
newEntity.id(),
oldCatalogEntity.id());
- Integer updateResult;
+ String metalakeName = identifier.namespace().level(0);
+ String oldFullName =
+ NameIdentifierUtil.ofCatalog(metalakeName, oldCatalogEntity.name()).toString();
+ String newFullName = NameIdentifierUtil.ofCatalog(metalakeName, newEntity.name()).toString();
+ boolean isRenamed = !Objects.equals(oldFullName, newFullName);
+
+ AtomicInteger updateResult = new AtomicInteger(0);
try {
- updateResult =
- SessionUtils.doWithCommitAndFetchResult(
- CatalogMetaMapper.class,
- mapper ->
- mapper.updateCatalogMeta(
- POConverters.updateCatalogPOWithVersion(
- oldCatalogPO, newEntity, oldCatalogPO.getMetalakeId()),
- oldCatalogPO));
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ updateResult.set(
+ SessionUtils.getWithoutCommit(
+ CatalogMetaMapper.class,
+ mapper ->
+ mapper.updateCatalogMeta(
+ POConverters.updateCatalogPOWithVersion(
+ oldCatalogPO, newEntity, oldCatalogPO.getMetalakeId()),
+ oldCatalogPO))),
+ () -> {
+ if (isRenamed && updateResult.get() > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.CATALOG.name(),
+ oldFullName,
+ OperateType.ALTER));
+ }
+ });
} catch (RuntimeException re) {
ExceptionUtils.checkSQLException(
re, Entity.EntityType.CATALOG, newEntity.nameIdentifier().toString());
throw re;
}
- if (updateResult > 0) {
+ if (updateResult.get() > 0) {
return newEntity;
} else {
throw new IOException("Failed to update the entity: " + identifier);
@@ -250,6 +273,7 @@ public class CatalogMetaService {
String catalogName = identifier.name();
long catalogId = EntityIdService.getEntityId(identifier, Entity.EntityType.CATALOG);
+ String metalakeName = identifier.namespace().level(0);
if (cascade) {
SessionUtils.doMultipleWithCommit(
@@ -322,8 +346,20 @@ public class CatalogMetaService {
mapper -> mapper.softDeleteStatisticsByCatalogId(catalogId)),
() ->
SessionUtils.doWithoutCommit(
- ViewMetaMapper.class,
- mapper -> mapper.softDeleteViewMetasByCatalogId(catalogId)));
+ ViewMetaMapper.class, mapper -> mapper.softDeleteViewMetasByCatalogId(catalogId)),
+ // Only one CATALOG DROP record is written here; the cache layer performs prefix
+ // eviction on '<metalake>.<catalog>.*', covering all descendants automatically.
+ // Writing per-child DROP rows would multiply changelog volume without benefit.
+ () -> {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.CATALOG.name(),
+ NameIdentifierUtil.ofCatalog(metalakeName, catalogName).toString(),
+ OperateType.DROP));
+ });
} else {
List<SchemaEntity> schemaEntities =
SchemaMetaService.getInstance()
@@ -365,7 +401,17 @@ public class CatalogMetaService {
PolicyMetadataObjectRelMapper.class,
mapper ->
mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- catalogId, MetadataObject.Type.CATALOG.name())));
+ catalogId, MetadataObject.Type.CATALOG.name())),
+ () -> {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.CATALOG.name(),
+ NameIdentifierUtil.ofCatalog(metalakeName, catalogName).toString(),
+ OperateType.DROP));
+ });
}
return true;
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java
index 118b9f0cbf..9c1f677b4b 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/FilesetMetaService.java
@@ -24,6 +24,7 @@ import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.gravitino.Entity;
@@ -36,6 +37,7 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.FilesetEntity;
import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
@@ -45,6 +47,7 @@ import org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.po.FilesetMaxVersionPO;
import org.apache.gravitino.storage.relational.po.FilesetPO;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -207,6 +210,14 @@ public class FilesetMetaService {
newEntity.id(),
oldFilesetEntity.id());
+ String metalakeName = identifier.namespace().level(0);
+ String catalogName = identifier.namespace().level(1);
+ String schemaName = identifier.namespace().level(2);
+ String oldFullName =
+ NameIdentifierUtil.ofFileset(metalakeName, catalogName, schemaName, oldFilesetEntity.name())
+ .toString();
+ boolean isRenamed = !Objects.equals(oldFilesetEntity.name(), newEntity.name());
+
Integer updateResult;
try {
boolean checkNeedUpdateVersion =
@@ -234,6 +245,18 @@ public class FilesetMetaService {
if (metaUpdateCountRef[0] == 0) {
throw new RuntimeException("Failed to update the entity: " + identifier);
}
+ },
+ () -> {
+ if (isRenamed && metaUpdateCountRef[0] > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.FILESET.name(),
+ oldFullName,
+ OperateType.ALTER));
+ }
});
updateResult = 1;
} catch (RuntimeException re) {
@@ -248,10 +271,26 @@ public class FilesetMetaService {
}
}
} else {
- updateResult =
- SessionUtils.doWithCommitAndFetchResult(
- FilesetMetaMapper.class,
- mapper -> mapper.updateFilesetMeta(newFilesetPO, oldFilesetPO));
+ int[] metaUpdateCountRef = new int[1];
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ metaUpdateCountRef[0] =
+ SessionUtils.getWithoutCommit(
+ FilesetMetaMapper.class,
+ mapper -> mapper.updateFilesetMeta(newFilesetPO, oldFilesetPO)),
+ () -> {
+ if (isRenamed && metaUpdateCountRef[0] > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.FILESET.name(),
+ oldFullName,
+ OperateType.ALTER));
+ }
+ });
+ updateResult = metaUpdateCountRef[0];
}
} catch (RuntimeException re) {
ExceptionUtils.checkSQLException(
@@ -273,46 +312,65 @@ public class FilesetMetaService {
FilesetPO filesetPO = getFilesetPOByIdentifier(identifier);
Long filesetId = filesetPO.getFilesetId();
+ String metalakeName = identifier.namespace().level(0);
+ String catalogName = identifier.namespace().level(1);
+ String schemaName = identifier.namespace().level(2);
+ String filesetFullName =
+ NameIdentifierUtil.ofFileset(metalakeName, catalogName, schemaName, identifier.name())
+ .toString();
+
// We should delete meta and version info
+ AtomicInteger deleteResult = new AtomicInteger(0);
SessionUtils.doMultipleWithCommit(
() ->
- SessionUtils.doWithoutCommit(
- FilesetMetaMapper.class,
- mapper -> mapper.softDeleteFilesetMetasByFilesetId(filesetId)),
- () ->
+ deleteResult.set(
+ SessionUtils.getWithoutCommit(
+ FilesetMetaMapper.class,
+ mapper -> mapper.softDeleteFilesetMetasByFilesetId(filesetId))),
+ () -> {
+ if (deleteResult.get() > 0) {
SessionUtils.doWithoutCommit(
FilesetVersionMapper.class,
- mapper -> mapper.softDeleteFilesetVersionsByFilesetId(filesetId)),
- () ->
+ mapper -> mapper.softDeleteFilesetVersionsByFilesetId(filesetId));
SessionUtils.doWithoutCommit(
OwnerMetaMapper.class,
mapper ->
mapper.softDeleteOwnerRelByMetadataObjectIdAndType(
- filesetId, MetadataObject.Type.FILESET.name())),
- () ->
+ filesetId, MetadataObject.Type.FILESET.name()));
SessionUtils.doWithoutCommit(
SecurableObjectMapper.class,
mapper ->
mapper.softDeleteObjectRelsByMetadataObject(
- filesetId, MetadataObject.Type.FILESET.name())),
- () ->
+ filesetId, MetadataObject.Type.FILESET.name()));
SessionUtils.doWithoutCommit(
TagMetadataObjectRelMapper.class,
mapper ->
mapper.softDeleteTagMetadataObjectRelsByMetadataObject(
- filesetId, MetadataObject.Type.FILESET.name())),
- () ->
+ filesetId, MetadataObject.Type.FILESET.name()));
SessionUtils.doWithoutCommit(
StatisticMetaMapper.class,
- mapper -> mapper.softDeleteStatisticsByEntityId(filesetId)),
- () ->
+ mapper -> mapper.softDeleteStatisticsByEntityId(filesetId));
SessionUtils.doWithoutCommit(
PolicyMetadataObjectRelMapper.class,
mapper ->
mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- filesetId, MetadataObject.Type.FILESET.name())));
+ filesetId, MetadataObject.Type.FILESET.name()));
+ }
+ },
+ () -> {
+ if (deleteResult.get() > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.FILESET.name(),
+ filesetFullName,
+ OperateType.DROP));
+ }
+ });
- return true;
+ return deleteResult.get() > 0;
}
@Monitored(
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java
index fc423a7b43..607dab00c1 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java
@@ -25,6 +25,7 @@ import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.gravitino.Entity;
@@ -36,6 +37,7 @@ import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
@@ -64,6 +66,7 @@ import org.apache.gravitino.storage.relational.mapper.UserMetaMapper;
import org.apache.gravitino.storage.relational.mapper.UserRoleRelMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.po.MetalakePO;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -173,19 +176,37 @@ public class MetalakeMetaService {
oldMetalakeEntity.id());
MetalakePO newMetalakePO =
POConverters.updateMetalakePOWithVersion(oldMetalakePO, newMetalakeEntity);
- Integer updateResult;
+
+ String oldFullName = oldMetalakeEntity.name();
+ boolean isRenamed = !Objects.equals(oldMetalakeEntity.name(), newMetalakeEntity.name());
+
+ AtomicInteger updateResult = new AtomicInteger(0);
try {
- updateResult =
- SessionUtils.doWithCommitAndFetchResult(
- MetalakeMetaMapper.class,
- mapper -> mapper.updateMetalakeMeta(newMetalakePO, oldMetalakePO));
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ updateResult.set(
+ SessionUtils.getWithoutCommit(
+ MetalakeMetaMapper.class,
+ mapper -> mapper.updateMetalakeMeta(newMetalakePO, oldMetalakePO))),
+ () -> {
+ if (isRenamed && updateResult.get() > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ oldMetalakeEntity.name(),
+ Entity.EntityType.METALAKE.name(),
+ oldFullName,
+ OperateType.ALTER));
+ }
+ });
} catch (RuntimeException re) {
ExceptionUtils.checkSQLException(
re, Entity.EntityType.METALAKE, newMetalakeEntity.nameIdentifier().toString());
throw re;
}
- if (updateResult > 0) {
+ if (updateResult.get() > 0) {
return newMetalakeEntity;
} else {
throw new IOException("Failed to update the entity: " + ident);
@@ -312,7 +333,17 @@ public class MetalakeMetaService {
() ->
SessionUtils.doWithoutCommit(
ViewMetaMapper.class,
- mapper -> mapper.softDeleteViewMetasByMetalakeId(metalakeId)));
+ mapper -> mapper.softDeleteViewMetasByMetalakeId(metalakeId)),
+ () -> {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ ident.name(),
+ Entity.EntityType.METALAKE.name(),
+ ident.name(),
+ OperateType.DROP));
+ });
} else {
List<CatalogEntity> catalogEntities =
CatalogMetaService.getInstance()
@@ -373,7 +404,17 @@ public class MetalakeMetaService {
() ->
SessionUtils.doWithoutCommit(
JobMetaMapper.class,
- mapper -> mapper.softDeleteJobMetasByMetalakeId(metalakeId)));
+ mapper -> mapper.softDeleteJobMetasByMetalakeId(metalakeId)),
+ () -> {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ ident.name(),
+ Entity.EntityType.METALAKE.name(),
+ ident.name(),
+ OperateType.DROP));
+ });
}
}
return true;
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
index 2b2a91d79e..d492371024 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/ModelMetaService.java
@@ -39,6 +39,7 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.ModelEntity;
import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ModelVersionAliasRelMapper;
import org.apache.gravitino.storage.relational.mapper.ModelVersionMetaMapper;
@@ -48,6 +49,7 @@ import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.po.ModelPO;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -123,6 +125,12 @@ public class ModelMetaService {
Long schemaId = modelPO.getSchemaId();
Long modelId = modelPO.getModelId();
+ String metalakeName = ident.namespace().level(0);
+ String catalogName = ident.namespace().level(1);
+ String schemaName = ident.namespace().level(2);
+ String modelFullName =
+ NameIdentifierUtil.ofModel(metalakeName, catalogName, schemaName, ident.name()).toString();
+
AtomicInteger modelDeletedCount = new AtomicInteger();
SessionUtils.doMultipleWithCommit(
// delete model versions first
@@ -174,7 +182,19 @@ public class ModelMetaService {
PolicyMetadataObjectRelMapper.class,
mapper ->
mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- modelId, MetadataObject.Type.MODEL.name())));
+ modelId, MetadataObject.Type.MODEL.name())),
+ () -> {
+ if (modelDeletedCount.get() > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.MODEL.name(),
+ modelFullName,
+ OperateType.DROP));
+ }
+ });
return modelDeletedCount.get() > 0;
}
@@ -349,21 +369,43 @@ public class ModelMetaService {
newEntity.id(),
oldModelEntity.id());
- Integer updateResult;
+ String metalakeName = identifier.namespace().level(0);
+ String catalogName = identifier.namespace().level(1);
+ String schemaName = identifier.namespace().level(2);
+ String oldFullName =
+ NameIdentifierUtil.ofModel(metalakeName, catalogName, schemaName, oldModelEntity.name())
+ .toString();
+ boolean isRenamed = !Objects.equals(oldModelEntity.name(), newEntity.name());
+
+ AtomicInteger updateResult = new AtomicInteger(0);
try {
- updateResult =
- SessionUtils.doWithCommitAndFetchResult(
- ModelMetaMapper.class,
- mapper ->
- mapper.updateModelMeta(
- POConverters.updateModelPO(oldModelPO, newEntity), oldModelPO));
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ updateResult.set(
+ SessionUtils.getWithoutCommit(
+ ModelMetaMapper.class,
+ mapper ->
+ mapper.updateModelMeta(
+ POConverters.updateModelPO(oldModelPO, newEntity), oldModelPO))),
+ () -> {
+ if (isRenamed && updateResult.get() > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.MODEL.name(),
+ oldFullName,
+ OperateType.ALTER));
+ }
+ });
} catch (RuntimeException re) {
ExceptionUtils.checkSQLException(
re, Entity.EntityType.MODEL, newEntity.nameIdentifier().toString());
throw re;
}
- if (updateResult > 0) {
+ if (updateResult.get() > 0) {
return newEntity;
} else {
throw new IOException("Failed to update the entity: " + identifier);
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 561ed604fa..8127ae4c11 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
@@ -24,6 +24,7 @@ import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.gravitino.Entity;
@@ -43,6 +44,7 @@ import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.meta.TopicEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.helper.SchemaIds;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
@@ -61,6 +63,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.po.SchemaPO;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -195,21 +198,42 @@ public class SchemaMetaService {
newEntity.id(),
oldSchemaEntity.id());
- Integer updateResult;
+ String metalakeName = identifier.namespace().level(0);
+ String catalogName = identifier.namespace().level(1);
+ String oldFullName =
+ NameIdentifierUtil.ofSchema(metalakeName, catalogName, oldSchemaEntity.name()).toString();
+ boolean isRenamed = !Objects.equals(oldSchemaEntity.name(), newEntity.name());
+
+ AtomicInteger updateResult = new AtomicInteger(0);
try {
- updateResult =
- SessionUtils.doWithCommitAndFetchResult(
- SchemaMetaMapper.class,
- mapper ->
- mapper.updateSchemaMeta(
- POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity), oldSchemaPO));
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ updateResult.set(
+ SessionUtils.getWithoutCommit(
+ SchemaMetaMapper.class,
+ mapper ->
+ mapper.updateSchemaMeta(
+ POConverters.updateSchemaPOWithVersion(oldSchemaPO, newEntity),
+ oldSchemaPO))),
+ () -> {
+ if (isRenamed && updateResult.get() > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.SCHEMA.name(),
+ oldFullName,
+ OperateType.ALTER));
+ }
+ });
} catch (RuntimeException re) {
ExceptionUtils.checkSQLException(
re, Entity.EntityType.SCHEMA, newEntity.nameIdentifier().toString());
throw re;
}
- if (updateResult > 0) {
+ if (updateResult.get() > 0) {
return newEntity;
} else {
throw new IOException("Failed to update the entity: " + identifier);
@@ -225,6 +249,10 @@ public class SchemaMetaService {
String schemaName = identifier.name();
SchemaPO schemaPO = getSchemaPOByIdentifier(identifier);
Long schemaId = schemaPO.getSchemaId();
+ String metalakeName = identifier.namespace().level(0);
+ String catalogName = identifier.namespace().level(1);
+ String schemaFullName =
+ NameIdentifierUtil.ofSchema(metalakeName, catalogName, schemaName).toString();
if (cascade) {
SessionUtils.doMultipleWithCommit(
@@ -289,7 +317,17 @@ public class SchemaMetaService {
mapper -> mapper.softDeleteStatisticsBySchemaId(schemaId)),
() ->
SessionUtils.doWithoutCommit(
- ViewMetaMapper.class, mapper -> mapper.softDeleteViewMetasBySchemaId(schemaId)));
+ ViewMetaMapper.class, mapper -> mapper.softDeleteViewMetasBySchemaId(schemaId)),
+ () -> {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.SCHEMA.name(),
+ schemaFullName,
+ OperateType.DROP));
+ });
} else {
List<TableEntity> tableEntities =
TableMetaService.getInstance()
@@ -369,7 +407,17 @@ public class SchemaMetaService {
PolicyMetadataObjectRelMapper.class,
mapper ->
mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- schemaId, MetadataObject.Type.SCHEMA.name())));
+ schemaId, MetadataObject.Type.SCHEMA.name())),
+ () -> {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.SCHEMA.name(),
+ schemaFullName,
+ OperateType.DROP));
+ });
}
return true;
}
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 23d8a0f790..02c094a509 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
@@ -40,6 +40,7 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
@@ -49,6 +50,7 @@ import org.apache.gravitino.storage.relational.mapper.TableVersionMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.po.ColumnPO;
import org.apache.gravitino.storage.relational.po.TablePO;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -186,6 +188,15 @@ public class TableMetaService {
TablePO newTablePO =
POConverters.updateTablePOWithVersionAndSchemaId(oldTablePO, newTableEntity, newSchemaId);
+ String metalakeName = identifier.namespace().level(0);
+ String catalogName = identifier.namespace().level(1);
+ String schemaName = identifier.namespace().level(2);
+ String oldFullName =
+ NameIdentifierUtil.ofTable(metalakeName, catalogName, schemaName, oldTableEntity.name())
+ .toString();
+ boolean isFullNameChanged =
+ isSchemaChanged || !Objects.equals(oldTableEntity.name(), newTableEntity.name());
+
final AtomicInteger updateResult = new AtomicInteger(0);
try {
SessionUtils.doMultipleWithCommit(
@@ -207,6 +218,18 @@ public class TableMetaService {
TableColumnMetaService.getInstance()
.updateColumnPOsFromTableDiff(oldTableEntity, newTableEntity, newTablePO);
}
+ },
+ () -> {
+ if (isFullNameChanged && updateResult.get() > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.TABLE.name(),
+ oldFullName,
+ OperateType.ALTER));
+ }
});
} catch (RuntimeException re) {
@@ -226,6 +249,13 @@ public class TableMetaService {
public boolean deleteTable(NameIdentifier identifier) {
TablePO tablePO = getTablePOByIdentifier(identifier);
+ String metalakeName = identifier.namespace().level(0);
+ String catalogName = identifier.namespace().level(1);
+ String schemaName = identifier.namespace().level(2);
+ String tableFullName =
+ NameIdentifierUtil.ofTable(metalakeName, catalogName, schemaName, identifier.name())
+ .toString();
+
AtomicInteger deleteResult = new AtomicInteger(0);
SessionUtils.doMultipleWithCommit(
() ->
@@ -267,6 +297,18 @@ public class TableMetaService {
mapper.softDeleteTableVersionByTableIdAndVersion(
tablePO.getTableId(), tablePO.getCurrentVersion()));
}
+ },
+ () -> {
+ if (deleteResult.get() > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.TABLE.name(),
+ tableFullName,
+ OperateType.DROP));
+ }
});
return deleteResult.get() > 0;
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 ede75548b1..85bc2dbbe0 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
@@ -24,6 +24,7 @@ import com.google.common.base.Preconditions;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.gravitino.Entity;
@@ -36,6 +37,7 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.meta.TopicEntity;
import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.mapper.PolicyMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
@@ -43,6 +45,7 @@ import org.apache.gravitino.storage.relational.mapper.StatisticMetaMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
import org.apache.gravitino.storage.relational.po.TopicPO;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.POConverters;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -110,21 +113,44 @@ public class TopicMetaService {
newEntity.id(),
oldTopicEntity.id());
- Integer updateResult;
+ String metalakeName = ident.namespace().level(0);
+ String catalogName = ident.namespace().level(1);
+ String schemaName = ident.namespace().level(2);
+ String oldFullName =
+ NameIdentifierUtil.ofTopic(metalakeName, catalogName, schemaName, oldTopicEntity.name())
+ .toString();
+ boolean isRenamed = !Objects.equals(oldTopicEntity.name(), newEntity.name());
+
+ AtomicInteger updateResult = new AtomicInteger(0);
try {
- updateResult =
- SessionUtils.doWithCommitAndFetchResult(
- TopicMetaMapper.class,
- mapper ->
- mapper.updateTopicMeta(
- POConverters.updateTopicPOWithVersion(oldTopicPO, newEntity), oldTopicPO));
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ updateResult.set(
+ SessionUtils.getWithoutCommit(
+ TopicMetaMapper.class,
+ mapper ->
+ mapper.updateTopicMeta(
+ POConverters.updateTopicPOWithVersion(oldTopicPO, newEntity),
+ oldTopicPO))),
+ () -> {
+ if (isRenamed && updateResult.get() > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.TOPIC.name(),
+ oldFullName,
+ OperateType.ALTER));
+ }
+ });
} catch (RuntimeException re) {
ExceptionUtils.checkSQLException(
re, Entity.EntityType.TOPIC, newEntity.nameIdentifier().toString());
throw re;
}
- if (updateResult > 0) {
+ if (updateResult.get() > 0) {
return newEntity;
} else {
throw new IOException("Failed to update the entity: " + ident);
@@ -267,40 +293,61 @@ public class TopicMetaService {
TopicPO topicPO = getTopicPOByIdentifier(identifier);
Long topicId = topicPO.getTopicId();
+ String metalakeName = identifier.namespace().level(0);
+ String catalogName = identifier.namespace().level(1);
+ String schemaName = identifier.namespace().level(2);
+ String topicFullName =
+ NameIdentifierUtil.ofTopic(metalakeName, catalogName, schemaName, identifier.name())
+ .toString();
+
+ AtomicInteger deleteResult = new AtomicInteger(0);
SessionUtils.doMultipleWithCommit(
() ->
- SessionUtils.doWithoutCommit(
- TopicMetaMapper.class, mapper -> mapper.softDeleteTopicMetasByTopicId(topicId)),
- () ->
+ deleteResult.set(
+ SessionUtils.getWithoutCommit(
+ TopicMetaMapper.class,
+ mapper -> mapper.softDeleteTopicMetasByTopicId(topicId))),
+ () -> {
+ if (deleteResult.get() > 0) {
SessionUtils.doWithoutCommit(
OwnerMetaMapper.class,
mapper ->
mapper.softDeleteOwnerRelByMetadataObjectIdAndType(
- topicId, MetadataObject.Type.TOPIC.name())),
- () ->
+ topicId, MetadataObject.Type.TOPIC.name()));
SessionUtils.doWithoutCommit(
SecurableObjectMapper.class,
mapper ->
mapper.softDeleteObjectRelsByMetadataObject(
- topicId, MetadataObject.Type.TOPIC.name())),
- () ->
+ topicId, MetadataObject.Type.TOPIC.name()));
SessionUtils.doWithoutCommit(
TagMetadataObjectRelMapper.class,
mapper ->
mapper.softDeleteTagMetadataObjectRelsByMetadataObject(
- topicId, MetadataObject.Type.TOPIC.name())),
- () ->
+ topicId, MetadataObject.Type.TOPIC.name()));
SessionUtils.doWithoutCommit(
StatisticMetaMapper.class,
- mapper -> mapper.softDeleteStatisticsByEntityId(topicId)),
- () ->
+ mapper -> mapper.softDeleteStatisticsByEntityId(topicId));
SessionUtils.doWithoutCommit(
PolicyMetadataObjectRelMapper.class,
mapper ->
mapper.softDeletePolicyMetadataObjectRelsByMetadataObject(
- topicId, MetadataObject.Type.TOPIC.name())));
+ topicId, MetadataObject.Type.TOPIC.name()));
+ }
+ },
+ () -> {
+ if (deleteResult.get() > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.TOPIC.name(),
+ topicFullName,
+ OperateType.DROP));
+ }
+ });
- return true;
+ return deleteResult.get() > 0;
}
@Monitored(
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 4bdce7b3e0..177118c811 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
@@ -40,12 +40,14 @@ import org.apache.gravitino.Namespace;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.ViewEntity;
import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewVersionInfoMapper;
import org.apache.gravitino.storage.relational.po.ViewPO;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.utils.NameIdentifierUtil;
@@ -153,6 +155,14 @@ public class ViewMetaService {
AtomicInteger updateResult = new AtomicInteger(0);
try {
ViewPO newViewPO = updateViewPO(oldViewPO, newEntity);
+ String metalakeName = ident.namespace().level(0);
+ String catalogName = ident.namespace().level(1);
+ String schemaName = ident.namespace().level(2);
+ String oldFullName =
+ NameIdentifierUtil.ofView(metalakeName, catalogName, schemaName, oldViewPO.getViewName())
+ .toString();
+ boolean isRenamed = !Objects.equals(oldViewPO.getViewName(), newViewPO.getViewName());
+
SessionUtils.doMultipleWithCommit(
() ->
SessionUtils.doWithoutCommit(
@@ -165,6 +175,18 @@ public class ViewMetaService {
if (updateResult.get() == 0) {
throw new RuntimeException("Failed to update the entity: " + ident);
}
+ },
+ () -> {
+ if (isRenamed && updateResult.get() > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.VIEW.name(),
+ oldFullName,
+ OperateType.ALTER));
+ }
});
return newEntity;
} catch (RuntimeException re) {
@@ -183,7 +205,13 @@ public class ViewMetaService {
public boolean deleteView(NameIdentifier ident) {
NameIdentifierUtil.checkView(ident);
ViewPO viewPO = viewPOFetcher().apply(ident);
- return deleteView(viewPO.getViewId());
+ String metalakeName = ident.namespace().level(0);
+ String catalogName = ident.namespace().level(1);
+ String schemaName = ident.namespace().level(2);
+ String viewFullName =
+ NameIdentifierUtil.ofView(metalakeName, catalogName, schemaName, viewPO.getViewName())
+ .toString();
+ return deleteView(viewPO.getViewId(), metalakeName, viewFullName);
}
@Monitored(
@@ -203,7 +231,7 @@ public class ViewMetaService {
return versionDeletedCount + metaDeletedCount;
}
- private boolean deleteView(Long viewId) {
+ private boolean deleteView(Long viewId, String metalakeName, String viewFullName) {
AtomicInteger deleteResult = new AtomicInteger(0);
SessionUtils.doMultipleWithCommit(
() ->
@@ -231,6 +259,18 @@ public class ViewMetaService {
mapper.softDeleteTagMetadataObjectRelsByMetadataObject(
viewId, MetadataObject.Type.VIEW.name()));
}
+ },
+ () -> {
+ if (deleteResult.get() > 0) {
+ SessionUtils.doWithoutCommit(
+ EntityChangeLogMapper.class,
+ mapper ->
+ mapper.insertEntityChange(
+ metalakeName,
+ Entity.EntityType.VIEW.name(),
+ viewFullName,
+ OperateType.DROP));
+ }
});
return deleteResult.get() > 0;
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/session/SqlSessionFactoryHelper.java b/core/src/main/java/org/apache/gravitino/storage/relational/session/SqlSessionFactoryHelper.java
index bc406af3b5..529dfad676 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/session/SqlSessionFactoryHelper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/session/SqlSessionFactoryHelper.java
@@ -31,7 +31,9 @@ import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.metrics.MetricsSystem;
import org.apache.gravitino.metrics.source.RelationDatasourceMetricsSource;
import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;
+import org.apache.gravitino.storage.relational.mapper.OperateTypeHandler;
import org.apache.gravitino.storage.relational.mapper.provider.MapperPackageProvider;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.utils.JdbcUrlUtils;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
@@ -110,6 +112,7 @@ public class SqlSessionFactoryHelper {
// Initialize the configuration
Configuration configuration = new Configuration(environment);
configuration.setDatabaseId(jdbcType.name().toLowerCase());
+ configuration.getTypeHandlerRegistry().register(OperateType.class, new OperateTypeHandler());
ServiceLoader<MapperPackageProvider> loader = ServiceLoader.load(MapperPackageProvider.class);
for (MapperPackageProvider provider : loader) {
provider.getMapperClasses().forEach(configuration::addMapper);
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestEntityChangeLogMapper.java b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestEntityChangeLogMapper.java
new file mode 100644
index 0000000000..8b4a3be8c2
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/mapper/provider/base/TestEntityChangeLogMapper.java
@@ -0,0 +1,172 @@
+/*
+ * 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.base;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.List;
+import org.apache.commons.io.FileUtils;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.storage.relational.JDBCBackend;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
+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.ibatis.session.SqlSession;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+public class TestEntityChangeLogMapper {
+
+ private static Path jdbcStorePath;
+ private static String dbDir;
+ private static JDBCBackend backend;
+ private static EntityChangeLogMapper entityChangeLogMapper;
+ private static SqlSession sharedSession;
+
+ @BeforeAll
+ public static void setup() throws Exception {
+ jdbcStorePath = Files.createTempDirectory("gravitino_jdbc_entityChangeLog_");
+ Path dbPath = jdbcStorePath.resolve("testdb");
+ Files.createDirectories(dbPath);
+ dbDir = dbPath.toString();
+
+ Config config = Mockito.mock(Config.class);
+ Mockito.when(config.get(Configs.ENTITY_STORE)).thenReturn("relational");
+ Mockito.when(config.get(Configs.ENTITY_RELATIONAL_STORE)).thenReturn("h2");
+ Mockito.when(config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL))
+ .thenReturn(String.format("jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL", dbDir));
+ Mockito.when(config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_USER)).thenReturn("gravitino");
+ Mockito.when(config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD))
+ .thenReturn("gravitino");
+ Mockito.when(config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER))
+ .thenReturn("org.h2.Driver");
+ Mockito.when(config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS)).thenReturn(20);
+ Mockito.when(config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_MILLISECONDS))
+ .thenReturn(1000L);
+
+ backend = new JDBCBackend();
+ backend.initialize(config);
+
+ sharedSession = SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ entityChangeLogMapper = sharedSession.getMapper(EntityChangeLogMapper.class);
+ }
+
+ @AfterAll
+ public static void tearDown() throws IOException {
+ if (sharedSession != null) {
+ sharedSession.close();
+ }
+ if (backend != null) {
+ backend.close();
+ }
+ if (jdbcStorePath != null) {
+ FileUtils.deleteDirectory(jdbcStorePath.toFile());
+ }
+ }
+
+ @BeforeEach
+ void truncate() throws SQLException {
+ try (Statement statement = sharedSession.getConnection().createStatement()) {
+ statement.execute("DELETE FROM entity_change_log");
+ }
+ sharedSession.clearCache();
+ }
+
+ @Test
+ void testEntityChangeLogInsertAndSelect() {
+ long jvmBefore = System.currentTimeMillis();
+ entityChangeLogMapper.insertEntityChange(
+ "metalake1", "TABLE", "metalake1.cat.schema.tbl", OperateType.ALTER);
+ long jvmAfter = System.currentTimeMillis();
+
+ List<EntityChangeRecord> records =
+ entityChangeLogMapper.selectEntityChanges(jvmBefore - 1000L, 10);
+ Assertions.assertEquals(1, records.size());
+ EntityChangeRecord record = records.get(0);
+ Assertions.assertEquals("metalake1", record.getMetalakeName());
+ Assertions.assertEquals("TABLE", record.getEntityType());
+ Assertions.assertEquals("metalake1.cat.schema.tbl", record.getFullName());
+ Assertions.assertEquals(OperateType.ALTER, record.getOperateType());
+ // created_at is set by the DB, so it should be close to JVM time but not exactly equal.
+ Assertions.assertTrue(
+ record.getCreatedAt() >= jvmBefore - 1000L && record.getCreatedAt() <= jvmAfter + 1000L,
+ "expected DB-time created_at within 1s of JVM clock, got " + record.getCreatedAt());
+ Assertions.assertTrue(record.getId() > 0L);
+ }
+
+ @Test
+ void testEntityChangeLogPruneOldEntries() throws SQLException {
+ entityChangeLogMapper.insertEntityChange(
+ "metalake1", "SCHEMA", "metalake1.cat.schema", OperateType.ALTER);
+ forceCreatedAt("metalake1.cat.schema", 1000L);
+ entityChangeLogMapper.insertEntityChange(
+ "metalake1", "TABLE", "metalake1.cat.schema.tbl", OperateType.DROP);
+ long recent =
+ entityChangeLogMapper.selectEntityChanges(0L, 100).stream()
+ .filter(r -> r.getFullName().equals("metalake1.cat.schema.tbl"))
+ .mapToLong(EntityChangeRecord::getCreatedAt)
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("recent row missing"));
+
+ entityChangeLogMapper.pruneOldEntityChanges(1001L);
+
+ List<EntityChangeRecord> after = entityChangeLogMapper.selectEntityChanges(0L, 100);
+ Assertions.assertEquals(1, after.size());
+ Assertions.assertEquals(recent, after.get(0).getCreatedAt());
+ }
+
+ @Test
+ void testEntityChangeLogSameTimestampOrderedById() throws SQLException {
+ entityChangeLogMapper.insertEntityChange("metalake1", "TABLE", "a", OperateType.ALTER);
+ entityChangeLogMapper.insertEntityChange("metalake1", "TABLE", "b", OperateType.ALTER);
+ entityChangeLogMapper.insertEntityChange("metalake1", "TABLE", "c", OperateType.ALTER);
+ forceCreatedAt("a", 5_000_000L);
+ forceCreatedAt("b", 5_000_000L);
+ forceCreatedAt("c", 5_000_000L);
+
+ List<EntityChangeRecord> rows = entityChangeLogMapper.selectEntityChanges(0L, 100);
+ Assertions.assertEquals(3, rows.size());
+ Assertions.assertTrue(rows.get(0).getId() < rows.get(1).getId());
+ Assertions.assertTrue(rows.get(1).getId() < rows.get(2).getId());
+ }
+
+ private void forceCreatedAt(String fullName, long createdAt) throws SQLException {
+ try (PreparedStatement statement =
+ sharedSession
+ .getConnection()
+ .prepareStatement(
+ "UPDATE entity_change_log SET created_at = ? WHERE entity_full_name = ?")) {
+ statement.setLong(1, createdAt);
+ statement.setString(2, fullName);
+ statement.executeUpdate();
+ }
+ sharedSession.clearCache();
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestEntityChangeLogService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestEntityChangeLogService.java
new file mode 100644
index 0000000000..d605400f41
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestEntityChangeLogService.java
@@ -0,0 +1,329 @@
+/*
+ * 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 java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.meta.BaseMetalake;
+import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.FilesetEntity;
+import org.apache.gravitino.meta.ModelEntity;
+import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.TopicEntity;
+import org.apache.gravitino.meta.ViewEntity;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
+import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.TestTemplate;
+
+public class TestEntityChangeLogService extends TestJDBCBackend {
+ private static final String METALAKE_NAME = "metalake_for_entity_change_log_test";
+ private static final String CATALOG_NAME = "catalog_for_entity_change_log_test";
+ private static final String SCHEMA_NAME = "schema_for_entity_change_log_test";
+
+ private List<EntityChangeRecord> listEntityChanges(long createdAtFrom) {
+ return SessionUtils.doWithCommitAndFetchResult(
+ EntityChangeLogMapper.class, mapper -> mapper.selectEntityChanges(createdAtFrom, 100));
+ }
+
+ private void assertEntityChange(
+ long createdAtFrom,
+ String metalakeName,
+ Entity.EntityType entityType,
+ String fullName,
+ OperateType operateType) {
+ Assertions.assertTrue(
+ listEntityChanges(createdAtFrom).stream()
+ .anyMatch(
+ record ->
+ record.getMetalakeName().equals(metalakeName)
+ && record.getEntityType().equals(entityType.name())
+ && record.getFullName().equals(fullName)
+ && record.getOperateType() == operateType),
+ String.format("Missing %s %s changelog for %s", entityType, operateType, fullName));
+ }
+
+ @TestTemplate
+ void testMetalakeChangeLogOnRenameAndDrop() throws IOException {
+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);
+
+ long beforeRename = System.currentTimeMillis() - 1;
+ BaseMetalake renamedMetalake =
+ backend.update(
+ metalake.nameIdentifier(),
+ Entity.EntityType.METALAKE,
+ entity ->
+ createBaseMakeLake(
+ metalake.id(), METALAKE_NAME + "_renamed", metalake.auditInfo()));
+ assertEntityChange(
+ beforeRename, METALAKE_NAME, Entity.EntityType.METALAKE, METALAKE_NAME, OperateType.ALTER);
+
+ long beforeDrop = System.currentTimeMillis() - 1;
+ Assertions.assertTrue(
+ MetalakeMetaService.getInstance().deleteMetalake(renamedMetalake.nameIdentifier(), false));
+ assertEntityChange(
+ beforeDrop,
+ renamedMetalake.name(),
+ Entity.EntityType.METALAKE,
+ renamedMetalake.name(),
+ OperateType.DROP);
+ }
+
+ @TestTemplate
+ void testCatalogAndSchemaChangeLogOnRenameAndDrop() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+
+ CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, CATALOG_NAME);
+ long beforeCatalogRename = System.currentTimeMillis() - 1;
+ CatalogEntity renamedCatalog =
+ backend.update(
+ catalog.nameIdentifier(),
+ Entity.EntityType.CATALOG,
+ entity ->
+ createCatalog(
+ catalog.id(), catalog.namespace(), CATALOG_NAME + "_renamed", AUDIT_INFO));
+ assertEntityChange(
+ beforeCatalogRename,
+ METALAKE_NAME,
+ Entity.EntityType.CATALOG,
+ NameIdentifierUtil.ofCatalog(METALAKE_NAME, CATALOG_NAME).toString(),
+ OperateType.ALTER);
+
+ long beforeCatalogDrop = System.currentTimeMillis() - 1;
+ Assertions.assertTrue(
+ CatalogMetaService.getInstance().deleteCatalog(renamedCatalog.nameIdentifier(), false));
+ assertEntityChange(
+ beforeCatalogDrop,
+ METALAKE_NAME,
+ Entity.EntityType.CATALOG,
+ NameIdentifierUtil.ofCatalog(METALAKE_NAME, renamedCatalog.name()).toString(),
+ OperateType.DROP);
+
+ CatalogEntity schemaCatalog = createAndInsertCatalog(METALAKE_NAME, CATALOG_NAME + "_schema");
+ SchemaEntity schema = createAndInsertSchema(METALAKE_NAME, schemaCatalog.name(), SCHEMA_NAME);
+ long beforeSchemaRename = System.currentTimeMillis() - 1;
+ SchemaEntity renamedSchema =
+ backend.update(
+ schema.nameIdentifier(),
+ Entity.EntityType.SCHEMA,
+ entity ->
+ createSchemaEntity(
+ schema.id(), schema.namespace(), SCHEMA_NAME + "_renamed", AUDIT_INFO));
+ assertEntityChange(
+ beforeSchemaRename,
+ METALAKE_NAME,
+ Entity.EntityType.SCHEMA,
+ NameIdentifierUtil.ofSchema(METALAKE_NAME, schemaCatalog.name(), SCHEMA_NAME).toString(),
+ OperateType.ALTER);
+
+ long beforeSchemaDrop = System.currentTimeMillis() - 1;
+ Assertions.assertTrue(
+ SchemaMetaService.getInstance().deleteSchema(renamedSchema.nameIdentifier(), false));
+ assertEntityChange(
+ beforeSchemaDrop,
+ METALAKE_NAME,
+ Entity.EntityType.SCHEMA,
+ NameIdentifierUtil.ofSchema(METALAKE_NAME, schemaCatalog.name(), renamedSchema.name())
+ .toString(),
+ OperateType.DROP);
+ }
+
+ @TestTemplate
+ void testLeafEntityChangeLogOnRenameAndDrop() throws IOException {
+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);
+ Namespace namespace = Namespace.of(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME);
+
+ TableEntity table =
+ createTableEntity(RandomIdGenerator.INSTANCE.nextId(), namespace, "table1", AUDIT_INFO);
+ backend.insert(table, false);
+ long beforeTableRename = System.currentTimeMillis() - 1;
+ TableEntity renamedTable =
+ TableMetaService.getInstance()
+ .updateTable(
+ table.nameIdentifier(),
+ entity ->
+ createTableEntity(table.id(), table.namespace(), "table2", table.auditInfo()));
+ assertEntityChange(
+ beforeTableRename,
+ METALAKE_NAME,
+ Entity.EntityType.TABLE,
+ NameIdentifierUtil.ofTable(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "table1").toString(),
+ OperateType.ALTER);
+
+ long beforeTableDrop = System.currentTimeMillis() - 1;
+ Assertions.assertTrue(
+ TableMetaService.getInstance().deleteTable(renamedTable.nameIdentifier()));
+ assertEntityChange(
+ beforeTableDrop,
+ METALAKE_NAME,
+ Entity.EntityType.TABLE,
+ NameIdentifierUtil.ofTable(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "table2").toString(),
+ OperateType.DROP);
+
+ TopicEntity topic =
+ createTopicEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofTopic(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),
+ "topic1",
+ AUDIT_INFO);
+ backend.insert(topic, false);
+ long beforeTopicRename = System.currentTimeMillis() - 1;
+ TopicEntity renamedTopic =
+ backend.update(
+ topic.nameIdentifier(),
+ Entity.EntityType.TOPIC,
+ entity -> createTopicEntity(topic.id(), topic.namespace(), "topic2", AUDIT_INFO));
+ assertEntityChange(
+ beforeTopicRename,
+ METALAKE_NAME,
+ Entity.EntityType.TOPIC,
+ NameIdentifierUtil.ofTopic(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "topic1").toString(),
+ OperateType.ALTER);
+
+ long beforeTopicDrop = System.currentTimeMillis() - 1;
+ Assertions.assertTrue(
+ TopicMetaService.getInstance().deleteTopic(renamedTopic.nameIdentifier()));
+ assertEntityChange(
+ beforeTopicDrop,
+ METALAKE_NAME,
+ Entity.EntityType.TOPIC,
+ NameIdentifierUtil.ofTopic(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "topic2").toString(),
+ OperateType.DROP);
+
+ ViewEntity view =
+ createViewEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofView(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),
+ "view1");
+ ViewMetaService.getInstance().insertView(view, false);
+ long beforeViewRename = System.currentTimeMillis() - 1;
+ ViewEntity renamedView =
+ ViewMetaService.getInstance()
+ .updateView(
+ view.nameIdentifier(),
+ entity ->
+ ViewEntity.builder()
+ .withId(view.id())
+ .withName("view2")
+ .withNamespace(view.namespace())
+ .withColumns(view.columns())
+ .withRepresentations(view.representations())
+ .withAuditInfo(view.auditInfo())
+ .build());
+ assertEntityChange(
+ beforeViewRename,
+ METALAKE_NAME,
+ Entity.EntityType.VIEW,
+ NameIdentifierUtil.ofView(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "view1").toString(),
+ OperateType.ALTER);
+
+ long beforeViewDrop = System.currentTimeMillis() - 1;
+ Assertions.assertTrue(ViewMetaService.getInstance().deleteView(renamedView.nameIdentifier()));
+ assertEntityChange(
+ beforeViewDrop,
+ METALAKE_NAME,
+ Entity.EntityType.VIEW,
+ NameIdentifierUtil.ofView(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "view2").toString(),
+ OperateType.DROP);
+
+ FilesetEntity fileset =
+ createFilesetEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofFileset(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),
+ "fileset1",
+ AUDIT_INFO);
+ FilesetMetaService.getInstance().insertFileset(fileset, false);
+ long beforeFilesetRename = System.currentTimeMillis() - 1;
+ FilesetEntity renamedFileset =
+ FilesetMetaService.getInstance()
+ .updateFileset(
+ fileset.nameIdentifier(),
+ entity ->
+ createFilesetEntity(fileset.id(), fileset.namespace(), "fileset2", AUDIT_INFO));
+ assertEntityChange(
+ beforeFilesetRename,
+ METALAKE_NAME,
+ Entity.EntityType.FILESET,
+ NameIdentifierUtil.ofFileset(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "fileset1")
+ .toString(),
+ OperateType.ALTER);
+
+ long beforeFilesetDrop = System.currentTimeMillis() - 1;
+ Assertions.assertTrue(
+ FilesetMetaService.getInstance().deleteFileset(renamedFileset.nameIdentifier()));
+ assertEntityChange(
+ beforeFilesetDrop,
+ METALAKE_NAME,
+ Entity.EntityType.FILESET,
+ NameIdentifierUtil.ofFileset(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "fileset2")
+ .toString(),
+ OperateType.DROP);
+
+ ModelEntity model =
+ createModelEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofModel(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),
+ "model1",
+ "model comment",
+ 0,
+ Map.of("k1", "v1"),
+ AUDIT_INFO);
+ ModelMetaService.getInstance().insertModel(model, false);
+ long beforeModelRename = System.currentTimeMillis() - 1;
+ ModelEntity renamedModel =
+ ModelMetaService.getInstance()
+ .updateModel(
+ model.nameIdentifier(),
+ entity ->
+ createModelEntity(
+ model.id(),
+ model.namespace(),
+ "model2",
+ model.comment(),
+ model.latestVersion(),
+ model.properties(),
+ AUDIT_INFO));
+ assertEntityChange(
+ beforeModelRename,
+ METALAKE_NAME,
+ Entity.EntityType.MODEL,
+ NameIdentifierUtil.ofModel(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "model1").toString(),
+ OperateType.ALTER);
+
+ long beforeModelDrop = System.currentTimeMillis() - 1;
+ Assertions.assertTrue(
+ ModelMetaService.getInstance().deleteModel(renamedModel.nameIdentifier()));
+ assertEntityChange(
+ beforeModelDrop,
+ METALAKE_NAME,
+ Entity.EntityType.MODEL,
+ NameIdentifierUtil.ofModel(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, "model2").toString(),
+ OperateType.DROP);
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableMetaService.java
index 0c30660818..6596b4af2c 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableMetaService.java
@@ -55,6 +55,11 @@ import org.apache.gravitino.rel.indexes.Indexes;
import org.apache.gravitino.rel.types.Types;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
+import org.apache.gravitino.storage.relational.po.cache.EntityChangeRecord;
+import org.apache.gravitino.storage.relational.po.cache.OperateType;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.TestTemplate;
@@ -64,6 +69,11 @@ public class TestTableMetaService extends TestJDBCBackend {
private final String catalogName = "catalog_for_table_test";
private final String schemaName = "schema_for_table_test";
+ private List<EntityChangeRecord> listEntityChanges(long createdAtFrom) {
+ return SessionUtils.doWithCommitAndFetchResult(
+ EntityChangeLogMapper.class, mapper -> mapper.selectEntityChanges(createdAtFrom, 100));
+ }
+
@TestTemplate
public void testInsertAlreadyExistsException() throws IOException {
createAndInsertMakeLake(metalakeName);
@@ -191,6 +201,7 @@ public class TestTableMetaService extends TestJDBCBackend {
TableMetaService.getInstance().insertTable(createdTable, false);
// test update table without changing schema name
+ long beforeRename = System.currentTimeMillis() - 1;
TableEntity updatedTable =
TableEntity.builder()
.withId(createdTable.id())
@@ -210,6 +221,19 @@ public class TestTableMetaService extends TestJDBCBackend {
Assertions.assertEquals(updatedTable.auditInfo(), retrievedTable.auditInfo());
compareTwoColumns(updatedTable.columns(), retrievedTable.columns());
compareTwoColumns(updatedTable.columns(), retrievedTable.columns());
+ Assertions.assertTrue(
+ listEntityChanges(beforeRename).stream()
+ .anyMatch(
+ record ->
+ record.getMetalakeName().equals(metalakeName)
+ && record.getEntityType().equals(Entity.EntityType.TABLE.name())
+ && record
+ .getFullName()
+ .equals(
+ NameIdentifierUtil.ofTable(
+ metalakeName, catalogName, schemaName, "table1")
+ .toString())
+ && record.getOperateType() == OperateType.ALTER));
// test update table with changing schema name to a non-existing schema
String newSchemaName = "schema2";
@@ -238,7 +262,33 @@ public class TestTableMetaService extends TestJDBCBackend {
newSchemaName,
AUDIT_INFO);
backend.insert(newSchema, false);
- TableMetaService.getInstance().updateTable(updatedTable.nameIdentifier(), updater2);
+
+ long beforeSchemaMove = System.currentTimeMillis() - 1;
+ TableEntity movedTable =
+ TableEntity.builder()
+ .withId(updatedTable.id())
+ .withName(updatedTable.name())
+ .withNamespace(Namespace.of(metalakeName, catalogName, newSchemaName))
+ .withColumns(updatedTable.columns())
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ TableMetaService.getInstance()
+ .updateTable(updatedTable.nameIdentifier(), oldTable -> movedTable);
+ Assertions.assertTrue(
+ listEntityChanges(beforeSchemaMove).stream()
+ .anyMatch(
+ record ->
+ record.getMetalakeName().equals(metalakeName)
+ && record.getEntityType().equals(Entity.EntityType.TABLE.name())
+ && record
+ .getFullName()
+ .equals(
+ NameIdentifierUtil.ofTable(
+ metalakeName, catalogName, schemaName, "table2")
+ .toString())
+ && record.getOperateType() == OperateType.ALTER));
+
+ TableMetaService.getInstance().updateTable(movedTable.nameIdentifier(), updater2);
TableEntity retrievedTable2 =
TableMetaService.getInstance().getTableByIdentifier(updatedTable2.nameIdentifier());
@@ -247,6 +297,23 @@ public class TestTableMetaService extends TestJDBCBackend {
Assertions.assertEquals(updatedTable2.namespace(), retrievedTable2.namespace());
Assertions.assertEquals(updatedTable2.auditInfo(), retrievedTable2.auditInfo());
compareTwoColumns(updatedTable2.columns(), retrievedTable2.columns());
+
+ long beforeDelete = System.currentTimeMillis() - 1;
+ Assertions.assertTrue(
+ TableMetaService.getInstance().deleteTable(updatedTable2.nameIdentifier()));
+ Assertions.assertTrue(
+ listEntityChanges(beforeDelete).stream()
+ .anyMatch(
+ record ->
+ record.getMetalakeName().equals(metalakeName)
+ && record.getEntityType().equals(Entity.EntityType.TABLE.name())
+ && record
+ .getFullName()
+ .equals(
+ NameIdentifierUtil.ofTable(
+ metalakeName, catalogName, newSchemaName, "table3")
+ .toString())
+ && record.getOperateType() == OperateType.DROP));
}
@TestTemplate