World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#9107] refactor(TestJDBCBackend): refactor TestJDBCBackend and fix bugs (#9207)
mchades2a458603f5c8
diff --git a/build.gradle.kts b/build.gradle.ktsindex be919c3c0d..dbac9bbf74 100644--- a/build.gradle.kts+++ b/build.gradle.kts@@ -209,8 +209,9 @@ allprojects {param.include("**/integration/test/**")}+ val dockerTest = project.rootProject.extra["dockerTest"] as? Boolean ?: false+ param.environment("dockerTest", dockerTest.toString())param.useJUnitPlatform {- val dockerTest = project.rootProject.extra["dockerTest"] as? Boolean ?: falseif (!dockerTest) {excludeTags("gravitino-docker-test")}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/CatalogMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/CatalogMetaPostgreSQLProvider.javaindex 19f17acfcc..0482d9b330 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/CatalogMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/CatalogMetaPostgreSQLProvider.java@@ -29,8 +29,7 @@ public class CatalogMetaPostgreSQLProvider extends CatalogMetaBaseSQLProvider {public String softDeleteCatalogMetasByCatalogId(Long catalogId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE catalog_id = #{catalogId} AND deleted_at = 0";}@@ -38,8 +37,7 @@ public class CatalogMetaPostgreSQLProvider extends CatalogMetaBaseSQLProvider {public String softDeleteCatalogMetasByMetalakeId(Long metalakeId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/FilesetMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/FilesetMetaPostgreSQLProvider.javaindex e29a964e70..6c8920b0fd 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/FilesetMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/FilesetMetaPostgreSQLProvider.java@@ -29,8 +29,7 @@ public class FilesetMetaPostgreSQLProvider extends FilesetMetaBaseSQLProvider {public String softDeleteFilesetMetasByMetalakeId(Long metalakeId) {return "UPDATE "+ META_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}@@ -38,8 +37,7 @@ public class FilesetMetaPostgreSQLProvider extends FilesetMetaBaseSQLProvider {public String softDeleteFilesetMetasByCatalogId(Long catalogId) {return "UPDATE "+ META_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE catalog_id = #{catalogId} AND deleted_at = 0";}@@ -47,8 +45,7 @@ public class FilesetMetaPostgreSQLProvider extends FilesetMetaBaseSQLProvider {public String softDeleteFilesetMetasBySchemaId(Long schemaId) {return "UPDATE "+ META_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE schema_id = #{schemaId} AND deleted_at = 0";}@@ -56,8 +53,7 @@ public class FilesetMetaPostgreSQLProvider extends FilesetMetaBaseSQLProvider {public String softDeleteFilesetMetasByFilesetId(Long filesetId) {return "UPDATE "+ META_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE fileset_id = #{filesetId} AND deleted_at = 0";}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/FilesetVersionPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/FilesetVersionPostgreSQLProvider.javaindex 9d0d5f0d03..db5a7a4fe6 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/FilesetVersionPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/FilesetVersionPostgreSQLProvider.java@@ -30,8 +30,7 @@ public class FilesetVersionPostgreSQLProvider extends FilesetVersionBaseSQLProvipublic String softDeleteFilesetVersionsByMetalakeId(Long metalakeId) {return "UPDATE "+ VERSION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}@@ -39,8 +38,7 @@ public class FilesetVersionPostgreSQLProvider extends FilesetVersionBaseSQLProvipublic String softDeleteFilesetVersionsByCatalogId(Long catalogId) {return "UPDATE "+ VERSION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE catalog_id = #{catalogId} AND deleted_at = 0";}@@ -48,8 +46,7 @@ public class FilesetVersionPostgreSQLProvider extends FilesetVersionBaseSQLProvipublic String softDeleteFilesetVersionsBySchemaId(Long schemaId) {return "UPDATE "+ VERSION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE schema_id = #{schemaId} AND deleted_at = 0";}@@ -57,8 +54,7 @@ public class FilesetVersionPostgreSQLProvider extends FilesetVersionBaseSQLProvipublic String softDeleteFilesetVersionsByFilesetId(Long filesetId) {return "UPDATE "+ VERSION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE fileset_id = #{filesetId} AND deleted_at = 0";}@@ -77,8 +73,7 @@ public class FilesetVersionPostgreSQLProvider extends FilesetVersionBaseSQLProviLong filesetId, long versionRetentionLine, int limit) {return "UPDATE "+ VERSION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE id IN (SELECT id FROM "+ VERSION_TABLE_NAME+ " WHERE fileset_id = #{filesetId} AND version <= #{versionRetentionLine} AND deleted_at = 0 LIMIT #{limit})";diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/GroupMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/GroupMetaPostgreSQLProvider.javaindex 45c7439ee3..464c137e72 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/GroupMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/GroupMetaPostgreSQLProvider.java@@ -31,8 +31,7 @@ public class GroupMetaPostgreSQLProvider extends GroupMetaBaseSQLProvider {public String softDeleteGroupMetaByGroupId(Long groupId) {return "UPDATE "+ GROUP_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE group_id = #{groupId} AND deleted_at = 0";}@@ -40,8 +39,7 @@ public class GroupMetaPostgreSQLProvider extends GroupMetaBaseSQLProvider {public String softDeleteGroupMetasByMetalakeId(Long metalakeId) {return "UPDATE "+ GROUP_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/GroupRoleRelPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/GroupRoleRelPostgreSQLProvider.javaindex 022b933f22..e5ee7d4c18 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/GroupRoleRelPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/GroupRoleRelPostgreSQLProvider.java@@ -30,8 +30,7 @@ public class GroupRoleRelPostgreSQLProvider extends GroupRoleRelBaseSQLProviderpublic String softDeleteGroupRoleRelByGroupId(Long groupId) {return "UPDATE "+ GROUP_ROLE_RELATION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE group_id = #{groupId} AND deleted_at = 0";}@@ -40,8 +39,7 @@ public class GroupRoleRelPostgreSQLProvider extends GroupRoleRelBaseSQLProviderreturn "<script>"+ "UPDATE "+ GROUP_ROLE_RELATION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE group_id = #{groupId} AND role_id IN ("+ "<foreach collection='roleIds' item='roleId' separator=','>"+ "#{roleId}"@@ -55,8 +53,7 @@ public class GroupRoleRelPostgreSQLProvider extends GroupRoleRelBaseSQLProviderpublic String softDeleteGroupRoleRelByMetalakeId(Long metalakeId) {return "UPDATE "+ GROUP_ROLE_RELATION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE group_id IN (SELECT group_id FROM "+ GROUP_TABLE_NAME+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0)"@@ -67,8 +64,7 @@ public class GroupRoleRelPostgreSQLProvider extends GroupRoleRelBaseSQLProviderpublic String softDeleteGroupRoleRelByRoleId(Long roleId) {return "UPDATE "+ GROUP_ROLE_RELATION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE role_id = #{roleId} AND deleted_at = 0";}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/JobMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/JobMetaPostgreSQLProvider.javaindex e284fbea27..1addd89e54 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/JobMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/JobMetaPostgreSQLProvider.java@@ -64,8 +64,7 @@ public class JobMetaPostgreSQLProvider extends JobMetaBaseSQLProvider {@Param("jobTemplateName") String jobTemplateName) {return "UPDATE "+ JobMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id IN ("+ " SELECT metalake_id FROM "+ MetalakeMetaMapper.TABLE_NAME@@ -81,16 +80,14 @@ public class JobMetaPostgreSQLProvider extends JobMetaBaseSQLProvider {public String softDeleteJobMetasByMetalakeId(@Param("metalakeId") Long metalakeId) {return "UPDATE "+ JobMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}public String softDeleteJobMetaByRunId(@Param("jobRunId") Long jobRunId) {return "UPDATE "+ JobMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE job_run_id = #{jobRunId} AND deleted_at = 0";}@@ -98,8 +95,7 @@ public class JobMetaPostgreSQLProvider extends JobMetaBaseSQLProvider {public String softDeleteJobMetasByLegacyTimeline(@Param("legacyTimeline") Long legacyTimeline) {return "UPDATE "+ JobMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE job_finished_at < #{legacyTimeline} AND job_finished_at > 0 AND deleted_at = 0";}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/JobTemplateMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/JobTemplateMetaPostgreSQLProvider.javaindex bb558f74ce..b5c71cad93 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/JobTemplateMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/JobTemplateMetaPostgreSQLProvider.java@@ -32,8 +32,7 @@ public class JobTemplateMetaPostgreSQLProvider extends JobTemplateMetaBaseSQLPro@Param("jobTemplateName") String jobTemplateName) {return "UPDATE "+ JobTemplateMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id IN ("+ " SELECT metalake_id FROM "+ MetalakeMetaMapper.TABLE_NAME@@ -45,8 +44,7 @@ public class JobTemplateMetaPostgreSQLProvider extends JobTemplateMetaBaseSQLPropublic String softDeleteJobTemplateMetasByMetalakeId(@Param("metalakeId") Long metalakeId) {return "UPDATE "+ JobTemplateMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/MetalakeMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/MetalakeMetaPostgreSQLProvider.javaindex b0f8fd6b56..5ce01e6715 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/MetalakeMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/MetalakeMetaPostgreSQLProvider.java@@ -29,8 +29,7 @@ public class MetalakeMetaPostgreSQLProvider extends MetalakeMetaBaseSQLProviderpublic String softDeleteMetalakeMetaByMetalakeId(Long metalakeId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelMetaPostgreSQLProvider.javaindex c30afc02a1..1ea7afd880 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelMetaPostgreSQLProvider.java@@ -52,8 +52,7 @@ public class ModelMetaPostgreSQLProvider extends ModelMetaBaseSQLProvider {@Param("schemaId") Long schemaId, @Param("modelName") String modelName) {return "UPDATE "+ ModelMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE schema_id = #{schemaId} AND model_name = #{modelName} AND deleted_at = 0";}@@ -61,8 +60,7 @@ public class ModelMetaPostgreSQLProvider extends ModelMetaBaseSQLProvider {public String softDeleteModelMetasByCatalogId(@Param("catalogId") Long catalogId) {return "UPDATE "+ ModelMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE catalog_id = #{catalogId} AND deleted_at = 0";}@@ -70,8 +68,7 @@ public class ModelMetaPostgreSQLProvider extends ModelMetaBaseSQLProvider {public String softDeleteModelMetasByMetalakeId(@Param("metalakeId") Long metalakeId) {return "UPDATE "+ ModelMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}@@ -79,8 +76,7 @@ public class ModelMetaPostgreSQLProvider extends ModelMetaBaseSQLProvider {public String softDeleteModelMetasBySchemaId(@Param("schemaId") Long schemaId) {return "UPDATE "+ ModelMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE schema_id = #{schemaId} AND deleted_at = 0";}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionAliasRelPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionAliasRelPostgreSQLProvider.javaindex c47151097d..7aecaf2302 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionAliasRelPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionAliasRelPostgreSQLProvider.java@@ -30,8 +30,7 @@ public class ModelVersionAliasRelPostgreSQLProvider extends ModelVersionAliasRel@Param("schemaId") Long schemaId, @Param("modelName") String modelName) {return "UPDATE "+ ModelVersionAliasRelMapper.TABLE_NAME- + " mvar SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " mvar SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE mvar.model_id = ("+ " SELECT mm.model_id FROM "+ ModelMetaMapper.TABLE_NAME@@ -44,8 +43,7 @@ public class ModelVersionAliasRelPostgreSQLProvider extends ModelVersionAliasRel@Param("modelId") Long modelId, @Param("modelVersion") Integer modelVersion) {return "UPDATE "+ ModelVersionAliasRelMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE model_id = #{modelId} AND model_version = #{modelVersion} AND deleted_at = 0";}@@ -54,8 +52,7 @@ public class ModelVersionAliasRelPostgreSQLProvider extends ModelVersionAliasRel@Param("modelId") Long modelId, @Param("alias") String alias) {return "UPDATE "+ ModelVersionAliasRelMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE model_id = #{modelId} AND model_version = ("+ " SELECT model_version FROM "+ ModelVersionAliasRelMapper.TABLE_NAME@@ -67,8 +64,7 @@ public class ModelVersionAliasRelPostgreSQLProvider extends ModelVersionAliasRelpublic String softDeleteModelVersionAliasRelsBySchemaId(@Param("schemaId") Long schemaId) {return "UPDATE "+ ModelVersionAliasRelMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE model_id IN ("+ " SELECT model_id FROM "+ ModelMetaMapper.TABLE_NAME@@ -79,8 +75,7 @@ public class ModelVersionAliasRelPostgreSQLProvider extends ModelVersionAliasRelpublic String softDeleteModelVersionAliasRelsByCatalogId(@Param("catalogId") Long catalogId) {return "UPDATE "+ ModelVersionAliasRelMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE model_id IN ("+ " SELECT model_id FROM "+ ModelMetaMapper.TABLE_NAME@@ -91,8 +86,7 @@ public class ModelVersionAliasRelPostgreSQLProvider extends ModelVersionAliasRelpublic String softDeleteModelVersionAliasRelsByMetalakeId(@Param("metalakeId") Long metalakeId) {return "UPDATE "+ ModelVersionAliasRelMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE model_id IN ("+ " SELECT model_id FROM "+ ModelMetaMapper.TABLE_NAMEdiff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionMetaPostgreSQLProvider.javaindex b9d82d5e67..00ae16c503 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ModelVersionMetaPostgreSQLProvider.java@@ -31,8 +31,7 @@ public class ModelVersionMetaPostgreSQLProvider extends ModelVersionMetaBaseSQLP@Param("schemaId") Long schemaId, @Param("modelName") String modelName) {return "UPDATE "+ ModelVersionMetaMapper.TABLE_NAME- + " mvi SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " mvi SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE mvi.schema_id = #{schemaId} AND mvi.model_id = ("+ " SELECT mm.model_id FROM "+ ModelMetaMapper.TABLE_NAME@@ -45,8 +44,7 @@ public class ModelVersionMetaPostgreSQLProvider extends ModelVersionMetaBaseSQLP@Param("modelId") Long modelId, @Param("modelVersion") Integer modelVersion) {return "UPDATE "+ ModelVersionMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE model_id = #{modelId} AND version = #{modelVersion} AND deleted_at = 0";}@@ -55,8 +53,7 @@ public class ModelVersionMetaPostgreSQLProvider extends ModelVersionMetaBaseSQLP@Param("modelId") Long modelId, @Param("alias") String alias) {return "UPDATE "+ ModelVersionMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE model_id = #{modelId} AND version = ("+ " SELECT model_version FROM "+ ModelVersionAliasRelMapper.TABLE_NAME@@ -68,8 +65,7 @@ public class ModelVersionMetaPostgreSQLProvider extends ModelVersionMetaBaseSQLPpublic String softDeleteModelVersionMetasBySchemaId(@Param("schemaId") Long schemaId) {return "UPDATE "+ ModelVersionMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE schema_id = #{schemaId} AND deleted_at = 0";}@@ -77,8 +73,7 @@ public class ModelVersionMetaPostgreSQLProvider extends ModelVersionMetaBaseSQLPpublic String softDeleteModelVersionMetasByCatalogId(@Param("catalogId") Long catalogId) {return "UPDATE "+ ModelVersionMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE catalog_id = #{catalogId} AND deleted_at = 0";}@@ -86,8 +81,7 @@ public class ModelVersionMetaPostgreSQLProvider extends ModelVersionMetaBaseSQLPpublic String softDeleteModelVersionMetasByMetalakeId(@Param("metalakeId") Long metalakeId) {return "UPDATE "+ ModelVersionMetaMapper.TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}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.javaindex f538b7ff06..ec50c68fb1 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@@ -35,8 +35,7 @@ public class OwnerMetaPostgreSQLProvider extends OwnerMetaBaseSQLProvider {Long metadataObjectId, String metadataObjectType) {return "UPDATE "+ OWNER_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metadata_object_id = #{metadataObjectId} AND metadata_object_type = #{metadataObjectType} AND deleted_at = 0";}@@ -44,8 +43,7 @@ public class OwnerMetaPostgreSQLProvider extends OwnerMetaBaseSQLProvider {public String softDeleteOwnerRelByOwnerIdAndType(Long ownerId, String ownerType) {return "UPDATE "+ OWNER_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE owner_id = #{ownerId} AND owner_type = #{ownerType} AND deleted_at = 0";}@@ -53,8 +51,7 @@ public class OwnerMetaPostgreSQLProvider extends OwnerMetaBaseSQLProvider {public String softDeleteOwnerRelByMetalakeId(Long metalakeId) {return "UPDATE "+ OWNER_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}@@ -62,8 +59,7 @@ public class OwnerMetaPostgreSQLProvider extends OwnerMetaBaseSQLProvider {public String softDeleteOwnerRelByCatalogId(Long catalogId) {return "UPDATE "+ OWNER_TABLE_NAME- + " ot SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " ot SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE ot.deleted_at = 0 AND EXISTS ("+ " SELECT ct.catalog_id FROM "+ CatalogMetaMapper.TABLE_NAME@@ -101,7 +97,7 @@ public class OwnerMetaPostgreSQLProvider extends OwnerMetaBaseSQLProvider {public String softDeleteOwnerRelBySchemaId(Long schemaId) {return "UPDATE "+ OWNER_TABLE_NAME- + " ot SET deleted_at = floor(extract(epoch from(current_timestamp - timestamp '1970-01-01 00:00:00')) * 1000)"+ + " ot SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE ot.deleted_at = 0 AND EXISTS ("+ " SELECT st.schema_id FROM "+ SchemaMetaMapper.TABLE_NAMEdiff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyMetaPostgreSQLProvider.javaindex 328a3ca16f..4ce42b67da 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyMetaPostgreSQLProvider.java@@ -29,8 +29,7 @@ public class PolicyMetaPostgreSQLProvider extends PolicyMetaBaseSQLProvider {public String softDeletePolicyByMetalakeAndPolicyName(String metalakeName, String policyName) {return "UPDATE "+ POLICY_META_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = (SELECT metalake_id FROM "+ " metalake_meta mm WHERE mm.metalake_name = #{metalakeName} AND mm.deleted_at = 0)"+ " AND policy_name = #{policyName} AND deleted_at = 0";@@ -40,8 +39,7 @@ public class PolicyMetaPostgreSQLProvider extends PolicyMetaBaseSQLProvider {public String softDeletePolicyMetasByMetalakeId(Long metalakeId) {return "UPDATE "+ POLICY_META_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}@@ -61,21 +59,21 @@ public class PolicyMetaPostgreSQLProvider extends PolicyMetaBaseSQLProvider {+ " (policy_id, policy_name, policy_type, metalake_id,"+ " audit_info, current_version, last_version, deleted_at)"+ " VALUES ("- + " #{policyPO.policyId},"- + " #{policyPO.policyName},"- + " #{policyPO.policyType},"- + " #{policyPO.metalakeId},"- + " #{policyPO.auditInfo},"- + " #{policyPO.currentVersion},"- + " #{policyPO.lastVersion},"- + " #{policyPO.deletedAt})"+ + " #{policyMeta.policyId},"+ + " #{policyMeta.policyName},"+ + " #{policyMeta.policyType},"+ + " #{policyMeta.metalakeId},"+ + " #{policyMeta.auditInfo},"+ + " #{policyMeta.currentVersion},"+ + " #{policyMeta.lastVersion},"+ + " #{policyMeta.deletedAt})"+ " ON CONFLICT (policy_id) DO UPDATE SET"- + " policy_name = #{policyPO.policyName},"- + " policy_type = #{policyPO.policyType},"- + " metalake_id = #{policyPO.metalakeId},"- + " audit_info = #{policyPO.auditInfo},"- + " current_version = #{policyPO.currentVersion},"- + " last_version = #{policyPO.lastVersion},"- + " deleted_at = #{policyPO.deletedAt}";+ + " policy_name = #{policyMeta.policyName},"+ + " policy_type = #{policyMeta.policyType},"+ + " metalake_id = #{policyMeta.metalakeId},"+ + " audit_info = #{policyMeta.auditInfo},"+ + " current_version = #{policyMeta.currentVersion},"+ + " last_version = #{policyMeta.lastVersion},"+ + " deleted_at = #{policyMeta.deletedAt}";}}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyMetadataObjectRelPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyMetadataObjectRelPostgreSQLProvider.javaindex 99ef046f38..a1e8149870 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyMetadataObjectRelPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyMetadataObjectRelPostgreSQLProvider.java@@ -36,7 +36,7 @@ import org.apache.ibatis.annotations.Param;public class PolicyMetadataObjectRelPostgreSQLProviderextends PolicyMetadataObjectRelBaseSQLProvider {private static final String DELETED_AT_NOW_EXPRESSION =- " floor(extract(epoch from(current_timestamp - timestamp '1970-01-01 00:00:00')) * 1000)";+ " CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)";@Overridepublic String softDeletePolicyMetadataObjectRelsByMetalakeAndPolicyName(diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyVersionPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyVersionPostgreSQLProvider.javaindex a9371ec71e..539af52177 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyVersionPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/PolicyVersionPostgreSQLProvider.java@@ -31,8 +31,7 @@ public class PolicyVersionPostgreSQLProvider extends PolicyVersionBaseSQLProvideString metalakeName, String policyName) {return "UPDATE "+ POLICY_VERSION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = (SELECT metalake_id FROM "+ MetalakeMetaMapper.TABLE_NAME+ " mm WHERE mm.metalake_name = #{metalakeName} AND mm.deleted_at = 0)"@@ -56,11 +55,10 @@ public class PolicyVersionPostgreSQLProvider extends PolicyVersionBaseSQLProvideLong policyId, long versionRetentionLine, int limit) {return "UPDATE "+ POLICY_VERSION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE id IN (SELECT id FROM "+ POLICY_VERSION_TABLE_NAME- + " WHERE policy_id = #{policyId} AND version < #{versionRetentionLine}"+ + " WHERE policy_id = #{policyId} AND version <= #{versionRetentionLine}"+ " AND deleted_at = 0 LIMIT #{limit})";}@@ -68,8 +66,7 @@ public class PolicyVersionPostgreSQLProvider extends PolicyVersionBaseSQLProvidepublic String softDeletePolicyVersionsByMetalakeId(Long metalakeId) {return "UPDATE "+ POLICY_VERSION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/RoleMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/RoleMetaPostgreSQLProvider.javaindex f335323556..1dbdcac450 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/RoleMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/RoleMetaPostgreSQLProvider.java@@ -29,8 +29,7 @@ public class RoleMetaPostgreSQLProvider extends RoleMetaBaseSQLProvider {public String softDeleteRoleMetaByRoleId(Long roleId) {return "UPDATE "+ ROLE_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE role_id = #{roleId} AND deleted_at = 0";}@@ -38,8 +37,7 @@ public class RoleMetaPostgreSQLProvider extends RoleMetaBaseSQLProvider {public String softDeleteRoleMetasByMetalakeId(Long metalakeId) {return "UPDATE "+ ROLE_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}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.javaindex 590f036788..7cd6bf3903 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@@ -60,8 +60,7 @@ public class SchemaMetaPostgreSQLProvider extends SchemaMetaBaseSQLProvider {public String softDeleteSchemaMetasBySchemaId(Long schemaId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE schema_id = #{schemaId} AND deleted_at = 0";}@@ -69,8 +68,7 @@ public class SchemaMetaPostgreSQLProvider extends SchemaMetaBaseSQLProvider {public String softDeleteSchemaMetasByMetalakeId(Long metalakeId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}@@ -78,8 +76,7 @@ public class SchemaMetaPostgreSQLProvider extends SchemaMetaBaseSQLProvider {public String softDeleteSchemaMetasByCatalogId(Long catalogId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE catalog_id = #{catalogId} AND deleted_at = 0";}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.javaindex 23d049e2f5..56284fc642 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@@ -39,8 +39,7 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLProreturn "<script>"+ "UPDATE "+ SECURABLE_OBJECT_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE FALSE "+ "<foreach collection='securableObjects' item='item' separator=' '>"+ " OR (metadata_object_id = #{item.metadataObjectId} AND"@@ -53,8 +52,7 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLPropublic String softDeleteSecurableObjectsByRoleId(Long roleId) {return "UPDATE "+ SECURABLE_OBJECT_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE role_id = #{roleId} AND deleted_at = 0";}@@ -62,8 +60,7 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLPropublic String softDeleteSecurableObjectsByMetalakeId(Long metalakeId) {return "UPDATE "+ SECURABLE_OBJECT_TABLE_NAME- + " ob SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " ob SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE exists (SELECT * FROM "+ ROLE_TABLE_NAME+ " ro WHERE ro.metalake_id = #{metalakeId} AND ro.role_id = ob.role_id"@@ -76,8 +73,7 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLPro@Param("metadataObjectType") String metadataObjectType) {return "UPDATE "+ SECURABLE_OBJECT_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metadata_object_id = #{metadataObjectId} AND deleted_at = 0 AND type = #{metadataObjectType}";}@@ -85,8 +81,7 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLPropublic String softDeleteObjectRelsByCatalogId(@Param("catalogId") Long catalogId) {return "UPDATE "+ SECURABLE_OBJECT_TABLE_NAME- + " sect SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " sect SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE sect.deleted_at = 0 AND EXISTS ("+ " SELECT ct.catalog_id FROM "+ CatalogMetaMapper.TABLE_NAME@@ -124,8 +119,7 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLPropublic String softDeleteObjectRelsBySchemaId(@Param("schemaId") Long schemaId) {return "UPDATE "+ SECURABLE_OBJECT_TABLE_NAME- + " sect SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " sect SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE sect.deleted_at = 0 AND EXISTS ("+ " SELECT st.schema_id FROM "+ SchemaMetaMapper.TABLE_NAME@@ -160,7 +154,7 @@ public class SecurableObjectPostgreSQLProvider extends SecurableObjectBaseSQLProreturn "DELETE FROM "+ SECURABLE_OBJECT_TABLE_NAME+ " WHERE id IN (SELECT id FROM "- + ROLE_TABLE_NAME+ + SECURABLE_OBJECT_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/StatisticPostgresSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/StatisticPostgresSQLProvider.javaindex 800e519afc..f99cde946c 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/StatisticPostgresSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/StatisticPostgresSQLProvider.java@@ -27,8 +27,7 @@ import org.apache.gravitino.storage.relational.po.StatisticPO;public class StatisticPostgresSQLProvider extends StatisticBaseSQLProvider {@Overrideprotected String softDeleteSQL() {- return " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)";+ return " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)";}@Overridediff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TableColumnPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TableColumnPostgreSQLProvider.javaindex 2d020bce81..332b18aae5 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TableColumnPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TableColumnPostgreSQLProvider.java@@ -28,8 +28,7 @@ public class TableColumnPostgreSQLProvider extends TableColumnBaseSQLProvider {public String softDeleteColumnsByTableId(@Param("tableId") Long tableId) {return "UPDATE "+ TableColumnMapper.COLUMN_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE table_id = #{tableId} AND deleted_at = 0";}@@ -37,8 +36,7 @@ public class TableColumnPostgreSQLProvider extends TableColumnBaseSQLProvider {public String softDeleteColumnsByMetalakeId(@Param("metalakeId") Long metalakeId) {return "UPDATE "+ TableColumnMapper.COLUMN_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}@@ -46,8 +44,7 @@ public class TableColumnPostgreSQLProvider extends TableColumnBaseSQLProvider {public String softDeleteColumnsByCatalogId(@Param("catalogId") Long catalogId) {return "UPDATE "+ TableColumnMapper.COLUMN_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE catalog_id = #{catalogId} AND deleted_at = 0";}@@ -55,8 +52,7 @@ public class TableColumnPostgreSQLProvider extends TableColumnBaseSQLProvider {public String softDeleteColumnsBySchemaId(@Param("schemaId") Long schemaId) {return "UPDATE "+ TableColumnMapper.COLUMN_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE schema_id = #{schemaId} AND deleted_at = 0";}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.javaindex 01c520c874..f43e817ffb 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@@ -58,8 +58,7 @@ public class TableMetaPostgreSQLProvider extends TableMetaBaseSQLProvider {public String softDeleteTableMetasByTableId(Long tableId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE table_id = #{tableId} AND deleted_at = 0";}@@ -67,8 +66,7 @@ public class TableMetaPostgreSQLProvider extends TableMetaBaseSQLProvider {public String softDeleteTableMetasByMetalakeId(Long metalakeId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}@@ -76,8 +74,7 @@ public class TableMetaPostgreSQLProvider extends TableMetaBaseSQLProvider {public String softDeleteTableMetasByCatalogId(Long catalogId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE catalog_id = #{catalogId} AND deleted_at = 0";}@@ -85,8 +82,7 @@ public class TableMetaPostgreSQLProvider extends TableMetaBaseSQLProvider {public String softDeleteTableMetasBySchemaId(Long schemaId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE schema_id = #{schemaId} AND deleted_at = 0";}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.javaindex 11be90f345..fd5a7fadfd 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@@ -65,4 +65,14 @@ public class TableVersionPostgreSQLProvider extends TableVersionBaseSQLProvider+ " timestamp '1970-01-01 00:00:00')) * 1000)"+ " WHERE table_id = #{tableId} AND version = #{version}";}++ @Override+ public String deleteTableVersionByLegacyTimeline(+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {+ return "DELETE FROM "+ + TABLE_NAME+ + " WHERE table_id IN (SELECT table_id 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/TagMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TagMetaPostgreSQLProvider.javaindex 6fdae6f580..785e124d2c 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TagMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TagMetaPostgreSQLProvider.java@@ -30,8 +30,7 @@ public class TagMetaPostgreSQLProvider extends TagMetaBaseSQLProvider {public String softDeleteTagMetaByMetalakeAndTagName(String metalakeName, String tagName) {return "UPDATE "+ TAG_TABLE_NAME- + " tm SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " tm SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE tm.metalake_id IN ("+ " SELECT mm.metalake_id FROM "+ MetalakeMetaMapper.TABLE_NAME@@ -43,8 +42,7 @@ public class TagMetaPostgreSQLProvider extends TagMetaBaseSQLProvider {public String softDeleteTagMetasByMetalakeId(Long metalakeId) {return "UPDATE "+ TAG_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}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.javaindex 6bdc711e6b..ed7bdf3917 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@@ -40,8 +40,7 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRelString metalakeName, String tagName) {return "UPDATE "+ TAG_METADATA_OBJECT_RELATION_TABLE_NAME- + " te SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " te SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE te.tag_id IN (SELECT tm.tag_id FROM "+ TagMetaMapper.TAG_TABLE_NAME+ " tm WHERE tm.metalake_id IN (SELECT mm.metalake_id FROM "@@ -54,8 +53,7 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRelpublic String softDeleteTagMetadataObjectRelsByMetalakeId(Long metalakeId) {return "UPDATE "+ TAG_METADATA_OBJECT_RELATION_TABLE_NAME- + " te SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " te SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE EXISTS (SELECT * FROM "+ TagMetaMapper.TAG_TABLE_NAME+ " tm WHERE tm.metalake_id = #{metalakeId} AND tm.tag_id = te.tag_id"@@ -68,8 +66,7 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRel@Param("metadataObjectType") String metadataObjectType) {return " UPDATE "+ TAG_METADATA_OBJECT_RELATION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metadata_object_id = #{metadataObjectId} AND deleted_at = 0"+ " AND metadata_object_type = #{metadataObjectType}";}@@ -78,8 +75,7 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRelpublic String softDeleteTagMetadataObjectRelsByCatalogId(@Param("catalogId") Long catalogId) {return " UPDATE "+ TagMetadataObjectRelMapper.TAG_METADATA_OBJECT_RELATION_TABLE_NAME- + " tmt SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " tmt SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE tmt.deleted_at = 0 AND EXISTS ("+ " SELECT ct.catalog_id FROM "+ CatalogMetaMapper.TABLE_NAME@@ -122,8 +118,7 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRelpublic String softDeleteTagMetadataObjectRelsBySchemaId(@Param("schemaId") Long schemaId) {return " UPDATE "+ TagMetadataObjectRelMapper.TAG_METADATA_OBJECT_RELATION_TABLE_NAME- + " tmt SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " tmt SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE tmt.deleted_at = 0 AND EXISTS ("+ " SELECT st.schema_id FROM "+ SchemaMetaMapper.TABLE_NAME@@ -161,8 +156,7 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRelpublic String softDeleteTagMetadataObjectRelsByTableId(@Param("tableId") Long tableId) {return " UPDATE "+ TagMetadataObjectRelMapper.TAG_METADATA_OBJECT_RELATION_TABLE_NAME- + " tmt SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " tmt SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE tmt.deleted_at = 0 AND EXISTS ("+ " SELECT tat.table_id FROM "+ TableMetaMapper.TABLE_NAME@@ -182,8 +176,7 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRelreturn "<script>"+ "UPDATE "+ TAG_METADATA_OBJECT_RELATION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE tag_id IN "+ "<foreach item='tagId' collection='tagIds' open='(' separator=',' close=')'>"+ "#{tagId}"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.javaindex f969043e9a..970b2d1b2f 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@@ -30,8 +30,7 @@ public class TopicMetaPostgreSQLProvider extends TopicMetaBaseSQLProvider {public String softDeleteTopicMetasByTopicId(Long topicId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE topic_id = #{topicId} AND deleted_at = 0";}@@ -39,8 +38,7 @@ public class TopicMetaPostgreSQLProvider extends TopicMetaBaseSQLProvider {public String softDeleteTopicMetasByCatalogId(Long catalogId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE catalog_id = #{catalogId} AND deleted_at = 0";}@@ -48,8 +46,7 @@ public class TopicMetaPostgreSQLProvider extends TopicMetaBaseSQLProvider {public String softDeleteTopicMetasByMetalakeId(Long metalakeId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}@@ -57,8 +54,7 @@ public class TopicMetaPostgreSQLProvider extends TopicMetaBaseSQLProvider {public String softDeleteTopicMetasBySchemaId(Long schemaId) {return "UPDATE "+ TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE schema_id = #{schemaId} AND deleted_at = 0";}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/UserMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/UserMetaPostgreSQLProvider.javaindex f67f33f2a9..73730cafef 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/UserMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/UserMetaPostgreSQLProvider.java@@ -31,8 +31,7 @@ public class UserMetaPostgreSQLProvider extends UserMetaBaseSQLProvider {public String softDeleteUserMetaByUserId(Long userId) {return "UPDATE "+ USER_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE user_id = #{userId} AND deleted_at = 0";}@@ -40,8 +39,7 @@ public class UserMetaPostgreSQLProvider extends UserMetaBaseSQLProvider {public String softDeleteUserMetasByMetalakeId(Long metalakeId) {return "UPDATE "+ USER_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/UserRoleRelPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/UserRoleRelPostgreSQLProvider.javaindex fc311f43f2..7d798a9bad 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/UserRoleRelPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/UserRoleRelPostgreSQLProvider.java@@ -32,8 +32,7 @@ public class UserRoleRelPostgreSQLProvider extends UserRoleRelBaseSQLProvider {public String softDeleteUserRoleRelByUserId(Long userId) {return "UPDATE "+ USER_ROLE_RELATION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE user_id = #{userId} AND deleted_at = 0";}@@ -42,8 +41,7 @@ public class UserRoleRelPostgreSQLProvider extends UserRoleRelBaseSQLProvider {return "<script>"+ "UPDATE "+ USER_ROLE_RELATION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE user_id = #{userId} AND role_id IN ("+ "<foreach collection='roleIds' item='roleId' separator=','>"+ "#{roleId}"@@ -57,8 +55,7 @@ public class UserRoleRelPostgreSQLProvider extends UserRoleRelBaseSQLProvider {public String softDeleteUserRoleRelByMetalakeId(Long metalakeId) {return "UPDATE "+ USER_ROLE_RELATION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE user_id IN (SELECT user_id FROM "+ USER_TABLE_NAME+ " WHERE metalake_id = #{metalakeId} AND deleted_at = 0)"@@ -69,8 +66,7 @@ public class UserRoleRelPostgreSQLProvider extends UserRoleRelBaseSQLProvider {public String softDeleteUserRoleRelByRoleId(Long roleId) {return "UPDATE "+ USER_ROLE_RELATION_TABLE_NAME- + " SET deleted_at = floor(extract(epoch from(current_timestamp -"- + " timestamp '1970-01-01 00:00:00')) * 1000)"+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ " WHERE role_id = #{roleId} AND deleted_at = 0";}diff --git a/core/src/test/java/org/apache/gravitino/storage/TestEntityStorage.java b/core/src/test/java/org/apache/gravitino/storage/TestEntityStorage.javaindex 458a58f18c..57efd5b1f1 100644--- a/core/src/test/java/org/apache/gravitino/storage/TestEntityStorage.java+++ b/core/src/test/java/org/apache/gravitino/storage/TestEntityStorage.java@@ -33,8 +33,6 @@ import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;import static org.apache.gravitino.Configs.VERSION_RETENTION_COUNT;import static org.apache.gravitino.file.Fileset.LOCATION_NAME_UNKNOWN;-import static org.apache.gravitino.storage.relational.TestJDBCBackend.createRoleEntity;-import static org.apache.gravitino.storage.relational.TestJDBCBackend.createUserEntity;import com.github.benmanes.caffeine.cache.Cache;import com.google.common.base.Preconditions;@@ -52,6 +50,7 @@ import java.time.Instant;import java.util.ArrayList;import java.util.Collections;import java.util.List;+import java.util.Map;import java.util.UUID;import java.util.stream.Collectors;import org.apache.commons.io.FileUtils;@@ -105,7 +104,6 @@ import org.apache.gravitino.rel.types.Types;import org.apache.gravitino.storage.relational.RelationalBackend;import org.apache.gravitino.storage.relational.RelationalEntityStore;import org.apache.gravitino.storage.relational.RelationalGarbageCollector;-import org.apache.gravitino.storage.relational.TestJDBCBackend;import org.apache.gravitino.storage.relational.converters.H2ExceptionConverter;import org.apache.gravitino.storage.relational.converters.MySQLExceptionConverter;import org.apache.gravitino.storage.relational.converters.PostgreSQLExceptionConverter;@@ -139,6 +137,8 @@ public class TestEntityStorage {@AfterEachvoid closeSuit() throws IOException {+ // todo: refactor TestEntityStorage to extend TestJDBCBackend, otherwise, each test will start+ // and stop the container suite.ContainerSuite.getInstance().close();}@@ -317,7 +317,7 @@ public class TestEntityStorage {"topic1",auditInfo);ModelEntity model1 =- TestJDBCBackend.createModelEntity(+ createModelEntity(RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema1"),"model1",@@ -326,7 +326,7 @@ public class TestEntityStorage {null,auditInfo);ModelVersionEntity modelVersion1 =- TestJDBCBackend.createModelVersionEntity(+ createModelVersionEntity(model1.nameIdentifier(),0,ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),@@ -710,7 +710,7 @@ public class TestEntityStorage {createTopicEntity(1L, Namespace.of("metalake", "catalog", "schema1"), "topic1", auditInfo);ModelEntity model1 =- TestJDBCBackend.createModelEntity(+ createModelEntity(RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema1"),"model1",@@ -719,7 +719,7 @@ public class TestEntityStorage {null,auditInfo);ModelVersionEntity modelVersion1 =- TestJDBCBackend.createModelVersionEntity(+ createModelVersionEntity(model1.nameIdentifier(),0,ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),@@ -750,7 +750,7 @@ public class TestEntityStorage {createTopicEntity(2L, Namespace.of("metalake", "catalog", "schema2"), "topic1", auditInfo);ModelEntity model1InSchema2 =- TestJDBCBackend.createModelEntity(+ createModelEntity(RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema2"),"model1",@@ -759,7 +759,7 @@ public class TestEntityStorage {null,auditInfo);ModelVersionEntity modelVersion1InSchema2 =- TestJDBCBackend.createModelVersionEntity(+ createModelVersionEntity(model1InSchema2.nameIdentifier(),0,ImmutableMap.of(ModelVersion.URI_NAME_UNKNOWN, "model_path"),@@ -941,7 +941,7 @@ public class TestEntityStorage {// modelModelEntity model1New =- TestJDBCBackend.createModelEntity(+ createModelEntity(RandomIdGenerator.INSTANCE.nextId(),model1.namespace(),model1.name(),@@ -1018,7 +1018,7 @@ public class TestEntityStorage {createTopicEntity(RandomIdGenerator.INSTANCE.nextId(), namespace, "sameName", auditInfo);ModelEntity model1 =- TestJDBCBackend.createModelEntity(+ createModelEntity(RandomIdGenerator.INSTANCE.nextId(),namespace,"sameName",@@ -1709,7 +1709,7 @@ public class TestEntityStorage {store.put(topic1New);ModelEntity model1New =- TestJDBCBackend.createModelEntity(+ createModelEntity(RandomIdGenerator.INSTANCE.nextId(),model1.namespace(),model1.name(),@@ -1911,7 +1911,7 @@ public class TestEntityStorage {store.put(topic1New);ModelEntity model1New =- TestJDBCBackend.createModelEntity(+ createModelEntity(RandomIdGenerator.INSTANCE.nextId(),model1.namespace(),model1.name(),@@ -3215,4 +3215,69 @@ public class TestEntityStorage {throw new RuntimeException(e);}}++ private UserEntity createUserEntity(+ Long id, Namespace namespace, String name, AuditInfo auditInfo) {+ return UserEntity.builder()+ .withId(id)+ .withName(name)+ .withNamespace(namespace)+ .withRoleNames(null)+ .withRoleIds(null)+ .withAuditInfo(auditInfo)+ .build();+ }++ private RoleEntity createRoleEntity(+ Long id, Namespace namespace, String name, AuditInfo auditInfo, String catalogName) {+ SecurableObject securableObject =+ SecurableObjects.ofCatalog(catalogName, Lists.newArrayList(Privileges.UseCatalog.allow()));++ return RoleEntity.builder()+ .withId(id)+ .withName(name)+ .withNamespace(namespace)+ .withProperties(null)+ .withAuditInfo(auditInfo)+ .withSecurableObjects(Lists.newArrayList(securableObject))+ .build();+ }++ private ModelEntity createModelEntity(+ Long id,+ Namespace namespace,+ String name,+ String comment,+ Integer latestVersion,+ Map<String, String> properties,+ AuditInfo auditInfo) {+ return ModelEntity.builder()+ .withId(id)+ .withName(name)+ .withNamespace(namespace)+ .withComment(comment)+ .withLatestVersion(latestVersion)+ .withProperties(properties)+ .withAuditInfo(auditInfo)+ .build();+ }++ private ModelVersionEntity createModelVersionEntity(+ NameIdentifier modelId,+ Integer version,+ Map<String, String> modelUris,+ List<String> aliases,+ String comment,+ Map<String, String> properties,+ AuditInfo auditInfo) {+ return ModelVersionEntity.builder()+ .withModelIdentifier(modelId)+ .withVersion(version)+ .withUris(modelUris)+ .withAliases(aliases)+ .withComment(comment)+ .withProperties(properties)+ .withAuditInfo(auditInfo)+ .build();+ }}diff --git a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.javaindex efe5f7e934..85ff8d0b22 100644--- a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java+++ b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java@@ -18,70 +18,36 @@*/package org.apache.gravitino.storage;-import static org.apache.gravitino.integration.test.util.TestDatabaseName.MYSQL_JDBC_BACKEND;-import static org.apache.gravitino.integration.test.util.TestDatabaseName.PG_JDBC_BACKEND;-import java.io.File;import java.io.IOException;-import java.nio.file.Files;import java.nio.file.Path;import java.sql.Connection;-import java.sql.DriverManager;+import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;+import java.util.ArrayList;import java.util.Arrays;import java.util.Comparator;import java.util.HashMap;+import java.util.List;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;import org.apache.commons.io.FileUtils;-import org.apache.commons.lang3.StringUtils;-import org.apache.gravitino.integration.test.container.MySQLContainer;-import org.apache.gravitino.integration.test.container.PostgreSQLContainer;-import org.apache.gravitino.integration.test.util.BaseIT;-import org.junit.jupiter.api.AfterAll;+import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.BeforeAll;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.io.TempDir;--public class TestSQLScripts extends BaseIT {+import org.junit.jupiter.api.TestTemplate;- private String jdbcBackend;- private Path scriptDir;- @TempDir private File tempDir;- private Map<String, Connection> versionConnections;-- @BeforeAll- public void startIntegrationTest() {- jdbcBackend = System.getenv("jdbcBackend");- Assertions.assertNotNull(jdbcBackend, "jdbcBackend environment variable is not set");+public class TestSQLScripts extends TestJDBCBackend {+ @TestTemplate+ public void testSQLScripts() throws SQLException, IOException {String gravitinoHome = System.getenv("GRAVITINO_HOME");Assertions.assertNotNull(gravitinoHome, "GRAVITINO_HOME environment variable is not set");- scriptDir = Path.of(gravitinoHome, "scripts", jdbcBackend.toLowerCase());- Assertions.assertTrue(Files.exists(scriptDir), "Script directory does not exist: " + scriptDir);- versionConnections = new HashMap<>();- }-- @AfterAll- public void stopIntegrationTest() {- // Close all connections- for (Connection conn : versionConnections.values()) {- if (conn != null) {- try {- conn.close();- } catch (SQLException e) {- // Ignore- }- }- }- versionConnections.clear();- }+ Path scriptDir = Path.of(gravitinoHome, "scripts", backendType.toLowerCase());- @Test- public void testSQLScripts() throws SQLException {File[] scriptFiles = scriptDir.toFile().listFiles();Assertions.assertNotNull(scriptFiles, "No script files found in " + scriptDir);// Sort files to ensure the correct execution order (schema -> upgrade)@@ -89,12 +55,13 @@ public class TestSQLScripts extends BaseIT {// A map to store connections for different schema versionsPattern schemaPattern =- Pattern.compile("schema-([\\d.]+)-" + jdbcBackend.toLowerCase() + "\\.sql");+ Pattern.compile("schema-([\\d.]+)-" + backendType.toLowerCase() + "\\.sql");Pattern upgradePattern =- Pattern.compile("upgrade-([\\d.]+)-to-([\\d.]+)-" + jdbcBackend.toLowerCase() + "\\.sql");+ Pattern.compile("upgrade-([\\d.]+)-to-([\\d.]+)-" + backendType.toLowerCase() + "\\.sql");Pattern metricsPattern =- Pattern.compile("iceberg-metrics-schema-([\\d.]+)-" + jdbcBackend.toLowerCase() + "\\.sql");+ Pattern.compile("iceberg-metrics-schema-([\\d.]+)-" + backendType.toLowerCase() + "\\.sql");+ Map<String, List<File>> versionScrips = new HashMap<>();for (File scriptFile : scriptFiles) {Matcher schemaMatcher = schemaPattern.matcher(scriptFile.getName());Matcher upgradeMatcher = upgradePattern.matcher(scriptFile.getName());@@ -102,80 +69,92 @@ public class TestSQLScripts extends BaseIT {if (schemaMatcher.matches()) {String version = schemaMatcher.group(1);- String dbName = "schema_" + version.replace('.', '_');-- Connection conn = getSQLConnection(jdbcBackend, dbName);- Assertions.assertDoesNotThrow(- () -> executeSQLScript(conn, scriptFile),- "Failed to execute schema script for version " + version);- versionConnections.put(version, conn);+ versionScrips.computeIfAbsent(version, k -> new ArrayList<>()).add(scriptFile);} else if (upgradeMatcher.matches()) {String fromVersion = upgradeMatcher.group(1);+ Assertions.assertTrue(+ versionScrips.containsKey(fromVersion), "No schema script found for " + fromVersion);- Connection conn = versionConnections.get(fromVersion);- Assertions.assertNotNull(- conn, "No existing database connection found for version " + fromVersion);- Assertions.assertDoesNotThrow(- () -> executeSQLScript(conn, scriptFile),- "Failed to execute upgrade script" + " in file " + scriptFile.getName());} else if (metricsMatcher.matches()) {- // ignore iceberg metrics scripts for now+ String version = metricsMatcher.group(1);+ versionScrips.computeIfAbsent(version, k -> new ArrayList<>()).add(scriptFile);+} else {Assertions.fail("Unrecognized script file name: " + scriptFile.getName());}}- }- private void executeSQLScript(Connection connection, File scriptFile) throws IOException {- String sqlContent = FileUtils.readFileToString(scriptFile, "UTF-8");- Arrays.stream(sqlContent.split(";"))- .map(String::trim)- .filter(s -> !s.isEmpty())- .forEach(- sql -> {- try (Statement stmt = connection.createStatement()) {- stmt.execute(sql);- } catch (SQLException e) {- throw new RuntimeException("Failed to execute SQL: " + sql, e);+ for (List<File> scripts : versionScrips.values()) {+ dropAllTables();+ for (File scriptFile : scripts) {+ String sqlContent = FileUtils.readFileToString(scriptFile, "UTF-8");+ List<String> ddls =+ Arrays.stream(sqlContent.split(";"))+ .map(String::trim)+ .filter(s -> !s.isEmpty())+ .toList();++ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true)) {+ try (Connection connection = sqlSession.getConnection()) {+ try (Statement statement = connection.createStatement()) {+ for (String ddl : ddls) {+ Assertions.assertDoesNotThrow(+ () -> statement.execute(ddl),+ "Failed to execute DDL in file " + scriptFile.getName() + "ddl: " + ddl);}- });+ }+ }+ }+ }+ }}- private Connection getSQLConnection(String jdbcBackend, String dBName) throws SQLException {- if ("h2".equalsIgnoreCase(jdbcBackend)) {- // Use a temporary directory for the database files- String dbPath = new File(tempDir, dBName).getAbsolutePath();- // AUTO_SERVER=TRUE allows multiple connections to the same database in the same process- String url = String.format("jdbc:h2:file:%s;MODE=MYSQL;AUTO_SERVER=TRUE", dbPath);- return DriverManager.getConnection(url, "sa", "");-- } else if ("mysql".equalsIgnoreCase(jdbcBackend)) {- containerSuite.startMySQLContainer(MYSQL_JDBC_BACKEND);- MySQLContainer mySQLContainer = containerSuite.getMySQLContainer();- String mysqlUrl = mySQLContainer.getJdbcUrl(MYSQL_JDBC_BACKEND);- Connection connection =- DriverManager.getConnection(- StringUtils.substring(mysqlUrl, 0, mysqlUrl.lastIndexOf("/")), "root", "root");- Statement statement = connection.createStatement();- statement.execute("create database if not exists " + dBName);- connection.setCatalog(dBName);- return connection;-- } else if ("PostgreSQL".equalsIgnoreCase(jdbcBackend)) {- containerSuite.startPostgreSQLContainer(PG_JDBC_BACKEND);- PostgreSQLContainer pgContainer = containerSuite.getPostgreSQLContainer();- String pgUrlWithoutSchema = pgContainer.getJdbcUrl(PG_JDBC_BACKEND);- Connection connection =- DriverManager.getConnection(- pgUrlWithoutSchema, pgContainer.getUsername(), pgContainer.getPassword());- connection.setCatalog(PG_JDBC_BACKEND.toString().toLowerCase());- Statement statement = connection.createStatement();- statement.execute("create schema if not exists " + dBName);- connection.setSchema(dBName);- return connection;+ private void dropAllTables() throws SQLException {+ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true)) {+ try (Connection connection = sqlSession.getConnection()) {+ if ("postgresql".equals(backendType)) {+ dropAllTablesForPostgreSQL(connection);+ } else {+ dropAllTablesForMySQLCompatible(connection);+ }+ }+ }+ }++ private void dropAllTablesForMySQLCompatible(Connection connection) throws SQLException {+ try (Statement statement = connection.createStatement()) {+ String query = "SHOW TABLES";+ List<String> tableList = new ArrayList<>();+ try (ResultSet rs = statement.executeQuery(query)) {+ while (rs.next()) {+ tableList.add(rs.getString(1));+ }+ }+ for (String table : tableList) {+ statement.execute("DROP TABLE " + table);+ }+ }+ }++ private void dropAllTablesForPostgreSQL(Connection connection) throws SQLException {+ String query =+ "SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema()";+ List<String> tableList = new ArrayList<>();+ try (ResultSet rs = connection.createStatement().executeQuery(query)) {+ while (rs.next()) {+ tableList.add(rs.getString(1));+ }+ }++ if (tableList.isEmpty()) {+ return;+ }++ for (String table : tableList) {+ connection.createStatement().execute("DROP TABLE " + table);}- Assertions.fail("Unsupported JDBC backend: " + jdbcBackend);- return null;}}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/BackendTestExtension.java b/core/src/test/java/org/apache/gravitino/storage/relational/BackendTestExtension.javanew file mode 100644index 0000000000..95906540a3--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/storage/relational/BackendTestExtension.java@@ -0,0 +1,231 @@+/*+ * 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;++import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;+import static org.apache.gravitino.Configs.DEFAULT_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;+import static org.apache.gravitino.Configs.DEFAULT_RELATIONAL_JDBC_BACKEND_MAX_WAIT_MILLISECONDS;+import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;+import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;+import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD;+import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL;+import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_USER;+import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_MILLISECONDS;++import java.io.File;+import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Paths;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.UUID;+import java.util.concurrent.ConcurrentHashMap;+import java.util.stream.Stream;+import org.apache.commons.io.FileUtils;+import org.apache.gravitino.Config;+import org.apache.gravitino.Configs;+import org.apache.gravitino.integration.test.util.BaseIT;+import org.apache.gravitino.storage.relational.service.EntityIdService;+import org.junit.jupiter.api.extension.AfterAllCallback;+import org.junit.jupiter.api.extension.BeforeAllCallback;+import org.junit.jupiter.api.extension.BeforeEachCallback;+import org.junit.jupiter.api.extension.Extension;+import org.junit.jupiter.api.extension.ExtensionContext;+import org.junit.jupiter.api.extension.TestTemplateInvocationContext;+import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider;+import org.mockito.Mockito;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class BackendTestExtension+ implements TestTemplateInvocationContextProvider, BeforeAllCallback, AfterAllCallback {++ private static final Logger LOG = LoggerFactory.getLogger(BackendTestExtension.class);+ private static final String DOCKER_TEST_FLAG = "dockerTest";++ private static final ExtensionContext.Namespace NAMESPACE =+ ExtensionContext.Namespace.create(BackendTestExtension.class);+ private static final String STORE_KEY = "BACKEND_MAP";++ @Override+ public void beforeAll(ExtensionContext context) {+ // Initialize a Map and store it at the Class level.+ // Key: backendType ("h2", "mysql"...), Value: RelationalBackend instance+ context.getStore(NAMESPACE).put(STORE_KEY, new ConcurrentHashMap<String, RelationalBackend>());+ }++ @Override+ @SuppressWarnings("unchecked")+ public void afterAll(ExtensionContext context) {+ // Test class ended, close all started Backend+ ConcurrentHashMap<String, RelationalBackend> map =+ (ConcurrentHashMap<String, RelationalBackend>) context.getStore(NAMESPACE).get(STORE_KEY);++ if (map != null) {+ map.forEach(+ (type, backend) -> {+ try {+ LOG.info("Tearing down backend: {}", type);+ backend.close();+ // H2 special cleaning logic+ if ("h2".equals(type) && backend instanceof H2BackendWrapper) {+ ((H2BackendWrapper) backend).cleanFile();+ }+ } catch (Exception e) {+ LOG.error("Failed to close backend {}", type, e);+ }+ });+ }+ }++ @Override+ public boolean supportsTestTemplate(ExtensionContext context) {+ return true;+ }++ @Override+ public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts(+ ExtensionContext context) {+ List<String> backendsToTest = new ArrayList<>();+ backendsToTest.add("h2"); // Always test with H2++ String dockerTest = System.getenv(DOCKER_TEST_FLAG);+ if ("true".equalsIgnoreCase(dockerTest)) {+ backendsToTest.add("mysql");+ backendsToTest.add("postgresql");+ LOG.info("Running tests with H2, MySQL, and PostgreSQL backends.");+ } else {+ LOG.info(+ "Running tests with H2 backend only. Set env var 'dockerTest=true' to include all backends.");+ }++ return backendsToTest.stream().map(BackendInvocationContext::new);+ }++ private static class BackendInvocationContext implements TestTemplateInvocationContext {+ private final String backendType;++ public BackendInvocationContext(String backendType) {+ this.backendType = backendType;+ }++ @Override+ public String getDisplayName(int invocationIndex) {+ return String.format("[%s Backend]", backendType.toUpperCase());+ }++ @Override+ public List<Extension> getAdditionalExtensions() {+ return Collections.singletonList(new BackendSetupCallback(backendType));+ }+ }++ private static class BackendSetupCallback implements BeforeEachCallback {+ private final String backendType;+ private final BaseIT baseIT = new BaseIT();++ public BackendSetupCallback(String backendType) {+ this.backendType = backendType;+ }++ @Override+ public void beforeEach(ExtensionContext context) throws Exception {++ // Lazy loading: If the backend of this type has not started, start it+ RelationalBackend backend = startBackend(backendType);++ // Inject into the test instance+ Object testInstance = context.getRequiredTestInstance();+ if (testInstance instanceof TestJDBCBackend) {+ LOG.info("Injecting {} backend into test instance", backendType);+ ((TestJDBCBackend) testInstance).setBackend(backend);+ ((TestJDBCBackend) testInstance).setBackendType(backendType);+ }+ }++ private RelationalBackend startBackend(String type) throws Exception {+ LOG.info("Initializing backend resource: {}", type);+ Config config = Mockito.mock(Config.class);+ Mockito.when(config.get(Configs.ENTITY_STORE)).thenReturn(Configs.RELATIONAL_ENTITY_STORE);+ Mockito.when(config.get(Configs.ENTITY_RELATIONAL_STORE))+ .thenReturn(DEFAULT_ENTITY_RELATIONAL_STORE);+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS))+ .thenReturn(DEFAULT_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS);+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_MILLISECONDS))+ .thenReturn(DEFAULT_RELATIONAL_JDBC_BACKEND_MAX_WAIT_MILLISECONDS);++ RelationalBackend backend = new JDBCBackend();+ if ("mysql".equals(type)) {+ String url = baseIT.startAndInitMySQLBackend();+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_URL)).thenReturn(url);+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_USER)).thenReturn("root");+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD)).thenReturn("root");+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER))+ .thenReturn("com.mysql.cj.jdbc.Driver");+ } else if ("postgresql".equals(type)) {+ String url = baseIT.startAndInitPGBackend();+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_URL)).thenReturn(url);+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_USER)).thenReturn("root");+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD)).thenReturn("root");+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER))+ .thenReturn("org.postgresql.Driver");+ } else {+ // H2 Logic+ String uuid = UUID.randomUUID().toString().replace("-", "");+ String jdbcPath = "/tmp/gravitino_jdbc_test_h2_" + uuid;+ File dir = new File(jdbcPath);+ if (!dir.exists() && !dir.mkdirs()) throw new IOException("Create dir failed");++ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_URL))+ .thenReturn(String.format("jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL", jdbcPath));+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_USER)).thenReturn("root");+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD)).thenReturn("123456");+ Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER)).thenReturn("org.h2.Driver");++ // Wrap it with a Wrapper so that files can be deleted during the clean process+ backend = new H2BackendWrapper(config, jdbcPath);+ }++ // close the backend before initializing to make sure the singleton sqlSession+ // has been cleared.+ backend.close();+ backend.initialize(config);+ EntityIdService.initialize(new RelationalEntityStoreIdResolver());+ return backend;+ }+ }++ // A simple Wrapper solves the H2 file cleanup issue.+ public static class H2BackendWrapper extends JDBCBackend {+ private final String path;++ public H2BackendWrapper(Config config, String path) {+ this.path = path;+ super.initialize(config);+ }++ public void cleanFile() throws IOException {+ if (Files.exists(Paths.get(path))) {+ FileUtils.deleteDirectory(new File(path));+ }+ }+ }+}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestJDBCBackend.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestJDBCBackend.javaindex cbe019d2f7..5faa1a71ee 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestJDBCBackend.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestJDBCBackend.java@@ -18,36 +18,14 @@*/package org.apache.gravitino.storage.relational;-import static org.apache.gravitino.Configs.DEFAULT_ENTITY_RELATIONAL_STORE;-import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER;-import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS;-import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD;-import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL;-import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_USER;-import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_MILLISECONDS;-import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;-import static org.apache.gravitino.Configs.ENTITY_STORE;-import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;-import static org.apache.gravitino.SupportsRelationOperations.Type.OWNER_REL;import static org.apache.gravitino.file.Fileset.LOCATION_NAME_UNKNOWN;-import static org.junit.Assert.assertNotNull;-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;-import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertFalse;-import static org.junit.jupiter.api.Assertions.assertThrows;-import static org.junit.jupiter.api.Assertions.assertTrue;import com.google.common.collect.ImmutableMap;import com.google.common.collect.ImmutableSet;import com.google.common.collect.Lists;-import java.io.File;import java.io.IOException;-import java.lang.invoke.MethodHandles;-import java.nio.file.Files;-import java.nio.file.Paths;import java.sql.Connection;import java.sql.ResultSet;-import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Statement;import java.time.Instant;@@ -55,1271 +33,146 @@ import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;-import java.util.Set;-import java.util.UUID;import org.apache.gravitino.Catalog;-import org.apache.gravitino.Config;-import org.apache.gravitino.Configs;import org.apache.gravitino.Entity;-import org.apache.gravitino.Entity.EntityType;-import org.apache.gravitino.EntityAlreadyExistsException;import org.apache.gravitino.MetadataObject;-import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;-import org.apache.gravitino.authorization.AuthorizationUtils;import org.apache.gravitino.authorization.Privileges;import org.apache.gravitino.authorization.SecurableObject;import org.apache.gravitino.authorization.SecurableObjects;import org.apache.gravitino.file.Fileset;+import org.apache.gravitino.integration.test.util.CloseContainerExtension;+import org.apache.gravitino.integration.test.util.PrintFuncNameExtension;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.FilesetEntity;import org.apache.gravitino.meta.GroupEntity;import org.apache.gravitino.meta.ModelEntity;-import org.apache.gravitino.meta.ModelVersionEntity;import org.apache.gravitino.meta.PolicyEntity;import org.apache.gravitino.meta.RoleEntity;import org.apache.gravitino.meta.SchemaEntity;import org.apache.gravitino.meta.SchemaVersion;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.policy.Policy;import org.apache.gravitino.policy.PolicyContents;import org.apache.gravitino.storage.RandomIdGenerator;-import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;-import org.apache.gravitino.storage.relational.mapper.GroupMetaMapper;-import org.apache.gravitino.storage.relational.mapper.UserMetaMapper;-import org.apache.gravitino.storage.relational.service.CatalogMetaService;-import org.apache.gravitino.storage.relational.service.EntityIdService;-import org.apache.gravitino.storage.relational.service.MetalakeMetaService;-import org.apache.gravitino.storage.relational.service.RoleMetaService;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.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.junit.jupiter.api.TestInstance;-import org.junit.jupiter.api.condition.EnabledIf;-import org.mockito.Mockito;+import org.junit.jupiter.api.extension.ExtendWith;@TestInstance(TestInstance.Lifecycle.PER_CLASS)-// Avoid re-executing tests in subclasses-@EnabledIf("isDirectlyRunningThisClass")-public class TestJDBCBackend {- private static final Set<MetadataObject.Type> SUPPORTED_OBJECT_TYPES =- ImmutableSet.of(- MetadataObject.Type.CATALOG,- MetadataObject.Type.SCHEMA,- MetadataObject.Type.TABLE,- MetadataObject.Type.FILESET,- MetadataObject.Type.MODEL,- MetadataObject.Type.TOPIC);-- private final String JDBC_STORE_PATH =- "/tmp/gravitino_jdbc_entityStore_" + UUID.randomUUID().toString().replace("-", "");- private final String DB_DIR = JDBC_STORE_PATH + "/testdb";- private final String H2_FILE = DB_DIR + ".mv.db";- private final Config config = Mockito.mock(Config.class);- public final ImmutableMap<String, String> RELATIONAL_BACKENDS =- ImmutableMap.of(- Configs.DEFAULT_ENTITY_RELATIONAL_STORE, JDBCBackend.class.getCanonicalName());+@ExtendWith({+ BackendTestExtension.class,+ PrintFuncNameExtension.class,+ CloseContainerExtension.class+})+public abstract class TestJDBCBackend {+ protected static final AuditInfo AUDIT_INFO =+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();++ protected String backendType;protected RelationalBackend backend;- static boolean isDirectlyRunningThisClass() {- return MethodHandles.lookup().lookupClass() == TestJDBCBackend.class;- }-- @BeforeAll- public void setup() {- File dir = new File(DB_DIR);- dir.deleteOnExit();- if (dir.exists() || !dir.isDirectory()) {- dir.delete();- }- dir.mkdirs();- Mockito.when(config.get(ENTITY_STORE)).thenReturn(RELATIONAL_ENTITY_STORE);- Mockito.when(config.get(ENTITY_RELATIONAL_STORE)).thenReturn(DEFAULT_ENTITY_RELATIONAL_STORE);- Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_URL))- .thenReturn(String.format("jdbc:h2:file:%s;DB_CLOSE_DELAY=-1;MODE=MYSQL", DB_DIR));- Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_USER)).thenReturn("root");- Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD)).thenReturn("123456");- Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER)).thenReturn("org.h2.Driver");- Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_MAX_CONNECTIONS)).thenReturn(100);- Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_MILLISECONDS)).thenReturn(1000L);-- String backendName = config.get(ENTITY_RELATIONAL_STORE);- String className =- RELATIONAL_BACKENDS.getOrDefault(backendName, Configs.DEFAULT_ENTITY_RELATIONAL_STORE);-- try {- backend = (RelationalBackend) Class.forName(className).getDeclaredConstructor().newInstance();- backend.initialize(config);- EntityIdService.initialize(new RelationalEntityStoreIdResolver());- } catch (Exception e) {- throw new RuntimeException(- "Failed to create and initialize RelationalBackend by name: " + backendName, e);- }+ public void setBackend(RelationalBackend backend) {+ this.backend = backend;}- @AfterAll- public void tearDown() throws IOException {- dropAllTables();- backend.close();- File dir = new File(DB_DIR);- if (dir.exists()) {- Files.delete(Paths.get(DB_DIR));- }-- Files.delete(Paths.get(H2_FILE));- Files.delete(Paths.get(JDBC_STORE_PATH));+ public void setBackendType(String backendType) {+ this.backendType = backendType;}@BeforeEach- public void init() {+ public void init() throws SQLException {truncateAllTables();}- private static void truncateAllTables() {+ private void truncateAllTables() throws SQLException {try (SqlSession sqlSession =SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true)) {try (Connection connection = sqlSession.getConnection()) {try (Statement statement = connection.createStatement()) {- String query = "SHOW TABLES";- List<String> tableList = new ArrayList<>();- try (ResultSet rs = statement.executeQuery(query)) {- while (rs.next()) {- tableList.add(rs.getString(1));+ if ("postgresql".equalsIgnoreCase(backendType)) {+ truncateAllTablesForPostgreSQL(connection);+ } else {+ String query = "SHOW TABLES";+ List<String> tableList = new ArrayList<>();+ try (ResultSet rs = statement.executeQuery(query)) {+ while (rs.next()) {+ tableList.add(rs.getString(1));+ }+ }+ for (String table : tableList) {+ statement.execute("TRUNCATE TABLE " + table);}- }- for (String table : tableList) {- statement.execute("TRUNCATE TABLE " + table);}}}- } catch (SQLException e) {- throw new RuntimeException("Truncate table failed", e);}}- private static void dropAllTables() {- try (SqlSession sqlSession =- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true)) {- try (Connection connection = sqlSession.getConnection()) {- try (Statement statement = connection.createStatement()) {- String query = "SHOW TABLES";- List<String> tableList = new ArrayList<>();- try (ResultSet rs = statement.executeQuery(query)) {- while (rs.next()) {- tableList.add(rs.getString(1));- }- }- for (String table : tableList) {- statement.execute("DROP TABLE " + table);- }+ private void truncateAllTablesForPostgreSQL(Connection connection) throws SQLException {+ List<String> tableList = new ArrayList<>();+ try (Statement statement = connection.createStatement()) {+ String query =+ "SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema()";+ try (ResultSet rs = statement.executeQuery(query)) {+ while (rs.next()) {+ tableList.add(rs.getString(1));}}- } catch (SQLException e) {- throw new RuntimeException("Drop table failed", e);- }- }-- @Test- public void testInsertAlreadyExistsException() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();-- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), "metalake", auditInfo);- BaseMetalake metalakeCopy =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), "metalake", auditInfo);- backend.insert(metalake, false);- assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(metalakeCopy, false));-- PolicyEntity policy =- createPolicy(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofPolicy("metalake"),- "policy",- auditInfo);- PolicyEntity policyCopy =- createPolicy(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofPolicy("metalake"),- "policy",- auditInfo);- backend.insert(policy, false);- assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(policyCopy, false));-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofCatalog("metalake"),- "catalog",- auditInfo);- CatalogEntity catalogCopy =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofCatalog("metalake"),- "catalog",- auditInfo);- backend.insert(catalog, false);- assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(catalogCopy, false));-- SchemaEntity schema =- createSchemaEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofSchema("metalake", "catalog"),- "schema",- auditInfo);- SchemaEntity schemaCopy =- createSchemaEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofSchema("metalake", "catalog"),- "schema",- auditInfo);- backend.insert(schema, false);- assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(schemaCopy, false));-- TableEntity table =- createTableEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofTable("metalake", "catalog", "schema"),- "table",- auditInfo);- TableEntity tableCopy =- createTableEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofTable("metalake", "catalog", "schema"),- "table",- auditInfo);- backend.insert(table, false);- assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(tableCopy, false));-- FilesetEntity fileset =- createFilesetEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofFileset("metalake", "catalog", "schema"),- "fileset",- auditInfo);- FilesetEntity filesetCopy =- createFilesetEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofFileset("metalake", "catalog", "schema"),- "fileset",- auditInfo);- backend.insert(fileset, false);- assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(filesetCopy, false));-- TopicEntity topic =- createTopicEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofFileset("metalake", "catalog", "schema"),- "topic",- auditInfo);- TopicEntity topicCopy =- createTopicEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofFileset("metalake", "catalog", "schema"),- "topic",- auditInfo);- backend.insert(topic, false);- assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(topicCopy, false));-- ModelEntity model =- createModelEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofModel("metalake", "catalog", "schema"),- "model",- "model comment",- 1,- ImmutableMap.of("key", "value"),- auditInfo);- ModelEntity modelCopy =- createModelEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofModel("metalake", "catalog", "schema"),- "model",- "model comment",- 1,- ImmutableMap.of("key", "value"),- auditInfo);-- assertDoesNotThrow(() -> backend.insert(model, false));- assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(modelCopy, false));- assertDoesNotThrow(() -> backend.insert(modelCopy, true));- }-- @Test- public void testUpdateAlreadyExistsException() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();-- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), "metalake", auditInfo);- BaseMetalake metalakeCopy =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), "metalake1", auditInfo);- backend.insert(metalake, false);- backend.insert(metalakeCopy, false);- assertThrows(- EntityAlreadyExistsException.class,- () ->- backend.update(- metalakeCopy.nameIdentifier(),- Entity.EntityType.METALAKE,- e -> createBaseMakeLake(metalakeCopy.id(), "metalake", auditInfo)));-- PolicyEntity policy =- createPolicy(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofPolicy("metalake"),- "policy",- auditInfo);- PolicyEntity policy1 =- createPolicy(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofPolicy("metalake"),- "policy1",- auditInfo);- backend.insert(policy, false);- backend.insert(policy1, false);- assertThrows(- EntityAlreadyExistsException.class,- () ->- backend.update(- policy1.nameIdentifier(),- Entity.EntityType.POLICY,- e -> createPolicy(policy1.id(), policy1.namespace(), "policy", auditInfo)));-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofCatalog("metalake"),- "catalog",- auditInfo);- CatalogEntity catalogCopy =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofCatalog("metalake"),- "catalog1",- auditInfo);- backend.insert(catalog, false);- backend.insert(catalogCopy, false);- assertThrows(- EntityAlreadyExistsException.class,- () ->- backend.update(- catalogCopy.nameIdentifier(),- Entity.EntityType.CATALOG,- e ->- createCatalog(- catalogCopy.id(), catalogCopy.namespace(), "catalog", auditInfo)));-- SchemaEntity schema =- createSchemaEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofSchema("metalake", "catalog"),- "schema",- auditInfo);- SchemaEntity schemaCopy =- createSchemaEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofSchema("metalake", "catalog"),- "schema1",- auditInfo);- backend.insert(schema, false);- backend.insert(schemaCopy, false);- assertThrows(- EntityAlreadyExistsException.class,- () ->- backend.update(- schemaCopy.nameIdentifier(),- Entity.EntityType.SCHEMA,- e ->- createSchemaEntity(- schemaCopy.id(), schemaCopy.namespace(), "schema", auditInfo)));-- TableEntity table =- createTableEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofTable("metalake", "catalog", "schema"),- "table",- auditInfo);- TableEntity tableCopy =- createTableEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofTable("metalake", "catalog", "schema"),- "table1",- auditInfo);- backend.insert(table, false);- backend.insert(tableCopy, false);- assertThrows(- EntityAlreadyExistsException.class,- () ->- backend.update(- tableCopy.nameIdentifier(),- Entity.EntityType.TABLE,- e -> createTableEntity(tableCopy.id(), tableCopy.namespace(), "table", auditInfo)));-- FilesetEntity fileset =- createFilesetEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofFileset("metalake", "catalog", "schema"),- "fileset",- auditInfo);- FilesetEntity filesetCopy =- createFilesetEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofFileset("metalake", "catalog", "schema"),- "fileset1",- auditInfo);- backend.insert(fileset, false);- backend.insert(filesetCopy, false);- assertThrows(- EntityAlreadyExistsException.class,- () ->- backend.update(- filesetCopy.nameIdentifier(),- Entity.EntityType.FILESET,- e ->- createFilesetEntity(- filesetCopy.id(), filesetCopy.namespace(), "fileset", auditInfo)));- TopicEntity topic =- createTopicEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofFileset("metalake", "catalog", "schema"),- "topic",- auditInfo);- TopicEntity topicCopy =- createTopicEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofFileset("metalake", "catalog", "schema"),- "topic1",- auditInfo);- backend.insert(topic, false);- backend.insert(topicCopy, false);- assertThrows(- EntityAlreadyExistsException.class,- () ->- backend.update(- topicCopy.nameIdentifier(),- Entity.EntityType.TOPIC,- e -> createTopicEntity(topicCopy.id(), topicCopy.namespace(), "topic", auditInfo)));- }-- @Test- void testUpdateMetalakeWithNullableComment() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();-- BaseMetalake metalake =- BaseMetalake.builder()- .withId(RandomIdGenerator.INSTANCE.nextId())- .withName("metalake" + RandomIdGenerator.INSTANCE.nextId())- .withAuditInfo(auditInfo)- .withComment(null)- .withProperties(null)- .withVersion(SchemaVersion.V_0_1)- .build();-- backend.insert(metalake, false);-- backend.update(- metalake.nameIdentifier(),- Entity.EntityType.METALAKE,- e ->- BaseMetalake.builder()- .withId(metalake.id())- .withName(metalake.name())- .withAuditInfo(auditInfo)- .withComment("comment")- .withProperties(metalake.properties())- .withVersion(metalake.getVersion())- .build());-- BaseMetalake updatedMetalake =- backend.get(metalake.nameIdentifier(), Entity.EntityType.METALAKE);- Assertions.assertNotNull(updatedMetalake.comment());-- backend.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE, false);- }-- @Test- void testUpdateCatalogWithNullableComment() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();-- String metalakeName = "metalake" + RandomIdGenerator.INSTANCE.nextId();- BaseMetalake metalake =- BaseMetalake.builder()- .withId(RandomIdGenerator.INSTANCE.nextId())- .withName(metalakeName)- .withAuditInfo(auditInfo)- .withComment("")- .withProperties(null)- .withVersion(SchemaVersion.V_0_1)- .build();- backend.insert(metalake, false);-- CatalogEntity catalog =- CatalogEntity.builder()- .withId(RandomIdGenerator.INSTANCE.nextId())- .withNamespace(NamespaceUtil.ofCatalog(metalakeName))- .withName("catalog")- .withAuditInfo(auditInfo)- .withComment(null)- .withProperties(null)- .withType(Catalog.Type.RELATIONAL)- .withProvider("test")- .build();-- backend.insert(catalog, false);-- backend.update(- catalog.nameIdentifier(),- Entity.EntityType.CATALOG,- e ->- CatalogEntity.builder()- .withId(catalog.id())- .withNamespace(catalog.namespace())- .withName(catalog.name())- .withAuditInfo(auditInfo)- .withComment("comment")- .withProperties(catalog.getProperties())- .withType(Catalog.Type.RELATIONAL)- .withProvider("test")- .build());-- CatalogEntity updatedCatalog = backend.get(catalog.nameIdentifier(), Entity.EntityType.CATALOG);- Assertions.assertNotNull(updatedCatalog.getComment());-- backend.delete(catalog.nameIdentifier(), Entity.EntityType.CATALOG, false);- backend.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE, false);- }-- @Test- public void testMetaLifeCycleFromCreationToDeletion() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();-- // meta data creation- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), "metalake", auditInfo);- backend.insert(metalake, false);-- PolicyEntity policy =- createPolicy(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofPolicy("metalake"),- "policy",- auditInfo);- backend.insert(policy, false);- // update policy enabled and version- PolicyEntity policyV2 =- PolicyEntity.builder()- .withId(policy.id())- .withNamespace(policy.namespace())- .withName(policy.name())- .withPolicyType(policy.policyType())- .withComment(policy.comment())- .withEnabled(!policy.enabled())- .withContent(policy.content())- .withAuditInfo(auditInfo)- .build();- backend.update(policy.nameIdentifier(), Entity.EntityType.POLICY, e -> policyV2);-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofCatalog("metalake"),- "catalog",- auditInfo);- backend.insert(catalog, false);-- SchemaEntity schema =- createSchemaEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofSchema("metalake", "catalog"),- "schema",- auditInfo);- backend.insert(schema, false);-- TableEntity table =- createTableEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofTable("metalake", "catalog", "schema"),- "table",- auditInfo);- backend.insert(table, false);-- FilesetEntity fileset =- createFilesetEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofFileset("metalake", "catalog", "schema"),- "fileset",- auditInfo);- backend.insert(fileset, false);-- TopicEntity topic =- createTopicEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofFileset("metalake", "catalog", "schema"),- "topic",- auditInfo);- backend.insert(topic, false);-- ModelEntity model =- createModelEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofModel("metalake", "catalog", "schema"),- "model",- "model comment",- 1,- ImmutableMap.of("key", "value"),- auditInfo);- backend.insert(model, false);-- // update fileset properties and version- FilesetEntity filesetV2 =- createFilesetEntity(- fileset.id(),- NamespaceUtil.ofFileset("metalake", "catalog", "schema"),- "fileset",- auditInfo);- filesetV2.properties().put("version", "2");- backend.update(fileset.nameIdentifier(), Entity.EntityType.FILESET, e -> filesetV2);-- RoleEntity role =- createRoleEntity(- RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace("metalake"),- "role",- auditInfo,- "catalog");- backend.insert(role, false);-- UserEntity user =- createUserEntity(- RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofUserNamespace("metalake"),- "user",- auditInfo,- Lists.newArrayList(role.name()),- Lists.newArrayList(role.id()));- backend.insert(user, false);-- GroupEntity group =- createGroupEntity(- RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofGroupNamespace("metalake"),- "group",- auditInfo,- Lists.newArrayList(role.name()),- Lists.newArrayList(role.id()));- backend.insert(group, false);-- TagEntity tag =- TagEntity.builder()- .withId(RandomIdGenerator.INSTANCE.nextId())- .withName("tag")- .withNamespace(NamespaceUtil.ofTag("metalake"))- .withComment("tag comment")- .withAuditInfo(auditInfo)- .build();- backend.insert(tag, false);-- // another meta data creation- BaseMetalake anotherMetaLake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), "another-metalake", auditInfo);- backend.insert(anotherMetaLake, false);-- PolicyEntity anotherPolicy =- createPolicy(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofPolicy("another-metalake"),- "another-policy",- auditInfo);- backend.insert(anotherPolicy, false);- // update another policy enabled and version- PolicyEntity anotherPolicyV2 =- PolicyEntity.builder()- .withId(anotherPolicy.id())- .withNamespace(anotherPolicy.namespace())- .withName(anotherPolicy.name())- .withPolicyType(anotherPolicy.policyType())- .withComment(anotherPolicy.comment())- .withEnabled(!anotherPolicy.enabled())- .withContent(anotherPolicy.content())- .withAuditInfo(auditInfo)- .build();- backend.update(anotherPolicy.nameIdentifier(), Entity.EntityType.POLICY, e -> anotherPolicyV2);- // update another policy comment and version- PolicyEntity anotherPolicyV3 =- PolicyEntity.builder()- .withId(anotherPolicy.id())- .withNamespace(anotherPolicy.namespace())- .withName(anotherPolicy.name())- .withPolicyType(anotherPolicy.policyType())- .withComment("v3")- .withEnabled(anotherPolicyV2.enabled())- .withContent(anotherPolicy.content())- .withAuditInfo(auditInfo)- .build();- backend.update(anotherPolicy.nameIdentifier(), Entity.EntityType.POLICY, e -> anotherPolicyV3);-- CatalogEntity anotherCatalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofCatalog("another-metalake"),- "another-catalog",- auditInfo);- backend.insert(anotherCatalog, false);-- SchemaEntity anotherSchema =- createSchemaEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofSchema("another-metalake", "another-catalog"),- "another-schema",- auditInfo);- backend.insert(anotherSchema, false);-- FilesetEntity anotherFileset =- createFilesetEntity(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofFileset("another-metalake", "another-catalog", "another-schema"),- "anotherFileset",- auditInfo);- backend.insert(anotherFileset, false);-- FilesetEntity anotherFilesetV2 =- createFilesetEntity(- anotherFileset.id(),- NamespaceUtil.ofFileset("another-metalake", "another-catalog", "another-schema"),- "anotherFileset",- auditInfo);- anotherFilesetV2.properties().put("version", "2");- backend.update(- anotherFileset.nameIdentifier(), Entity.EntityType.FILESET, e -> anotherFilesetV2);-- FilesetEntity anotherFilesetV3 =- createFilesetEntity(- anotherFileset.id(),- NamespaceUtil.ofFileset("another-metalake", "another-catalog", "another-schema"),- "anotherFileset",- auditInfo);- anotherFilesetV3.properties().put("version", "3");- backend.update(- anotherFileset.nameIdentifier(), Entity.EntityType.FILESET, e -> anotherFilesetV3);-- RoleEntity anotherRole =- createRoleEntity(- RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace("another-metalake"),- "another-role",- auditInfo,- "another-catalog");- backend.insert(anotherRole, false);-- UserEntity anotherUser =- createUserEntity(- RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofUserNamespace("another-metalake"),- "another-user",- auditInfo,- Lists.newArrayList(anotherRole.name()),- Lists.newArrayList(anotherRole.id()));- backend.insert(anotherUser, false);-- GroupEntity anotherGroup =- createGroupEntity(- RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofGroupNamespace("another-metalake"),- "another-group",- auditInfo,- Lists.newArrayList(anotherRole.name()),- Lists.newArrayList(anotherRole.id()));- backend.insert(anotherGroup, false);-- TagEntity anotherTagEntity =- TagEntity.builder()- .withId(RandomIdGenerator.INSTANCE.nextId())- .withName("another-tag")- .withNamespace(NamespaceUtil.ofTag("another-metalake"))- .withComment("another-tag comment")- .withAuditInfo(auditInfo)- .build();- backend.insert(anotherTagEntity, false);-- // meta data list- List<BaseMetalake> metaLakes =- backend.list(metalake.namespace(), Entity.EntityType.METALAKE, true);- assertTrue(metaLakes.contains(metalake));-- List<PolicyEntity> policies = backend.list(policy.namespace(), Entity.EntityType.POLICY, true);- assertFalse(policies.contains(policy));- assertTrue(policies.contains(policyV2));- assertEquals(policyV2.enabled(), policies.get(policies.indexOf(policyV2)).enabled());-- List<CatalogEntity> catalogs =- backend.list(catalog.namespace(), Entity.EntityType.CATALOG, true);- assertTrue(catalogs.contains(catalog));-- assertEquals(- 1,- SessionUtils.doWithCommitAndFetchResult(- CatalogMetaMapper.class,- mapper -> mapper.listCatalogPOsByMetalakeName(metalake.name()))- .size());-- List<SchemaEntity> schemas = backend.list(schema.namespace(), Entity.EntityType.SCHEMA, true);- assertTrue(schemas.contains(schema));-- List<TableEntity> tables = backend.list(table.namespace(), Entity.EntityType.TABLE, true);- assertTrue(tables.contains(table));-- List<FilesetEntity> filesets =- backend.list(fileset.namespace(), Entity.EntityType.FILESET, true);- assertFalse(filesets.contains(fileset));- assertTrue(filesets.contains(filesetV2));- assertEquals("2", filesets.get(filesets.indexOf(filesetV2)).properties().get("version"));-- List<TopicEntity> topics = backend.list(topic.namespace(), Entity.EntityType.TOPIC, true);- assertTrue(topics.contains(topic));-- List<ModelEntity> models = backend.list(model.namespace(), Entity.EntityType.MODEL, true);- assertTrue(models.contains(model));-- RoleEntity roleEntity = backend.get(role.nameIdentifier(), Entity.EntityType.ROLE);- assertEquals(role, roleEntity);- assertEquals(1, RoleMetaService.getInstance().listRolesByUserId(user.id()).size());- assertEquals(1, RoleMetaService.getInstance().listRolesByGroupId(group.id()).size());-- CatalogEntity catalogEntity = backend.get(catalog.nameIdentifier(), Entity.EntityType.CATALOG);- assertEquals(catalog, catalogEntity);- assertNotNull(- CatalogMetaService.getInstance()- .getCatalogPOByName(catalogEntity.namespace().level(0), catalog.name()));- assertEquals(- catalog.id(),- CatalogMetaService.getInstance()- .getCatalogIdByName(catalog.namespace().level(0), catalog.name()));-- UserEntity userEntity = backend.get(user.nameIdentifier(), Entity.EntityType.USER);- assertEquals(user, userEntity);- assertEquals(- 1,- SessionUtils.doWithCommitAndFetchResult(- UserMetaMapper.class, mapper -> mapper.listUsersByRoleId(role.id()))- .size());-- GroupEntity groupEntity = backend.get(group.nameIdentifier(), Entity.EntityType.GROUP);- assertEquals(group, groupEntity);- assertEquals(- 1,- SessionUtils.doWithCommitAndFetchResult(- GroupMetaMapper.class, mapper -> mapper.listGroupsByRoleId(role.id()))- .size());-- TagEntity tagEntity = backend.get(tag.nameIdentifier(), Entity.EntityType.TAG);- assertEquals(tag, tagEntity);- List<TagEntity> tags = backend.list(tag.namespace(), Entity.EntityType.TAG, true);- assertTrue(tags.contains(tag));- assertEquals(1, tags.size());-- backend.insertRelation(- OWNER_REL,- metalake.nameIdentifier(),- metalake.type(),- user.nameIdentifier(),- user.type(),- true);-- backend.insertRelation(- OWNER_REL,- anotherMetaLake.nameIdentifier(),- anotherMetaLake.type(),- anotherUser.nameIdentifier(),- anotherUser.type(),- true);-- backend.insertRelation(- OWNER_REL,- catalog.nameIdentifier(),- catalog.type(),- user.nameIdentifier(),- user.type(),- true);-- backend.insertRelation(- OWNER_REL,- schema.nameIdentifier(),- schema.type(),- user.nameIdentifier(),- user.type(),- true);-- backend.insertRelation(- OWNER_REL, table.nameIdentifier(), table.type(), user.nameIdentifier(), user.type(), true);-- backend.insertRelation(- OWNER_REL, topic.nameIdentifier(), topic.type(), user.nameIdentifier(), user.type(), true);-- backend.insertRelation(- OWNER_REL,- fileset.nameIdentifier(),- fileset.type(),- user.nameIdentifier(),- user.type(),- true);-- backend.insertRelation(- OWNER_REL, role.nameIdentifier(), role.type(), user.nameIdentifier(), user.type(), true);-- // meta data soft delete- backend.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE, true);-- assertEquals(- 0,- SessionUtils.doWithCommitAndFetchResult(- CatalogMetaMapper.class,- mapper -> mapper.listCatalogPOsByMetalakeName(metalake.name()))- .size());-- // check existence after soft delete- assertFalse(backend.exists(metalake.nameIdentifier(), Entity.EntityType.METALAKE));- assertTrue(backend.exists(anotherMetaLake.nameIdentifier(), Entity.EntityType.METALAKE));-- assertFalse(backend.exists(policy.nameIdentifier(), Entity.EntityType.POLICY));- assertTrue(backend.exists(anotherPolicy.nameIdentifier(), Entity.EntityType.POLICY));-- assertFalse(backend.exists(catalog.nameIdentifier(), Entity.EntityType.CATALOG));- assertTrue(backend.exists(anotherCatalog.nameIdentifier(), Entity.EntityType.CATALOG));-- assertFalse(backend.exists(schema.nameIdentifier(), Entity.EntityType.SCHEMA));- assertTrue(backend.exists(anotherSchema.nameIdentifier(), Entity.EntityType.SCHEMA));-- assertFalse(backend.exists(fileset.nameIdentifier(), Entity.EntityType.FILESET));- assertTrue(backend.exists(anotherFileset.nameIdentifier(), Entity.EntityType.FILESET));-- assertFalse(backend.exists(table.nameIdentifier(), Entity.EntityType.TABLE));- assertFalse(backend.exists(topic.nameIdentifier(), Entity.EntityType.TOPIC));- assertFalse(backend.exists(model.nameIdentifier(), Entity.EntityType.MODEL));-- assertFalse(backend.exists(role.nameIdentifier(), Entity.EntityType.ROLE));- assertEquals(0, RoleMetaService.getInstance().listRolesByUserId(user.id()).size());- assertEquals(0, RoleMetaService.getInstance().listRolesByGroupId(group.id()).size());- assertTrue(backend.exists(anotherRole.nameIdentifier(), Entity.EntityType.ROLE));-- assertFalse(backend.exists(user.nameIdentifier(), Entity.EntityType.USER));- assertEquals(- 0,- SessionUtils.doWithCommitAndFetchResult(- UserMetaMapper.class, mapper -> mapper.listUsersByRoleId(role.id()))- .size());- assertTrue(backend.exists(anotherUser.nameIdentifier(), Entity.EntityType.USER));-- assertFalse(backend.exists(group.nameIdentifier(), Entity.EntityType.GROUP));- assertEquals(- 0,- SessionUtils.doWithCommitAndFetchResult(- GroupMetaMapper.class, mapper -> mapper.listGroupsByRoleId(role.id()))- .size());- assertTrue(backend.exists(anotherGroup.nameIdentifier(), Entity.EntityType.GROUP));-- assertFalse(backend.exists(tag.nameIdentifier(), Entity.EntityType.TAG));- assertTrue(backend.exists(anotherTagEntity.nameIdentifier(), Entity.EntityType.TAG));-- // check legacy record after soft delete- assertTrue(legacyRecordExistsInDB(metalake.id(), Entity.EntityType.METALAKE));- assertTrue(legacyRecordExistsInDB(policy.id(), Entity.EntityType.POLICY));- assertTrue(legacyRecordExistsInDB(catalog.id(), Entity.EntityType.CATALOG));- assertTrue(legacyRecordExistsInDB(schema.id(), Entity.EntityType.SCHEMA));- assertTrue(legacyRecordExistsInDB(table.id(), Entity.EntityType.TABLE));- assertTrue(legacyRecordExistsInDB(topic.id(), Entity.EntityType.TOPIC));- assertTrue(legacyRecordExistsInDB(model.id(), Entity.EntityType.MODEL));- assertTrue(legacyRecordExistsInDB(fileset.id(), Entity.EntityType.FILESET));- assertTrue(legacyRecordExistsInDB(role.id(), Entity.EntityType.ROLE));- assertTrue(legacyRecordExistsInDB(user.id(), Entity.EntityType.USER));- assertTrue(legacyRecordExistsInDB(group.id(), Entity.EntityType.GROUP));- assertEquals(2, countRoleRels(role.id()));- assertEquals(7, countOwnerRel(metalake.id()));- assertEquals(1, countOwnerRel(anotherMetaLake.id()));- assertEquals(2, countRoleRels(anotherRole.id()));- assertEquals(2, listFilesetVersions(fileset.id()).size());- assertEquals(3, listFilesetVersions(anotherFileset.id()).size());- assertEquals(2, listPolicyVersions(policy.id()).size());- assertEquals(3, listPolicyVersions(anotherPolicy.id()).size());- assertTrue(legacyRecordExistsInDB(tag.id(), Entity.EntityType.TAG));-- // meta data hard delete- for (Entity.EntityType entityType : Entity.EntityType.values()) {- backend.hardDeleteLegacyData(entityType, Instant.now().toEpochMilli() + 1000);- }- assertFalse(legacyRecordExistsInDB(metalake.id(), Entity.EntityType.METALAKE));- assertFalse(legacyRecordExistsInDB(catalog.id(), Entity.EntityType.CATALOG));- assertFalse(legacyRecordExistsInDB(schema.id(), Entity.EntityType.SCHEMA));- assertFalse(legacyRecordExistsInDB(table.id(), Entity.EntityType.TABLE));- assertFalse(legacyRecordExistsInDB(fileset.id(), Entity.EntityType.FILESET));- assertFalse(legacyRecordExistsInDB(topic.id(), Entity.EntityType.TOPIC));- assertFalse(legacyRecordExistsInDB(model.id(), Entity.EntityType.MODEL));- assertFalse(legacyRecordExistsInDB(role.id(), Entity.EntityType.ROLE));- assertFalse(legacyRecordExistsInDB(user.id(), Entity.EntityType.USER));- assertFalse(legacyRecordExistsInDB(group.id(), Entity.EntityType.GROUP));- assertFalse(legacyRecordExistsInDB(policy.id(), Entity.EntityType.POLICY));- assertEquals(0, countRoleRels(role.id()));- assertEquals(2, countRoleRels(anotherRole.id()));- assertEquals(0, listFilesetVersions(fileset.id()).size());- assertEquals(0, listPolicyVersions(policy.id()).size());- assertFalse(legacyRecordExistsInDB(tag.id(), Entity.EntityType.TAG));- assertEquals(0, countOwnerRel(metalake.id()));- assertEquals(1, countOwnerRel(anotherMetaLake.id()));-- // soft delete for old version fileset- assertEquals(3, listFilesetVersions(anotherFileset.id()).size());- for (Entity.EntityType entityType : Entity.EntityType.values()) {- backend.deleteOldVersionData(entityType, 1);- }- Map<Integer, Long> versionDeletedMap = listFilesetVersions(anotherFileset.id());- assertEquals(3, versionDeletedMap.size());- assertEquals(1, versionDeletedMap.values().stream().filter(value -> value == 0L).count());- assertEquals(2, versionDeletedMap.values().stream().filter(value -> value != 0L).count());-- // hard delete for old version fileset- backend.hardDeleteLegacyData(Entity.EntityType.FILESET, Instant.now().toEpochMilli() + 1000);- assertEquals(1, listFilesetVersions(anotherFileset.id()).size());+ if (tableList.isEmpty()) {+ return;+ }- // soft delete for old version policy- assertEquals(3, listPolicyVersions(anotherPolicy.id()).size());- for (Entity.EntityType entityType : Entity.EntityType.values()) {- backend.deleteOldVersionData(entityType, 1);+ // Merge all TRUNCATE operations into a single DO block to improve efficiency+ StringBuilder pgTruncateCommand = new StringBuilder("DO $$ BEGIN\n");+ for (String table : tableList) {+ pgTruncateCommand.append(+ String.format("TRUNCATE TABLE %s RESTART IDENTITY CASCADE;", table));+ }+ pgTruncateCommand.append("END $$;");+ statement.execute(pgTruncateCommand.toString());}- Map<Integer, Long> versionDeletedMap2 = listPolicyVersions(anotherPolicy.id());- assertEquals(3, versionDeletedMap2.size());- assertEquals(1, versionDeletedMap2.values().stream().filter(value -> value == 0L).count());- assertEquals(2, versionDeletedMap2.values().stream().filter(value -> value != 0L).count());}- @Test- public void testGetRoleIdByMetalakeIdAndName() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- String metalakeName = "testMetalake";- String catalogName = "catalog";- String roleNameWithDot = "role.with.dot";- String roleNameWithoutDot = "roleWithoutDot";-+ protected BaseMetalake createAndInsertMakeLake(String metalakeName) throws IOException {BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, AUDIT_INFO);backend.insert(metalake, false);-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofCatalog(metalakeName),- catalogName,- auditInfo);- backend.insert(catalog, false);-- RoleEntity roleWithDot =- createRoleEntity(- RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),- roleNameWithDot,- auditInfo,- catalogName);- backend.insert(roleWithDot, false);-- RoleEntity roleWithoutDot =- createRoleEntity(- RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),- roleNameWithoutDot,- auditInfo,- catalogName);- backend.insert(roleWithoutDot, false);-- Long metalakeId = MetalakeMetaService.getInstance().getMetalakeIdByName(metalakeName);-- Long roleIdWithDot =- RoleMetaService.getInstance().getRoleIdByMetalakeIdAndName(metalakeId, roleNameWithDot);- assertEquals(roleWithDot.id(), roleIdWithDot);-- Long roleIdWithoutDot =- RoleMetaService.getInstance().getRoleIdByMetalakeIdAndName(metalakeId, roleNameWithoutDot);- assertEquals(roleWithoutDot.id(), roleIdWithoutDot);+ return metalake;}- @Test- public void testInsertRelationWithDotInRoleName() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- String metalakeName = "testMetalake";- String catalogName = "catalog";- String roleNameWithDot = "role.with.dot";-- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);-+ protected CatalogEntity createAndInsertCatalog(String metalakeName, String catalogName)+ throws IOException {CatalogEntity catalog =createCatalog(RandomIdGenerator.INSTANCE.nextId(),- NamespaceUtil.ofCatalog(metalakeName),+ Namespace.of(metalakeName),catalogName,- auditInfo);+ AUDIT_INFO);backend.insert(catalog, false);-- RoleEntity role =- createRoleEntity(- RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),- roleNameWithDot,- auditInfo,- catalogName);- backend.insert(role, false);-- UserEntity user =- createUserEntity(- RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofUserNamespace(metalakeName),- "user",- auditInfo);- backend.insert(user, false);-- backend.insertRelation(- OWNER_REL, role.nameIdentifier(), role.type(), user.nameIdentifier(), user.type(), true);- assertEquals(1, countActiveOwnerRel(user.id()));+ return catalog;}- @Test- void testUpdateAndDropLanceTable() throws IOException, InterruptedException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();-- String metalakeName = "metalake" + RandomIdGenerator.INSTANCE.nextId();- BaseMetalake metalake =- BaseMetalake.builder()- .withId(RandomIdGenerator.INSTANCE.nextId())- .withName(metalakeName)- .withAuditInfo(auditInfo)- .withComment(null)- .withProperties(null)- .withVersion(SchemaVersion.V_0_1)- .build();- backend.insert(metalake, false);-- CatalogEntity catalog =- CatalogEntity.builder()- .withId(RandomIdGenerator.INSTANCE.nextId())- .withNamespace(NamespaceUtil.ofCatalog(metalakeName))- .withName("catalog")- .withAuditInfo(auditInfo)- .withComment(null)- .withProperties(null)- .withType(Catalog.Type.RELATIONAL)- .withProvider("generic-lakehouse")- .build();-- backend.insert(catalog, false);-+ protected SchemaEntity createAndInsertSchema(+ String metalakeName, String catalogName, String schemaName) throws IOException {SchemaEntity schema =- SchemaEntity.builder()- .withId(RandomIdGenerator.INSTANCE.nextId())- .withNamespace(NamespaceUtil.ofSchema(metalakeName, catalog.name()))- .withName("schema")- .withAuditInfo(auditInfo)- .withComment(null)- .withProperties(null)- .build();-+ createSchemaEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ Namespace.of(metalakeName, catalogName),+ schemaName,+ AUDIT_INFO);backend.insert(schema, false);-- TableEntity table =- TableEntity.builder()- .withId(RandomIdGenerator.INSTANCE.nextId())- .withNamespace(NamespaceUtil.ofTable(metalakeName, catalog.name(), schema.name()))- .withName("table")- .withAuditInfo(auditInfo)- .withComment(null)- .withProperties(ImmutableMap.of("format", "lance", "location", "/tmp/test/lance"))- .build();-- backend.insert(table, false);-- TableEntity fetchedTable = backend.get(table.nameIdentifier(), Entity.EntityType.TABLE);- Assertions.assertEquals("lance", fetchedTable.properties().get("format"));-- TableEntity updatedTable =- TableEntity.builder()- .withId(table.id())- .withNamespace(table.namespace())- .withName(table.name())- .withAuditInfo(auditInfo)- .withComment("update comment")- .withProperties(ImmutableMap.of("format", "LANCE", "location", "/tmp/test/lance"))- .build();-- backend.update(table.nameIdentifier(), EntityType.TABLE, e -> updatedTable);- Thread.sleep(1000);- long now = System.currentTimeMillis();-- // For update lance table, we will do the following things- // 1. Update info in table table_meta;- // 2. Soft drop info in the table table_version_info with an old version.- // 3. Insert new version info in the table table_version_info.- // Let us check it.- int tableInfoCount =- countTableVersionInfoRow(- String.format(- "SELECT count(*) FROM table_version_info WHERE table_id = %d AND deleted_at = 0",- table.id()));- Assertions.assertEquals(1, tableInfoCount);- int tableInfoDeletedCount =- countTableVersionInfoRow(- String.format(- "SELECT count(*) FROM table_version_info WHERE table_id = %d AND deleted_at != 0",- table.id()));- Assertions.assertEquals(1, tableInfoDeletedCount);-- // Now try to clean up old version data- int deletedCount = backend.hardDeleteLegacyData(Entity.EntityType.TABLE, now);- // Only one old version data should be cleaned up in table version info table.- Assertions.assertEquals(1, deletedCount);-- // Try to drop the table- backend.delete(table.nameIdentifier(), Entity.EntityType.TABLE, false);-- Thread.sleep(1000);- now = System.currentTimeMillis();- // After drop, there should be one more deleted record in table_version_info- int deleteCountNow = backend.hardDeleteLegacyData(Entity.EntityType.TABLE, now);- // One row from table_meta and one row from table_version_info should be cleaned up.- Assertions.assertEquals(2, deleteCountNow);- }-- private int countTableVersionInfoRow(String sql) {- try (SqlSession sqlSession =- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);- Connection connection = sqlSession.getConnection();- Statement statement = connection.createStatement();- ResultSet rs = statement.executeQuery(sql)) {- while (rs.next()) {- return rs.getInt(1);- }- } catch (SQLException e) {- throw new RuntimeException("SQL execution failed", e);- }- return 0;+ return schema;}- private boolean legacyRecordExistsInDB(Long id, Entity.EntityType entityType) {+ protected boolean legacyRecordExistsInDB(Long id, Entity.EntityType entityType) {String tableName;String idColumnName;@@ -1391,7 +244,7 @@ public class TestJDBCBackend {}}- private Map<Integer, Long> listFilesetVersions(Long filesetId) {+ protected Map<Integer, Long> listFilesetVersions(Long filesetId) {Map<Integer, Long> versionDeletedTime = new HashMap<>();try (SqlSession sqlSession =SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);@@ -1411,7 +264,7 @@ public class TestJDBCBackend {return versionDeletedTime;}- private Map<Integer, Long> listPolicyVersions(Long policyId) {+ protected Map<Integer, Long> listPolicyVersions(Long policyId) {Map<Integer, Long> versionDeletedTime = new HashMap<>();try (SqlSession sqlSession =SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);@@ -1431,32 +284,7 @@ public class TestJDBCBackend {return versionDeletedTime;}- private Integer countRoleRels(Long roleId) {- int count = 0;- try (SqlSession sqlSession =- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);- Connection connection = sqlSession.getConnection();- Statement statement1 = connection.createStatement();- ResultSet rs1 =- statement1.executeQuery(- String.format("SELECT count(*) FROM user_role_rel WHERE role_id = %d", roleId));- Statement statement2 = connection.createStatement();- ResultSet rs2 =- statement2.executeQuery(- String.format("SELECT count(*) FROM group_role_rel WHERE role_id = %d", roleId))) {- while (rs1.next()) {- count += rs1.getInt(1);- }- while (rs2.next()) {- count += rs2.getInt(1);- }- } catch (SQLException e) {- throw new RuntimeException("SQL execution failed", e);- }- return count;- }-- private Integer countOwnerRel(Long metalakeId) {+ protected Integer countOwnerRel(Long metalakeId) {try (SqlSession sqlSession =SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);Connection connection = sqlSession.getConnection();@@ -1475,166 +303,6 @@ public class TestJDBCBackend {}}- protected Integer countAllObjectRel(Long roleId) {- try (SqlSession sqlSession =- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);- Connection connection = sqlSession.getConnection();- Statement statement1 = connection.createStatement();- ResultSet rs1 =- statement1.executeQuery(- String.format(- "SELECT count(*) FROM role_meta_securable_object WHERE role_id = %d",- roleId))) {- if (rs1.next()) {- return rs1.getInt(1);- } else {- throw new RuntimeException("Doesn't contain data");- }- } catch (SQLException se) {- throw new RuntimeException("SQL execution failed", se);- }- }-- protected Integer countActiveObjectRel(Long roleId) {- try (SqlSession sqlSession =- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);- Connection connection = sqlSession.getConnection();- Statement statement1 = connection.createStatement();- ResultSet rs1 =- statement1.executeQuery(- String.format(- "SELECT count(*) FROM role_meta_securable_object WHERE role_id = %d AND deleted_at = 0",- roleId))) {- if (rs1.next()) {- return rs1.getInt(1);- } else {- throw new RuntimeException("Doesn't contain data");- }- } catch (SQLException se) {- throw new RuntimeException("SQL execution failed", se);- }- }-- protected Integer countAllStats(Long metalakeId) {- try (SqlSession sqlSession =- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);- Connection connection = sqlSession.getConnection();- Statement statement1 = connection.createStatement();- ResultSet rs1 =- statement1.executeQuery(- String.format(- "SELECT count(*) FROM statistic_meta WHERE metalake_id = %d", metalakeId))) {- if (rs1.next()) {- return rs1.getInt(1);- } else {- throw new RuntimeException("Doesn't contain data");- }- } catch (SQLException se) {- throw new RuntimeException("SQL execution failed", se);- }- }-- protected Integer countActiveStats(Long metalakeId) {- try (SqlSession sqlSession =- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);- Connection connection = sqlSession.getConnection();- Statement statement1 = connection.createStatement();- ResultSet rs1 =- statement1.executeQuery(- String.format(- "SELECT count(*) FROM statistic_meta WHERE metalake_id = %d AND deleted_at = 0",- metalakeId))) {- if (rs1.next()) {- return rs1.getInt(1);- } else {- throw new RuntimeException("Doesn't contain data");- }- } catch (SQLException se) {- throw new RuntimeException("SQL execution failed", se);- }- }-- protected Integer testStats(Long metalakeId) {- try (SqlSession sqlSession =- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);- Connection connection = sqlSession.getConnection();- Statement statement1 = connection.createStatement();- ResultSet rs1 =- statement1.executeQuery(- String.format(- "SELECT * FROM statistic_meta WHERE metalake_id = %d AND deleted_at = 0",- metalakeId))) {- ResultSetMetaData metaData = rs1.getMetaData();- int columnCount = metaData.getColumnCount();- while (rs1.next()) {- for (int index = 0; index < columnCount; index++) {- String columnName = metaData.getColumnName(index + 1);- Object value = rs1.getObject(index + 1);- System.out.printf("Column: %s, Value: %s%n", columnName, value);- }- }- } catch (SQLException se) {- throw new RuntimeException("SQL execution failed", se);- }- return 1;- }-- protected Integer countAllTagRel(Long tagId) {- try (SqlSession sqlSession =- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);- Connection connection = sqlSession.getConnection();- Statement statement1 = connection.createStatement();- ResultSet rs1 =- statement1.executeQuery(- String.format("SELECT count(*) FROM tag_relation_meta WHERE tag_id = %d", tagId))) {- if (rs1.next()) {- return rs1.getInt(1);- } else {- throw new RuntimeException("Doesn't contain data");- }- } catch (SQLException se) {- throw new RuntimeException("SQL execution failed", se);- }- }-- protected Integer countActiveTagRel(Long tagId) {- try (SqlSession sqlSession =- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);- Connection connection = sqlSession.getConnection();- Statement statement1 = connection.createStatement();- ResultSet rs1 =- statement1.executeQuery(- String.format(- "SELECT count(*) FROM tag_relation_meta WHERE tag_id = %d AND deleted_at = 0",- tagId))) {- if (rs1.next()) {- return rs1.getInt(1);- } else {- throw new RuntimeException("Doesn't contain data");- }- } catch (SQLException se) {- throw new RuntimeException("SQL execution failed", se);- }- }-- protected Integer countAllOwnerRel(Long ownerId) {- try (SqlSession sqlSession =- SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);- Connection connection = sqlSession.getConnection();- Statement statement1 = connection.createStatement();- ResultSet rs1 =- statement1.executeQuery(- String.format("SELECT count(*) FROM owner_meta WHERE owner_id = %d", ownerId))) {- if (rs1.next()) {- return rs1.getInt(1);- } else {- throw new RuntimeException("Doesn't contain data");- }- } catch (SQLException se) {- throw new RuntimeException("SQL execution failed", se);- }- }-protected Integer countActiveOwnerRel(long ownerId) {try (SqlSession sqlSession =SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);@@ -1655,7 +323,7 @@ public class TestJDBCBackend {}}- public static BaseMetalake createBaseMakeLake(Long id, String name, AuditInfo auditInfo) {+ protected BaseMetalake createBaseMakeLake(Long id, String name, AuditInfo auditInfo) {return BaseMetalake.builder().withId(id).withName(name)@@ -1666,7 +334,7 @@ public class TestJDBCBackend {.build();}- public static CatalogEntity createCatalog(+ protected CatalogEntity createCatalog(Long id, Namespace namespace, String name, AuditInfo auditInfo) {return CatalogEntity.builder().withId(id)@@ -1680,7 +348,7 @@ public class TestJDBCBackend {.build();}- public static PolicyEntity createPolicy(Long id, Namespace ns, String name, AuditInfo auditInfo) {+ protected PolicyEntity createPolicy(Long id, Namespace ns, String name, AuditInfo auditInfo) {return PolicyEntity.builder().withId(id).withNamespace(ns)@@ -1689,12 +357,21 @@ public class TestJDBCBackend {.withComment("").withEnabled(true).withContent(- PolicyContents.custom(ImmutableMap.of("filed1", 123), SUPPORTED_OBJECT_TYPES, null))+ PolicyContents.custom(+ ImmutableMap.of("filed1", 123),+ ImmutableSet.of(+ MetadataObject.Type.CATALOG,+ MetadataObject.Type.SCHEMA,+ MetadataObject.Type.TABLE,+ MetadataObject.Type.FILESET,+ MetadataObject.Type.MODEL,+ MetadataObject.Type.TOPIC),+ null)).withAuditInfo(auditInfo).build();}- public static SchemaEntity createSchemaEntity(+ protected SchemaEntity createSchemaEntity(Long id, Namespace namespace, String name, AuditInfo auditInfo) {return SchemaEntity.builder().withId(id)@@ -1706,7 +383,7 @@ public class TestJDBCBackend {.build();}- public static TableEntity createTableEntity(+ protected TableEntity createTableEntity(Long id, Namespace namespace, String name, AuditInfo auditInfo) {return TableEntity.builder().withId(id)@@ -1716,7 +393,7 @@ public class TestJDBCBackend {.build();}- public static FilesetEntity createFilesetEntity(+ protected FilesetEntity createFilesetEntity(Long id, Namespace namespace, String name, AuditInfo auditInfo) {return FilesetEntity.builder().withId(id)@@ -1730,7 +407,7 @@ public class TestJDBCBackend {.build();}- public static TopicEntity createTopicEntity(+ protected TopicEntity createTopicEntity(Long id, Namespace namespace, String name, AuditInfo auditInfo) {return TopicEntity.builder().withId(id)@@ -1742,7 +419,7 @@ public class TestJDBCBackend {.build();}- public static UserEntity createUserEntity(+ protected UserEntity createUserEntity(Long id, Namespace namespace, String name, AuditInfo auditInfo) {return UserEntity.builder().withId(id)@@ -1754,7 +431,7 @@ public class TestJDBCBackend {.build();}- public static UserEntity createUserEntity(+ protected UserEntity createUserEntity(Long id,Namespace namespace,String name,@@ -1771,7 +448,7 @@ public class TestJDBCBackend {.build();}- public static RoleEntity createRoleEntity(+ protected RoleEntity createRoleEntity(Long id, Namespace namespace, String name, AuditInfo auditInfo, String catalogName) {SecurableObject securableObject =SecurableObjects.ofCatalog(catalogName, Lists.newArrayList(Privileges.UseCatalog.allow()));@@ -1786,19 +463,7 @@ public class TestJDBCBackend {.build();}- public static GroupEntity createGroupEntity(- Long id, Namespace namespace, String name, AuditInfo auditInfo) {- return GroupEntity.builder()- .withId(id)- .withName(name)- .withNamespace(namespace)- .withRoleNames(null)- .withRoleIds(null)- .withAuditInfo(auditInfo)- .build();- }-- public static GroupEntity createGroupEntity(+ protected GroupEntity createGroupEntity(Long id,Namespace namespace,String name,@@ -1815,19 +480,7 @@ public class TestJDBCBackend {.build();}- public static RoleEntity createRoleEntity(- Long id,- Namespace namespace,- String name,- AuditInfo auditInfo,- SecurableObject securableObject,- Map<String, String> properties) {-- return createRoleEntity(- id, namespace, name, auditInfo, Lists.newArrayList(securableObject), properties);- }-- public static RoleEntity createRoleEntity(+ protected RoleEntity createRoleEntity(Long id,Namespace namespace,String name,@@ -1844,7 +497,7 @@ public class TestJDBCBackend {.build();}- public static ModelEntity createModelEntity(+ protected ModelEntity createModelEntity(Long id,Namespace namespace,String name,@@ -1863,46 +516,11 @@ public class TestJDBCBackend {.build();}- public static ModelVersionEntity createModelVersionEntity(- NameIdentifier modelId,- Integer version,- Map<String, String> modelUris,- List<String> aliases,- String comment,- Map<String, String> properties,- AuditInfo auditInfo) {- return ModelVersionEntity.builder()- .withModelIdentifier(modelId)- .withVersion(version)- .withUris(modelUris)- .withAliases(aliases)- .withComment(comment)- .withProperties(properties)- .withAuditInfo(auditInfo)- .build();- }-protected void createParentEntities(String metalakeName, String catalogName, String schemaName, AuditInfo auditInfo)throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName),- catalogName,- auditInfo);- backend.insert(catalog, false);-- SchemaEntity schema =- createSchemaEntity(- RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name()),- schemaName,- auditInfo);- backend.insert(schema, false);+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);+ createAndInsertSchema(metalakeName, catalogName, schemaName);}}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestCatalogMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestCatalogMetaService.javanew file mode 100644index 0000000000..589dbec14e--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestCatalogMetaService.java@@ -0,0 +1,179 @@+/*+ * 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.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.io.IOException;+import java.time.Instant;+import java.util.List;+import org.apache.gravitino.Catalog;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityAlreadyExistsException;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.CatalogEntity;+import org.apache.gravitino.storage.RandomIdGenerator;+import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;+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.BeforeEach;+import org.junit.jupiter.api.TestTemplate;++public class TestCatalogMetaService extends TestJDBCBackend {++ private final AuditInfo auditInfo =+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();+ private final String metalakeName = "metalake_for_catalog_test";++ @BeforeEach+ public void prepare() throws IOException {+ createAndInsertMakeLake(metalakeName);+ }++ @TestTemplate+ public void testInsertAlreadyExistsException() throws IOException {+ CatalogEntity catalog =+ createCatalog(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofCatalog(metalakeName),+ "catalog",+ auditInfo);+ CatalogEntity catalogCopy =+ createCatalog(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofCatalog(metalakeName),+ "catalog",+ auditInfo);+ backend.insert(catalog, false);+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(catalogCopy, false));+ }++ @TestTemplate+ public void testUpdateAlreadyExistsException() throws IOException {+ CatalogEntity catalog =+ createCatalog(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofCatalog(metalakeName),+ "catalog",+ auditInfo);+ CatalogEntity catalogCopy =+ createCatalog(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofCatalog(metalakeName),+ "catalog1",+ auditInfo);+ backend.insert(catalog, false);+ backend.insert(catalogCopy, false);+ assertThrows(+ EntityAlreadyExistsException.class,+ () ->+ backend.update(+ catalogCopy.nameIdentifier(),+ Entity.EntityType.CATALOG,+ e ->+ createCatalog(+ catalogCopy.id(), catalogCopy.namespace(), "catalog", auditInfo)));+ }++ @TestTemplate+ void testUpdateCatalogWithNullableComment() throws IOException {+ CatalogEntity catalog =+ CatalogEntity.builder()+ .withId(RandomIdGenerator.INSTANCE.nextId())+ .withNamespace(NamespaceUtil.ofCatalog(metalakeName))+ .withName("catalog")+ .withAuditInfo(auditInfo)+ .withComment(null)+ .withProperties(null)+ .withType(Catalog.Type.RELATIONAL)+ .withProvider("test")+ .build();+ backend.insert(catalog, false);++ backend.update(+ catalog.nameIdentifier(),+ Entity.EntityType.CATALOG,+ e ->+ CatalogEntity.builder()+ .withId(catalog.id())+ .withNamespace(catalog.namespace())+ .withName(catalog.name())+ .withAuditInfo(auditInfo)+ .withComment("comment")+ .withProperties(catalog.getProperties())+ .withType(Catalog.Type.RELATIONAL)+ .withProvider("test")+ .build());++ CatalogEntity updatedCatalog = backend.get(catalog.nameIdentifier(), Entity.EntityType.CATALOG);+ Assertions.assertNotNull(updatedCatalog.getComment());+ }++ @TestTemplate+ public void testMetaLifeCycleFromCreationToDeletion() throws IOException {+ CatalogEntity catalog =+ createCatalog(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofCatalog(metalakeName),+ "catalog",+ auditInfo);+ backend.insert(catalog, false);++ List<CatalogEntity> catalogs =+ backend.list(catalog.namespace(), Entity.EntityType.CATALOG, true);+ assertTrue(catalogs.contains(catalog));+ assertEquals(1, catalogs.size());++ CatalogEntity catalogEntity = backend.get(catalog.nameIdentifier(), Entity.EntityType.CATALOG);+ assertEquals(catalog, catalogEntity);+ Assertions.assertNotNull(+ CatalogMetaService.getInstance()+ .getCatalogPOByName(catalogEntity.namespace().level(0), catalog.name()));+ assertEquals(+ catalog.id(),+ CatalogMetaService.getInstance()+ .getCatalogIdByName(catalog.namespace().level(0), catalog.name()));++ // meta data soft delete+ backend.delete(NameIdentifierUtil.ofMetalake(metalakeName), Entity.EntityType.METALAKE, true);++ assertEquals(+ 0,+ SessionUtils.doWithCommitAndFetchResult(+ CatalogMetaMapper.class,+ mapper -> mapper.listCatalogPOsByMetalakeName(metalakeName))+ .size());++ // check existence after soft delete+ assertFalse(backend.exists(catalog.nameIdentifier(), Entity.EntityType.CATALOG));++ // check legacy record after soft delete+ assertTrue(legacyRecordExistsInDB(catalog.id(), Entity.EntityType.CATALOG));++ // meta data hard delete+ backend.hardDeleteLegacyData(Entity.EntityType.CATALOG, Instant.now().toEpochMilli() + 3000);+ assertFalse(legacyRecordExistsInDB(catalog.id(), Entity.EntityType.CATALOG));+ }+}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestFilesetMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestFilesetMetaService.javaindex e096e67df4..01bf11929b 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestFilesetMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestFilesetMetaService.java@@ -19,163 +19,195 @@package org.apache.gravitino.storage.relational.service;import static org.apache.gravitino.file.Fileset.LOCATION_NAME_UNKNOWN;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;import com.google.common.collect.Lists;-import java.io.File;import java.io.IOException;import java.sql.Connection;-import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.time.Instant;-import java.util.Arrays;import java.util.List;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;-import org.apache.commons.io.FileUtils;-import org.apache.commons.lang3.ArrayUtils;-import org.apache.commons.lang3.StringUtils;-import org.apache.gravitino.Catalog;-import org.apache.gravitino.Config;-import org.apache.gravitino.Configs;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityAlreadyExistsException;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;-import org.apache.gravitino.config.ConfigConstants;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.file.Fileset;-import org.apache.gravitino.integration.test.container.ContainerSuite;-import org.apache.gravitino.integration.test.container.MySQLContainer;import org.apache.gravitino.integration.test.util.GravitinoITUtils;-import org.apache.gravitino.integration.test.util.TestDatabaseName;import org.apache.gravitino.meta.AuditInfo;-import org.apache.gravitino.meta.BaseMetalake;-import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.FilesetEntity;-import org.apache.gravitino.meta.SchemaEntity;-import org.apache.gravitino.meta.SchemaVersion;-import org.apache.gravitino.storage.IdGenerator;import org.apache.gravitino.storage.RandomIdGenerator;+import org.apache.gravitino.storage.relational.TestJDBCBackend;import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.NamespaceUtil;import org.apache.ibatis.session.SqlSession;-import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.BeforeAll;-import org.junit.jupiter.api.Tag;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;-import org.mockito.Mockito;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.TestTemplate;import org.testcontainers.shaded.com.google.common.collect.ImmutableMap;import org.testcontainers.shaded.org.apache.commons.lang3.tuple.Pair;-@Tag("gravitino-docker-test")-@EnabledIfEnvironmentVariable(named = "jdbcBackend", matches = "MySQL")-public class TestFilesetMetaService {- private static final Logger LOG = LoggerFactory.getLogger(TestFilesetMetaService.class);- private static final ContainerSuite containerSuite = ContainerSuite.getInstance();- private static final IdGenerator idGenerator = new RandomIdGenerator();+public class TestFilesetMetaService extends TestJDBCBackend {+ private final String metalakeName = GravitinoITUtils.genRandomName("tst_metalake");+ private final String catalogName = GravitinoITUtils.genRandomName("tst_fs_catalog");+ private final String schemaName = GravitinoITUtils.genRandomName("tst_fs_schema");- private static final AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- private static final String metalakeName = GravitinoITUtils.genRandomName("tst_metalake");- private static final String catalogName = GravitinoITUtils.genRandomName("tst_fs_catalog");- private static final String schemaName = GravitinoITUtils.genRandomName("tst_fs_schema");+ @BeforeEach+ public void prepare() throws IOException {+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);+ createAndInsertSchema(metalakeName, catalogName, schemaName);+ }- @BeforeAll- public static void setup() throws IOException {- TestDatabaseName META_DATA = TestDatabaseName.MYSQL_JDBC_BACKEND;- containerSuite.startMySQLContainer(META_DATA);- MySQLContainer MYSQL_CONTAINER = containerSuite.getMySQLContainer();+ @TestTemplate+ public void testInsertAlreadyExistsException() throws IOException {+ FilesetEntity fileset =+ createFilesetEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName),+ "fileset",+ AUDIT_INFO);+ FilesetEntity filesetCopy =+ createFilesetEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName),+ "fileset",+ AUDIT_INFO);+ backend.insert(fileset, false);+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(filesetCopy, false));+ }- String mysqlUrl = MYSQL_CONTAINER.getJdbcUrl(META_DATA);- LOG.info("MySQL URL: {}", mysqlUrl);- // Connect to the mysql docker and create a databases- try (Connection connection =- DriverManager.getConnection(- StringUtils.substring(mysqlUrl, 0, mysqlUrl.lastIndexOf("/")), "root", "root");- final Statement statement = connection.createStatement()) {- statement.execute("drop database if exists " + META_DATA);- statement.execute("create database " + META_DATA);- String gravitinoHome = System.getenv("GRAVITINO_ROOT_DIR");- String mysqlContent =- FileUtils.readFileToString(- new File(- gravitinoHome- + String.format(- "/scripts/mysql/schema-%s-mysql.sql",- ConfigConstants.CURRENT_SCRIPT_VERSION)),- "UTF-8");- String[] initMySQLBackendSqls =- Arrays.stream(mysqlContent.split(";"))- .map(String::trim)- .filter(s -> !s.isEmpty())- .toArray(String[]::new);- initMySQLBackendSqls = ArrayUtils.addFirst(initMySQLBackendSqls, "use " + META_DATA + ";");- for (String sql : initMySQLBackendSqls) {- statement.execute(sql);- }- } catch (Exception e) {- LOG.error("Failed to create database in mysql", e);- throw new RuntimeException(e);- }+ @TestTemplate+ public void testUpdateAlreadyExistsException() throws IOException {+ FilesetEntity fileset =+ createFilesetEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName),+ "fileset",+ AUDIT_INFO);+ FilesetEntity filesetCopy =+ createFilesetEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName),+ "fileset1",+ AUDIT_INFO);+ backend.insert(fileset, false);+ backend.insert(filesetCopy, false);+ assertThrows(+ EntityAlreadyExistsException.class,+ () ->+ backend.update(+ filesetCopy.nameIdentifier(),+ Entity.EntityType.FILESET,+ e ->+ createFilesetEntity(+ filesetCopy.id(), filesetCopy.namespace(), "fileset", AUDIT_INFO)));+ }- Config config = Mockito.mock(Config.class);- Mockito.when(config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_URL)).thenReturn(mysqlUrl);- Mockito.when(config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_DRIVER))- .thenReturn("com.mysql.cj.jdbc.Driver");- Mockito.when(config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_USER)).thenReturn("root");- Mockito.when(config.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PASSWORD)).thenReturn("root");+ @TestTemplate+ public void testMetaLifeCycleFromCreationToDeletion() throws IOException {+ FilesetEntity fileset =+ createFilesetEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName),+ "fileset",+ AUDIT_INFO);+ backend.insert(fileset, false);- SqlSessionFactoryHelper.getInstance().init(config);+ // update fileset properties and version+ FilesetEntity filesetV2 =+ createFilesetEntity(+ fileset.id(),+ NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName),+ "fileset",+ AUDIT_INFO);+ filesetV2.properties().put("version", "2");+ backend.update(fileset.nameIdentifier(), Entity.EntityType.FILESET, e -> filesetV2);- prepareMetalake();- prepareCatalog();- prepareSchema();- }+ String anotherMetalakeName = GravitinoITUtils.genRandomName("another-metalake");+ String anotherCatalogName = GravitinoITUtils.genRandomName("another-catalog");+ String anotherSchemaName = GravitinoITUtils.genRandomName("another-schema");+ createAndInsertMakeLake(anotherMetalakeName);+ createAndInsertCatalog(anotherMetalakeName, anotherCatalogName);+ createAndInsertSchema(anotherMetalakeName, anotherCatalogName, anotherSchemaName);- private static void prepareSchema() throws IOException {- SchemaEntity schemaEntity =- createSchemaEntity(- idGenerator.nextId(),- NamespaceUtil.ofSchema(metalakeName, catalogName),- schemaName,- auditInfo);- SchemaMetaService.getInstance().insertSchema(schemaEntity, true);- assertNotNull(- SchemaMetaService.getInstance()- .getSchemaByIdentifier(NameIdentifier.of(metalakeName, catalogName, schemaName)));- }+ FilesetEntity anotherFileset =+ createFilesetEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(anotherMetalakeName, anotherCatalogName, anotherSchemaName),+ "anotherFileset",+ AUDIT_INFO);+ backend.insert(anotherFileset, false);- private static void prepareMetalake() throws IOException {- BaseMetalake metalake = createBaseMakeLake(idGenerator.nextId(), metalakeName, auditInfo);- MetalakeMetaService.getInstance().insertMetalake(metalake, true);- assertNotNull(- MetalakeMetaService.getInstance().getMetalakeByIdentifier(NameIdentifier.of(metalakeName)));- }+ FilesetEntity anotherFilesetV2 =+ createFilesetEntity(+ anotherFileset.id(),+ NamespaceUtil.ofFileset(anotherMetalakeName, anotherCatalogName, anotherSchemaName),+ "anotherFileset",+ AUDIT_INFO);+ anotherFilesetV2.properties().put("version", "2");+ backend.update(+ anotherFileset.nameIdentifier(), Entity.EntityType.FILESET, e -> anotherFilesetV2);- private static void prepareCatalog() throws IOException {- CatalogEntity catalogEntity =- createCatalog(- idGenerator.nextId(), NamespaceUtil.ofCatalog(metalakeName), catalogName, auditInfo);- CatalogMetaService.getInstance().insertCatalog(catalogEntity, true);- assertNotNull(- CatalogMetaService.getInstance()- .getCatalogByIdentifier(NameIdentifier.of(metalakeName, catalogName)));- }+ FilesetEntity anotherFilesetV3 =+ createFilesetEntity(+ anotherFileset.id(),+ NamespaceUtil.ofFileset(anotherMetalakeName, anotherCatalogName, anotherSchemaName),+ "anotherFileset",+ AUDIT_INFO);+ anotherFilesetV3.properties().put("version", "3");+ backend.update(+ anotherFileset.nameIdentifier(), Entity.EntityType.FILESET, e -> anotherFilesetV3);++ List<FilesetEntity> filesets =+ backend.list(fileset.namespace(), Entity.EntityType.FILESET, true);+ assertFalse(filesets.contains(fileset));+ assertTrue(filesets.contains(filesetV2));+ assertEquals("2", filesets.get(filesets.indexOf(filesetV2)).properties().get("version"));++ // meta data soft delete+ backend.delete(NameIdentifierUtil.ofMetalake(metalakeName), Entity.EntityType.METALAKE, true);+ assertFalse(backend.exists(fileset.nameIdentifier(), Entity.EntityType.FILESET));+ assertTrue(backend.exists(anotherFileset.nameIdentifier(), Entity.EntityType.FILESET));++ // check legacy record after soft delete+ assertTrue(legacyRecordExistsInDB(fileset.id(), Entity.EntityType.FILESET));+ assertEquals(2, listFilesetVersions(fileset.id()).size());+ assertEquals(3, listFilesetVersions(anotherFileset.id()).size());- @AfterEach- public void cleanFilesets() throws IOException {- SchemaMetaService.getInstance()- .deleteSchema(NameIdentifier.of(metalakeName, catalogName, schemaName), true);- prepareSchema();+ // meta data hard delete+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.hardDeleteLegacyData(entityType, Instant.now().toEpochMilli() + 1000);+ }+ assertFalse(legacyRecordExistsInDB(fileset.id(), Entity.EntityType.FILESET));+ assertEquals(0, listFilesetVersions(fileset.id()).size());+ assertEquals(3, listFilesetVersions(anotherFileset.id()).size());++ // soft delete for old version fileset+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.deleteOldVersionData(entityType, 1);+ }+ Map<Integer, Long> versionDeletedMap = listFilesetVersions(anotherFileset.id());+ assertEquals(3, versionDeletedMap.size());+ assertEquals(1, versionDeletedMap.values().stream().filter(value -> value == 0L).count());+ assertEquals(2, versionDeletedMap.values().stream().filter(value -> value != 0L).count());++ // hard delete for old version fileset+ backend.hardDeleteLegacyData(Entity.EntityType.FILESET, Instant.now().toEpochMilli() + 1000);+ assertEquals(1, listFilesetVersions(anotherFileset.id()).size());}- @Test+ @TestTemplatepublic void testFilesetMultipleLocations() {// test createString filesetName = GravitinoITUtils.genRandomName("multiple_location_fileset");@@ -187,14 +219,14 @@ public class TestFilesetMetaService {Namespace filesetNs = NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName);FilesetEntity filesetEntity =FilesetEntity.builder()- .withId(idGenerator.nextId())+ .withId(RandomIdGenerator.INSTANCE.nextId()).withName(filesetName).withNamespace(filesetNs).withFilesetType(Fileset.Type.MANAGED).withStorageLocations(locations).withComment("").withProperties(null)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Assertions.assertDoesNotThrow(() -> FilesetMetaService.getInstance().insertFileset(filesetEntity, true));@@ -232,14 +264,14 @@ public class TestFilesetMetaService {NameIdentifier.of(metalakeName, catalogName, schemaName, filesetName2);FilesetEntity filesetEntity2 =FilesetEntity.builder()- .withId(idGenerator.nextId())+ .withId(RandomIdGenerator.INSTANCE.nextId()).withName(filesetName2).withNamespace(filesetNs).withFilesetType(Fileset.Type.MANAGED).withStorageLocations(locations).withComment("").withProperties(null)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Assertions.assertDoesNotThrow(() -> FilesetMetaService.getInstance().insertFileset(filesetEntity2, true));@@ -261,15 +293,15 @@ public class TestFilesetMetaService {Assertions.assertTrue(locationNames.contains(locationName));}- @Test+ @TestTemplatepublic void testDeleteFilesetVersionsByRetentionCount() throws IOException {String filesetName = GravitinoITUtils.genRandomName("tst_fs_fileset");FilesetEntity filesetEntity =createFilesetEntity(- idGenerator.nextId(),+ RandomIdGenerator.INSTANCE.nextId(),NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName),filesetName,- auditInfo,+ AUDIT_INFO,"/tmp");FilesetMetaService.getInstance().insertFileset(filesetEntity, true);assertNotNull(@@ -317,44 +349,7 @@ public class TestFilesetMetaService {return deletedVersions;}- public static BaseMetalake createBaseMakeLake(Long id, String name, AuditInfo auditInfo) {- return BaseMetalake.builder()- .withId(id)- .withName(name)- .withAuditInfo(auditInfo)- .withComment("")- .withProperties(null)- .withVersion(SchemaVersion.V_0_1)- .build();- }-- public static CatalogEntity createCatalog(- Long id, Namespace namespace, String name, AuditInfo auditInfo) {- return CatalogEntity.builder()- .withId(id)- .withName(name)- .withNamespace(namespace)- .withType(Catalog.Type.RELATIONAL)- .withProvider("test")- .withComment("")- .withProperties(null)- .withAuditInfo(auditInfo)- .build();- }-- public static SchemaEntity createSchemaEntity(- Long id, Namespace namespace, String name, AuditInfo auditInfo) {- return SchemaEntity.builder()- .withId(id)- .withName(name)- .withNamespace(namespace)- .withComment("")- .withProperties(null)- .withAuditInfo(auditInfo)- .build();- }-- public static FilesetEntity createFilesetEntity(+ private FilesetEntity createFilesetEntity(Long id, Namespace namespace, String name, AuditInfo auditInfo, String location) {return FilesetEntity.builder().withId(id)diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGroupMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGroupMetaService.javaindex 5e90f0eb89..4584cc02ac 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGroupMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGroupMetaService.java@@ -19,6 +19,10 @@package org.apache.gravitino.storage.relational.service;+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 com.google.common.collect.Lists;import com.google.common.collect.Sets;import java.io.IOException;@@ -39,35 +43,109 @@ import org.apache.gravitino.authorization.AuthorizationUtils;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.BaseMetalake;-import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.GroupEntity;import org.apache.gravitino.meta.RoleEntity;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.storage.relational.mapper.GroupMetaMapper;import org.apache.gravitino.storage.relational.mapper.RoleMetaMapper;import org.apache.gravitino.storage.relational.po.RolePO;import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;import org.apache.gravitino.storage.relational.utils.SessionUtils;+import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;class TestGroupMetaService extends TestJDBCBackend {- String metalakeName = "metalake";+ private final String metalakeName = "metalake_for_group_test";+ private final String catalogName = "catalog_for_group_test";- @Test- void getGroupByIdentifier() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();+ @TestTemplate+ public void testMetaLifeCycleFromCreationToDeletion() throws IOException {+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);++ RoleEntity role =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role",+ AUDIT_INFO,+ catalogName);+ backend.insert(role, false);++ GroupEntity group =+ createGroupEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofGroupNamespace(metalakeName),+ "group",+ AUDIT_INFO,+ Lists.newArrayList(role.name()),+ Lists.newArrayList(role.id()));+ backend.insert(group, false);++ String anotherMetalakeName = "another-metalake-for-group-test";+ String anotherCatalogName = "another-catalog-for-group-test";+ createAndInsertMakeLake(anotherMetalakeName);+ createAndInsertCatalog(anotherMetalakeName, anotherCatalogName);+ RoleEntity anotherRole =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(anotherMetalakeName),+ "another-role",+ AUDIT_INFO,+ anotherCatalogName);+ backend.insert(anotherRole, false);++ GroupEntity anotherGroup =+ createGroupEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofGroupNamespace(anotherMetalakeName),+ "another-group",+ AUDIT_INFO,+ Lists.newArrayList(anotherRole.name()),+ Lists.newArrayList(anotherRole.id()));+ backend.insert(anotherGroup, false);++ assertEquals(1, RoleMetaService.getInstance().listRolesByGroupId(group.id()).size());++ GroupEntity groupEntity = backend.get(group.nameIdentifier(), Entity.EntityType.GROUP);+ assertEquals(group, groupEntity);+ assertEquals(+ 1,+ SessionUtils.doWithCommitAndFetchResult(+ GroupMetaMapper.class, mapper -> mapper.listGroupsByRoleId(role.id()))+ .size());++ // meta data soft delete+ backend.delete(NameIdentifierUtil.ofMetalake(metalakeName), Entity.EntityType.METALAKE, true);++ // check existence after soft delete+ assertEquals(0, RoleMetaService.getInstance().listRolesByGroupId(group.id()).size());+ assertFalse(backend.exists(group.nameIdentifier(), Entity.EntityType.GROUP));+ assertEquals(+ 0,+ SessionUtils.doWithCommitAndFetchResult(+ GroupMetaMapper.class, mapper -> mapper.listGroupsByRoleId(role.id()))+ .size());+ assertTrue(backend.exists(anotherGroup.nameIdentifier(), Entity.EntityType.GROUP));- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog", auditInfo);- backend.insert(catalog, false);+ // check legacy record after soft delete+ assertTrue(legacyRecordExistsInDB(group.id(), Entity.EntityType.GROUP));++ // meta data hard delete+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.hardDeleteLegacyData(entityType, Instant.now().toEpochMilli() + 1000);+ }+ assertFalse(legacyRecordExistsInDB(group.id(), Entity.EntityType.GROUP));+ }++ @TestTemplate+ void getGroupByIdentifier() throws IOException {+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);GroupMetaService groupMetaService = GroupMetaService.getInstance();RoleMetaService roleMetaService = RoleMetaService.getInstance();@@ -85,7 +163,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group1",- auditInfo);+ AUDIT_INFO);groupMetaService.insertGroup(group1, false);Assertions.assertEquals(group1, groupMetaService.getGroupByIdentifier(group1.nameIdentifier()));@@ -95,15 +173,15 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role2",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);roleMetaService.insertRole(role1, false);roleMetaService.insertRole(role2, false);GroupEntity group2 =@@ -111,7 +189,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group2",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));groupMetaService.insertGroup(group2, false);@@ -121,50 +199,42 @@ class TestGroupMetaService extends TestJDBCBackend {Sets.newHashSet(group2.roleNames()), Sets.newHashSet(actualGroup.roleNames()));}- @Test+ @TestTemplatevoid testListGroups() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog", auditInfo);- backend.insert(catalog, false);+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);GroupEntity group1 =createGroupEntity(RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group1",- auditInfo);+ AUDIT_INFO);RoleEntity role1 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace("metalake"),+ AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);backend.insert(role1, false);RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace("metalake"),+ AuthorizationUtils.ofRoleNamespace(metalakeName),"role2",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);backend.insert(role2, false);GroupEntity group2 =createGroupEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofGroupNamespace("metalake"),+ AuthorizationUtils.ofGroupNamespace(metalakeName),"group2",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));@@ -219,17 +289,10 @@ class TestGroupMetaService extends TestJDBCBackend {Assertions.assertEquals(expectGroups.size(), actualGroups.size());}- @Test- void insertGroup() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog", auditInfo);- backend.insert(catalog, false);+ @TestTemplate+ void testInsertGroup() throws IOException {+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);GroupMetaService groupMetaService = GroupMetaService.getInstance();RoleMetaService roleMetaService = RoleMetaService.getInstance();@@ -240,7 +303,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group1",- auditInfo);+ AUDIT_INFO);Assertions.assertThrows(NoSuchEntityException.class,() -> groupMetaService.getGroupByIdentifier(group1.nameIdentifier()));@@ -253,7 +316,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group1",- auditInfo);+ AUDIT_INFO);Assertions.assertThrows(EntityAlreadyExistsException.class, () -> groupMetaService.insertGroup(group1Exist, false));@@ -263,7 +326,7 @@ class TestGroupMetaService extends TestJDBCBackend {group1.id(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group1Overwrite",- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> groupMetaService.insertGroup(group1Overwrite, true));Assertions.assertEquals("group1Overwrite",@@ -277,15 +340,15 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role2",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);roleMetaService.insertRole(role1, false);roleMetaService.insertRole(role2, false);GroupEntity group2 =@@ -293,7 +356,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group2",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));Assertions.assertDoesNotThrow(() -> groupMetaService.insertGroup(group2, false));@@ -308,7 +371,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group2",- auditInfo);+ AUDIT_INFO);Assertions.assertThrows(EntityAlreadyExistsException.class, () -> groupMetaService.insertGroup(group2Exist, false));@@ -318,7 +381,7 @@ class TestGroupMetaService extends TestJDBCBackend {group1.id(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group2Overwrite",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));Assertions.assertDoesNotThrow(() -> groupMetaService.insertGroup(group2Overwrite, true));@@ -337,15 +400,15 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role3",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);roleMetaService.insertRole(role3, false);GroupEntity group3Overwrite =createGroupEntity(group1.id(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group3Overwrite",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role3.name()),Lists.newArrayList(role3.id()));Assertions.assertDoesNotThrow(() -> groupMetaService.insertGroup(group3Overwrite, true));@@ -362,7 +425,7 @@ class TestGroupMetaService extends TestJDBCBackend {group1.id(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group4Overwrite",- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> groupMetaService.insertGroup(group4Overwrite, true));GroupEntity actualOverwriteGroup4 =@@ -371,17 +434,10 @@ class TestGroupMetaService extends TestJDBCBackend {Assertions.assertNull(actualOverwriteGroup4.roleNames());}- @Test- void deleteGroup() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog", auditInfo);- backend.insert(catalog, false);+ @TestTemplate+ void testDeleteGroup() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);GroupMetaService groupMetaService = GroupMetaService.getInstance();RoleMetaService roleMetaService = RoleMetaService.getInstance();@@ -393,7 +449,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group1",- auditInfo);+ AUDIT_INFO);Assertions.assertThrows(NoSuchEntityException.class,() -> groupMetaService.getGroupByIdentifier(group1.nameIdentifier()));@@ -424,15 +480,15 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role2",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);roleMetaService.insertRole(role1, false);roleMetaService.insertRole(role2, false);GroupEntity group2 =@@ -440,7 +496,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group2",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));groupMetaService.insertGroup(group2, false);@@ -463,17 +519,10 @@ class TestGroupMetaService extends TestJDBCBackend {Assertions.assertEquals(0, rolePOs.size());}- @Test- void updateGroup() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog", auditInfo);- backend.insert(catalog, false);+ @TestTemplate+ void testUpdateGroup() throws IOException {+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);GroupMetaService groupMetaService = GroupMetaService.getInstance();RoleMetaService roleMetaService = RoleMetaService.getInstance();@@ -483,15 +532,15 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role2",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);roleMetaService.insertRole(role1, false);roleMetaService.insertRole(role2, false);GroupEntity group1 =@@ -499,7 +548,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));groupMetaService.insertGroup(group1, false);@@ -513,8 +562,8 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role3",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);roleMetaService.insertRole(role3, false);// update group (grant)@@ -598,8 +647,8 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role4",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);roleMetaService.insertRole(role4, false);// update group (grant & revoke)@@ -684,17 +733,10 @@ class TestGroupMetaService extends TestJDBCBackend {Assertions.assertEquals(Sets.newHashSet("role4"), Sets.newHashSet(groupEntity.roleNames()));}- @Test- void deleteMetalake() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog", auditInfo);- backend.insert(catalog, false);+ @TestTemplate+ void testDeleteMetalake() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);GroupMetaService groupMetaService = GroupMetaService.getInstance();RoleMetaService roleMetaService = RoleMetaService.getInstance();@@ -704,22 +746,22 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role2",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);RoleEntity role3 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role3",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);roleMetaService.insertRole(role1, false);roleMetaService.insertRole(role2, false);roleMetaService.insertRole(role3, false);@@ -728,7 +770,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));GroupEntity group2 =@@ -736,7 +778,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group2",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role3.name()),Lists.newArrayList(role3.id()));groupMetaService.insertGroup(group1, false);@@ -750,7 +792,8 @@ class TestGroupMetaService extends TestJDBCBackend {Assertions.assertEquals(1, roleMetaService.listRolesByGroupId(group2.id()).size());Assertions.assertTrue(- CatalogMetaService.getInstance().deleteCatalog(catalog.nameIdentifier(), false));+ CatalogMetaService.getInstance()+ .deleteCatalog(NameIdentifierUtil.ofCatalog(metalakeName, catalogName), false));// delete metalake without cascadeAssertions.assertTrue(MetalakeMetaService.getInstance().deleteMetalake(metalake.nameIdentifier(), false));@@ -765,17 +808,10 @@ class TestGroupMetaService extends TestJDBCBackend {Assertions.assertEquals(0, roleMetaService.listRolesByGroupId(group2.id()).size());}- @Test- void deleteMetalakeCascade() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog", auditInfo);- backend.insert(catalog, false);+ @TestTemplate+ void testDeleteMetalakeCascade() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);GroupMetaService groupMetaService = GroupMetaService.getInstance();RoleMetaService roleMetaService = RoleMetaService.getInstance();@@ -785,22 +821,22 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role2",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);RoleEntity role3 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role3",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);roleMetaService.insertRole(role1, false);roleMetaService.insertRole(role2, false);roleMetaService.insertRole(role3, false);@@ -809,7 +845,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));GroupEntity group2 =@@ -817,7 +853,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group2",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role3.name()),Lists.newArrayList(role3.id()));groupMetaService.insertGroup(group1, false);@@ -844,17 +880,10 @@ class TestGroupMetaService extends TestJDBCBackend {Assertions.assertEquals(0, roleMetaService.listRolesByGroupId(group2.id()).size());}- @Test- void deleteGroupMetasByLegacyTimeline() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog", auditInfo);- backend.insert(catalog, false);+ @TestTemplate+ void testDeleteGroupMetasByLegacyTimeline() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);GroupMetaService groupMetaService = GroupMetaService.getInstance();RoleMetaService roleMetaService = RoleMetaService.getInstance();@@ -864,15 +893,15 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role2",- auditInfo,- "catalog");+ AUDIT_INFO,+ catalogName);roleMetaService.insertRole(role1, false);roleMetaService.insertRole(role2, false);@@ -881,7 +910,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));GroupEntity group2 =@@ -889,7 +918,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group2",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));GroupEntity group3 =@@ -897,7 +926,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group3",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));GroupEntity group4 =@@ -905,7 +934,7 @@ class TestGroupMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofGroupNamespace(metalakeName),"group4",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));groupMetaService.insertGroup(group1, false);@@ -1012,4 +1041,16 @@ class TestGroupMetaService extends TestJDBCBackend {}return count;}++ private GroupEntity createGroupEntity(+ Long id, Namespace namespace, String name, AuditInfo auditInfo) {+ return GroupEntity.builder()+ .withId(id)+ .withName(name)+ .withNamespace(namespace)+ .withRoleNames(null)+ .withRoleIds(null)+ .withAuditInfo(auditInfo)+ .build();+ }}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestJobMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestJobMetaService.javaindex 4fd59ef4df..30c5f31714 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestJobMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestJobMetaService.java@@ -35,7 +35,7 @@ import org.apache.gravitino.storage.relational.TestJDBCBackend;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.NamespaceUtil;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;public class TestJobMetaService extends TestJDBCBackend {@@ -44,7 +44,7 @@ public class TestJobMetaService extends TestJDBCBackend {private static final AuditInfo AUDIT_INFO =AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build();- @Test+ @TestTemplatepublic void testInsertAndListJobs() throws IOException {BaseMetalake metalake =createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME, AUDIT_INFO);@@ -87,7 +87,7 @@ public class TestJobMetaService extends TestJDBCBackend {Assertions.assertTrue(emptyJobs.isEmpty());}- @Test+ @TestTemplatepublic void testInsertAndGetJob() throws IOException {BaseMetalake metalake =createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME, AUDIT_INFO);@@ -148,7 +148,7 @@ public class TestJobMetaService extends TestJDBCBackend {Assertions.assertTrue(retrievedFinishedJob.finishedAt() > 0);}- @Test+ @TestTemplatepublic void testDeleteJobsByLegacyTimeline() throws IOException {BaseMetalake metalake =createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME, AUDIT_INFO);@@ -195,7 +195,7 @@ public class TestJobMetaService extends TestJDBCBackend {Assertions.assertTrue(jobs.isEmpty(), "Jobs should be deleted by legacy timeline");}- @Test+ @TestTemplatepublic void testDeleteJobByIdentifier() throws IOException {BaseMetalake metalake =createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME, AUDIT_INFO);diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestJobTemplateMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestJobTemplateMetaService.javaindex 70f1bf0864..76ca0203a1 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestJobTemplateMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestJobTemplateMetaService.java@@ -35,7 +35,7 @@ import org.apache.gravitino.storage.relational.TestJDBCBackend;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.NamespaceUtil;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;public class TestJobTemplateMetaService extends TestJDBCBackend {@@ -44,7 +44,7 @@ public class TestJobTemplateMetaService extends TestJDBCBackend {private static final AuditInfo AUDIT_INFO =AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build();- @Test+ @TestTemplatepublic void testInsertAndListJobTemplates() throws IOException {BaseMetalake metalake =createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME, AUDIT_INFO);@@ -110,7 +110,7 @@ public class TestJobTemplateMetaService extends TestJDBCBackend {Assertions.assertFalse(jobTemplates.contains(testJobTemplateEntity1));}- @Test+ @TestTemplatepublic void testInsertAndSelectJobTemplate() throws IOException {BaseMetalake metalake =createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME, AUDIT_INFO);@@ -145,7 +145,7 @@ public class TestJobTemplateMetaService extends TestJDBCBackend {NameIdentifierUtil.ofJobTemplate(METALAKE_NAME, "non_existent_template")));}- @Test+ @TestTemplatepublic void testInsertAndDeleteJobTemplate() throws IOException {BaseMetalake metalake =createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME, AUDIT_INFO);@@ -176,7 +176,7 @@ public class TestJobTemplateMetaService extends TestJDBCBackend {Assertions.assertFalse(deleted);}- @Test+ @TestTemplatepublic void testDeleteJobTemplateWithJobs() throws IOException {BaseMetalake metalake =createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME, AUDIT_INFO);@@ -209,7 +209,7 @@ public class TestJobTemplateMetaService extends TestJDBCBackend {Assertions.assertEquals(0, jobs.size());}- @Test+ @TestTemplatepublic void testUpdateJobTemplate() throws IOException {BaseMetalake metalake =createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME, AUDIT_INFO);diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestMetalakeMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestMetalakeMetaService.javanew file mode 100644index 0000000000..b1e6389a20--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestMetalakeMetaService.java@@ -0,0 +1,122 @@+/*+ * 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.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.io.IOException;+import java.time.Instant;+import java.util.List;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityAlreadyExistsException;+import org.apache.gravitino.meta.BaseMetalake;+import org.apache.gravitino.meta.SchemaVersion;+import org.apache.gravitino.storage.RandomIdGenerator;+import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.TestTemplate;++public class TestMetalakeMetaService extends TestJDBCBackend {++ private static final String METALAKE_NAME = "metalake_for_metalake_test";++ @TestTemplate+ public void testInsertAlreadyExistsException() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);+ BaseMetalake metalakeCopy =+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalake.name(), AUDIT_INFO);+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(metalakeCopy, false));+ }++ @TestTemplate+ public void testUpdateAlreadyExistsException() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);+ BaseMetalake metalakeCopy = createAndInsertMakeLake("another_metalake_for_metalake_test");+ assertThrows(+ EntityAlreadyExistsException.class,+ () ->+ backend.update(+ metalakeCopy.nameIdentifier(),+ Entity.EntityType.METALAKE,+ e -> createBaseMakeLake(metalakeCopy.id(), metalake.name(), AUDIT_INFO)));+ }++ @TestTemplate+ void testUpdateMetalakeWithNullableComment() throws IOException {+ BaseMetalake metalake =+ BaseMetalake.builder()+ .withId(RandomIdGenerator.INSTANCE.nextId())+ .withName(METALAKE_NAME)+ .withAuditInfo(AUDIT_INFO)+ .withComment(null)+ .withProperties(null)+ .withVersion(SchemaVersion.V_0_1)+ .build();+ backend.insert(metalake, false);++ backend.update(+ metalake.nameIdentifier(),+ Entity.EntityType.METALAKE,+ e ->+ BaseMetalake.builder()+ .withId(metalake.id())+ .withName(metalake.name())+ .withAuditInfo(AUDIT_INFO)+ .withComment("comment")+ .withProperties(metalake.properties())+ .withVersion(metalake.getVersion())+ .build());++ BaseMetalake updatedMetalake =+ backend.get(metalake.nameIdentifier(), Entity.EntityType.METALAKE);+ Assertions.assertNotNull(updatedMetalake.comment());++ backend.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE, false);+ }++ @TestTemplate+ public void testMetaLifeCycleFromCreationToDeletion() throws IOException {+ // meta data creation+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);+ BaseMetalake anotherMetaLake = createAndInsertMakeLake("another_metalake_for_metalake_test");++ // meta data list+ List<BaseMetalake> metaLakes =+ backend.list(metalake.namespace(), Entity.EntityType.METALAKE, true);+ assertTrue(metaLakes.contains(metalake));++ // meta data soft delete+ backend.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE, true);++ // check existence after soft delete+ assertFalse(backend.exists(metalake.nameIdentifier(), Entity.EntityType.METALAKE));+ assertTrue(backend.exists(anotherMetaLake.nameIdentifier(), Entity.EntityType.METALAKE));++ // check legacy record after soft delete+ assertTrue(legacyRecordExistsInDB(metalake.id(), Entity.EntityType.METALAKE));++ // meta data hard delete+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.hardDeleteLegacyData(entityType, Instant.now().toEpochMilli() + 1000);+ }+ assertFalse(legacyRecordExistsInDB(metalake.id(), Entity.EntityType.METALAKE));+ }+}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelMetaService.javaindex 3b294fb0df..cfc9eb1549 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelMetaService.java@@ -18,6 +18,9 @@*/package org.apache.gravitino.storage.relational.service;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;+import com.google.common.collect.ImmutableMap;import java.io.IOException;import java.time.Instant;@@ -29,14 +32,15 @@ import org.apache.gravitino.EntityAlreadyExistsException;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.exceptions.NoSuchEntityException;-import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.ModelEntity;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.TestJDBCBackend;import org.apache.gravitino.storage.relational.po.ModelPO;import org.apache.gravitino.storage.relational.utils.POConverters;+import org.apache.gravitino.utils.NamespaceUtil;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;public class TestModelMetaService extends TestJDBCBackend {@@ -48,12 +52,43 @@ public class TestModelMetaService extends TestJDBCBackend {private static final Namespace MODEL_NS = Namespace.of(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME);- private final AuditInfo auditInfo =- AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build();+ @TestTemplate+ public void testMetaLifeCycleFromCreationToDeletion() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);+ createAndInsertCatalog(METALAKE_NAME, CATALOG_NAME);+ createAndInsertSchema(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME);++ ModelEntity model =+ createModelEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofModel(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),+ "model",+ "model comment",+ 1,+ ImmutableMap.of("key", "value"),+ AUDIT_INFO);+ backend.insert(model, false);++ List<ModelEntity> models = backend.list(model.namespace(), Entity.EntityType.MODEL, true);+ assertTrue(models.contains(model));++ // meta data soft delete+ backend.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE, true);+ assertFalse(backend.exists(model.nameIdentifier(), Entity.EntityType.MODEL));++ // check legacy record after soft delete+ assertTrue(legacyRecordExistsInDB(model.id(), Entity.EntityType.MODEL));++ // meta data hard delete+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.hardDeleteLegacyData(entityType, Instant.now().toEpochMilli() + 1000);+ }+ assertFalse(legacyRecordExistsInDB(model.id(), Entity.EntityType.MODEL));+ }- @Test+ @TestTemplatepublic void testInsertAndSelectModel() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);Map<String, String> properties = ImmutableMap.of("k1", "v1");ModelEntity modelEntity =@@ -64,7 +99,7 @@ public class TestModelMetaService extends TestJDBCBackend {"model1 comment",0,properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelMetaService.getInstance().insertModel(modelEntity, false));@@ -87,7 +122,7 @@ public class TestModelMetaService extends TestJDBCBackend {null,modelEntity.latestVersion(),null,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelMetaService.getInstance().insertModel(modelEntity2, true));ModelEntity registeredModelEntity2 =@@ -123,9 +158,9 @@ public class TestModelMetaService extends TestJDBCBackend {() -> ModelMetaService.getInstance().getModelIdBySchemaIdAndModelName(schemaId, "model3"));}- @Test+ @TestTemplatepublic void testInsertAndListModels() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);Map<String, String> properties = ImmutableMap.of("k1", "v1");ModelEntity modelEntity1 =@@ -136,7 +171,7 @@ public class TestModelMetaService extends TestJDBCBackend {"model1 comment",0,properties,- auditInfo);+ AUDIT_INFO);ModelEntity modelEntity2 =createModelEntity(RandomIdGenerator.INSTANCE.nextId(),@@ -145,7 +180,7 @@ public class TestModelMetaService extends TestJDBCBackend {"model2 comment",0,properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelMetaService.getInstance().insertModel(modelEntity1, false));@@ -166,9 +201,9 @@ public class TestModelMetaService extends TestJDBCBackend {.listModelsByNamespace(Namespace.of(METALAKE_NAME, CATALOG_NAME, "inexistent")));}- @Test+ @TestTemplatepublic void testInsertAndDeleteModel() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);Map<String, String> properties = ImmutableMap.of("k1", "v1");ModelEntity modelEntity =@@ -179,7 +214,7 @@ public class TestModelMetaService extends TestJDBCBackend {"model1 comment",0,properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelMetaService.getInstance().insertModel(modelEntity, false));@@ -203,9 +238,9 @@ public class TestModelMetaService extends TestJDBCBackend {.deleteModel(NameIdentifier.of(METALAKE_NAME, CATALOG_NAME, "inexistent", "model1")));}- @Test+ @TestTemplatevoid testInsertAndRenameModel() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);Map<String, String> properties = ImmutableMap.of("k1", "v1");String newName = "new_model_name";@@ -217,7 +252,7 @@ public class TestModelMetaService extends TestJDBCBackend {"model1 comment",0,properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelMetaService.getInstance().insertModel(modelEntity, false));@@ -246,9 +281,9 @@ public class TestModelMetaService extends TestJDBCBackend {.updateModel(NameIdentifier.of(MODEL_NS, "model3"), renameUpdater));}- @Test+ @TestTemplatevoid testInsertAndUpdateModelComment() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);Map<String, String> properties = ImmutableMap.of("k1", "v1");String newComment = "new_model_comment";@@ -260,7 +295,7 @@ public class TestModelMetaService extends TestJDBCBackend {"model1 comment",0,properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelMetaService.getInstance().insertModel(modelEntity, false));@@ -289,9 +324,9 @@ public class TestModelMetaService extends TestJDBCBackend {.updateModel(NameIdentifier.of(MODEL_NS, "model3"), renameUpdater));}- @Test+ @TestTemplatevoid testInsertAndUpdateModelProperties() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);Map<String, String> properties = ImmutableMap.of("k1", "v1", "k2", "v2");Map<String, String> newProps = ImmutableMap.of("k1", "v1", "k3", "v3");@@ -303,7 +338,7 @@ public class TestModelMetaService extends TestJDBCBackend {"model1 comment",0,properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelMetaService.getInstance().insertModel(modelEntity, false));diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelVersionMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelVersionMetaService.javaindex 3d59e8591a..14aebe26fd 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelVersionMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestModelVersionMetaService.java@@ -22,7 +22,7 @@ import com.google.common.collect.ImmutableList;import com.google.common.collect.ImmutableMap;import com.google.common.collect.Lists;import java.io.IOException;-import java.time.Instant;+import java.sql.SQLException;import java.util.List;import java.util.Map;import java.util.UUID;@@ -41,9 +41,7 @@ import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.TestJDBCBackend;import org.apache.gravitino.utils.NameIdentifierUtil;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;-import org.junit.jupiter.params.ParameterizedTest;-import org.junit.jupiter.params.provider.ValueSource;+import org.junit.jupiter.api.TestTemplate;public class TestModelVersionMetaService extends TestJDBCBackend {@@ -55,16 +53,13 @@ public class TestModelVersionMetaService extends TestJDBCBackend {private static final Namespace MODEL_NS = Namespace.of(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME);- private final AuditInfo auditInfo =- AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build();-private final Map<String, String> properties = ImmutableMap.of("k1", "v1");private final List<String> aliases = Lists.newArrayList("alias1", "alias2");- @Test+ @TestTemplatepublic void testInsertAndSelectModelVersion() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);// Create a model entityModelEntity modelEntity =@@ -75,7 +70,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {"model1 comment",0,properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelMetaService.getInstance().insertModel(modelEntity, false));@@ -89,7 +84,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {aliases,"test comment",properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));@@ -121,7 +116,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {null,null,null,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity2));@@ -190,16 +185,16 @@ public class TestModelVersionMetaService extends TestJDBCBackend {aliases,"test comment",properties,- auditInfo);+ AUDIT_INFO);Assertions.assertThrows(NoSuchEntityException.class,() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity3));}- @Test+ @TestTemplatepublic void testInsertAndListModelVersions() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);// Create a model entityModelEntity modelEntity =@@ -210,7 +205,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {"model1 comment",0,properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelMetaService.getInstance().insertModel(modelEntity, false));@@ -224,7 +219,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {aliases,"test comment",properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));@@ -244,7 +239,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {null,null,null,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity2));@@ -267,9 +262,9 @@ public class TestModelVersionMetaService extends TestJDBCBackend {getModelVersionNs(NameIdentifier.of(MODEL_NS, "model2"))));}- @Test+ @TestTemplatepublic void testInsertAndDeleteModelVersion() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);// Create a model entityModelEntity modelEntity =@@ -280,7 +275,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {"model1 comment",0,properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelMetaService.getInstance().insertModel(modelEntity, false));@@ -294,7 +289,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {aliases,"test comment",properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));@@ -341,7 +336,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {aliases,"test comment",properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity2));@@ -386,9 +381,9 @@ public class TestModelVersionMetaService extends TestJDBCBackend {getModelVersionIdent(modelEntity.nameIdentifier(), "alias2")));}- @Test+ @TestTemplatepublic void testModelVersionWithMultipleUris() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);// Create a model entityModelEntity modelEntity =@@ -399,7 +394,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {"model1 comment",0,properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelMetaService.getInstance().insertModel(modelEntity, false));@@ -412,7 +407,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {aliases,"test comment",properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));@@ -481,10 +476,16 @@ public class TestModelVersionMetaService extends TestJDBCBackend {getModelVersionIdent(modelEntity.nameIdentifier(), 0)));}- @ParameterizedTest- @ValueSource(strings = {"model", "schema", "catalog", "metalake"})- public void testDeleteModelVersionsInDeletion(String input) throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ @TestTemplate+ public void testDeleteModelVersionsInDeletion() throws IOException, SQLException {+ for (String param : new String[] {"model", "schema", "catalog", "metalake"}) {+ init();+ performDeletionTestLogic(param);+ }+ }++ private void performDeletionTestLogic(String input) throws IOException {+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);// Create a model entityModelEntity modelEntity =@@ -495,7 +496,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {"model1 comment",0,properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelMetaService.getInstance().insertModel(modelEntity, false));@@ -509,7 +510,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {aliases,"test comment",properties,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity));@@ -522,7 +523,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {null,null,null,- auditInfo);+ AUDIT_INFO);Assertions.assertDoesNotThrow(() -> ModelVersionMetaService.getInstance().insertModelVersion(modelVersionEntity1));@@ -579,9 +580,9 @@ public class TestModelVersionMetaService extends TestJDBCBackend {verifyModelVersionExists(getModelVersionIdent(modelEntity.nameIdentifier(), "alias2"));}- @Test+ @TestTemplatevoid testUpdateVersionComment() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);Map<String, String> properties = ImmutableMap.of("k1", "v1");String modelName = randomModelName();@@ -600,7 +601,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {modelComment,0,properties,- auditInfo);+ AUDIT_INFO);ModelVersionEntity modelVersionEntity =createModelVersionEntity(@@ -610,7 +611,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {modelVersionAliases,modelVersionComment,properties,- auditInfo);+ AUDIT_INFO);ModelVersionEntity updatedModelVersionEntity =createModelVersionEntity(@@ -662,9 +663,9 @@ public class TestModelVersionMetaService extends TestJDBCBackend {updateCommentUpdater));}- @Test+ @TestTemplatevoid testAlterModelVersionProperties() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);Map<String, String> properties = ImmutableMap.of("k1", "v1", "k2", "v2");String modelName = randomModelName();@@ -684,7 +685,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {modelComment,0,properties,- auditInfo);+ AUDIT_INFO);ModelVersionEntity modelVersionEntity =createModelVersionEntity(@@ -694,7 +695,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {modelVersionAliases,modelVersionComment,properties,- auditInfo);+ AUDIT_INFO);ModelVersionEntity updatedModelVersionEntity =createModelVersionEntity(@@ -746,9 +747,9 @@ public class TestModelVersionMetaService extends TestJDBCBackend {updatePropertiesUpdater));}- @Test+ @TestTemplatevoid testUpdateModelVersionUri() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);Map<String, String> properties = ImmutableMap.of("k1", "v1", "k2", "v2");String modelName = randomModelName();@@ -766,7 +767,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {modelComment,0,properties,- auditInfo);+ AUDIT_INFO);ModelVersionEntity modelVersionEntity =createModelVersionEntity(@@ -776,7 +777,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {modelVersionAliases,modelVersionComment,properties,- auditInfo);+ AUDIT_INFO);Map<String, String> newModelVersionUris = ImmutableMap.of("n1", "u1-1", "n2", "u2");ModelVersionEntity updatedModelVersionEntity =@@ -829,9 +830,9 @@ public class TestModelVersionMetaService extends TestJDBCBackend {updatePropertiesUpdater));}- @Test+ @TestTemplatevoid testUpdateModelVersionAliases() throws IOException {- createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, auditInfo);+ createParentEntities(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME, AUDIT_INFO);Map<String, String> properties = ImmutableMap.of("k1", "v1", "k2", "v2");String modelName = randomModelName();@@ -850,7 +851,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {modelComment,0,properties,- auditInfo);+ AUDIT_INFO);ModelVersionEntity modelVersionEntity =createModelVersionEntity(@@ -860,7 +861,7 @@ public class TestModelVersionMetaService extends TestJDBCBackend {modelVersionAliases,modelVersionComment,properties,- auditInfo);+ AUDIT_INFO);ModelVersionEntity updatedModelVersionEntity =createModelVersionEntity(@@ -943,4 +944,23 @@ public class TestModelVersionMetaService extends TestJDBCBackend {private String randomModelName() {return "model_" + UUID.randomUUID().toString().replace("-", "");}++ private ModelVersionEntity createModelVersionEntity(+ NameIdentifier modelId,+ Integer version,+ Map<String, String> modelUris,+ List<String> aliases,+ String comment,+ Map<String, String> properties,+ AuditInfo auditInfo) {+ return ModelVersionEntity.builder()+ .withModelIdentifier(modelId)+ .withVersion(version)+ .withUris(modelUris)+ .withAliases(aliases)+ .withComment(comment)+ .withProperties(properties)+ .withAuditInfo(auditInfo)+ .build();+ }}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOwnerMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOwnerMetaService.javaindex 71fe73598b..8f42bb55c6 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOwnerMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOwnerMetaService.java@@ -19,7 +19,10 @@package org.apache.gravitino.storage.relational.service;import java.io.IOException;-import java.time.Instant;+import java.sql.Connection;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;import org.apache.gravitino.Entity;import org.apache.gravitino.Namespace;import org.apache.gravitino.authorization.AuthorizationUtils;@@ -36,34 +39,37 @@ import org.apache.gravitino.meta.TopicEntity;import org.apache.gravitino.meta.UserEntity;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;class TestOwnerMetaService extends TestJDBCBackend {- String metalakeName = "metalake";+ private static final String METALAKE_NAME = "metalake_for_owner_test";+ private static final String CATALOG_NAME = "catalog_for_owner_test";+ private static final String SCHEMA_NAME = "schema_for_owner_test";+ private static final String TABLE_NAME = "table_for_owner_test";+ private static final String FILESET_NAME = "fileset_for_owner_test";+ private static final String TOPIC_NAME = "topic_for_owner_test";- private final AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();-- @Test+ @TestTemplatevoid testDifferentOwners() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);+UserEntity user =createUserEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofUserNamespace(metalakeName),+ AuthorizationUtils.ofUserNamespace(METALAKE_NAME),"user",- auditInfo);+ AUDIT_INFO);backend.insert(user, false);GroupEntity group =createGroupEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofGroupNamespace(metalakeName),+ AuthorizationUtils.ofGroupNamespace(METALAKE_NAME),"group",- auditInfo);+ AUDIT_INFO);backend.insert(group, false);// Test no owner@@ -91,84 +97,63 @@ class TestOwnerMetaService extends TestJDBCBackend {Assertions.assertEquals("group", ((GroupEntity) entity).name());}- @Test+ @TestTemplatevoid testDifferentEntities() throws IOException {- String catalogName = "catalog";- String schemaName = "schema";- String tableName = "table";- String filesetName = "fileset";- String topicName = "topic";String userName = "user";String groupName = "group";String roleName = "role";- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName),- catalogName,- auditInfo);- backend.insert(catalog, false);-- SchemaEntity schema =- createSchemaEntity(- RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalogName),- schemaName,- auditInfo);- backend.insert(schema, false);+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);+ CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, CATALOG_NAME);+ SchemaEntity schema = createAndInsertSchema(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME);TableEntity table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalogName, schemaName),- tableName,- auditInfo);+ Namespace.of(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),+ TABLE_NAME,+ AUDIT_INFO);backend.insert(table, false);TopicEntity topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalogName, schemaName),- topicName,- auditInfo);+ Namespace.of(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),+ TOPIC_NAME,+ AUDIT_INFO);backend.insert(topic, false);FilesetEntity fileset =createFilesetEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalogName, schemaName),- filesetName,- auditInfo);+ Namespace.of(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),+ FILESET_NAME,+ AUDIT_INFO);backend.insert(fileset, false);UserEntity user =createUserEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofUserNamespace(metalakeName),+ AuthorizationUtils.ofUserNamespace(METALAKE_NAME),userName,- auditInfo);+ AUDIT_INFO);backend.insert(user, false);GroupEntity group =createGroupEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofGroupNamespace(metalakeName),+ AuthorizationUtils.ofGroupNamespace(METALAKE_NAME),groupName,- auditInfo);+ AUDIT_INFO);backend.insert(group, false);RoleEntity role =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),roleName,- auditInfo,- catalogName);+ AUDIT_INFO,+ CATALOG_NAME);backend.insert(role, false);OwnerMetaService.getInstance()@@ -188,96 +173,80 @@ class TestOwnerMetaService extends TestJDBCBackend {Entity entity =OwnerMetaService.getInstance().getOwner(metalake.nameIdentifier(), metalake.type()).get();- Assertions.assertTrue(entity instanceof UserEntity);+ Assertions.assertInstanceOf(UserEntity.class, entity);Assertions.assertEquals("user", ((UserEntity) entity).name());entity =OwnerMetaService.getInstance().getOwner(catalog.nameIdentifier(), catalog.type()).get();- Assertions.assertTrue(entity instanceof UserEntity);+ Assertions.assertInstanceOf(UserEntity.class, entity);Assertions.assertEquals("user", ((UserEntity) entity).name());entity = OwnerMetaService.getInstance().getOwner(schema.nameIdentifier(), schema.type()).get();- Assertions.assertTrue(entity instanceof UserEntity);+ Assertions.assertInstanceOf(UserEntity.class, entity);Assertions.assertEquals("user", ((UserEntity) entity).name());entity = OwnerMetaService.getInstance().getOwner(table.nameIdentifier(), table.type()).get();- Assertions.assertTrue(entity instanceof UserEntity);+ Assertions.assertInstanceOf(UserEntity.class, entity);Assertions.assertEquals("user", ((UserEntity) entity).name());entity = OwnerMetaService.getInstance().getOwner(topic.nameIdentifier(), topic.type()).get();- Assertions.assertTrue(entity instanceof UserEntity);+ Assertions.assertInstanceOf(UserEntity.class, entity);Assertions.assertEquals("user", ((UserEntity) entity).name());entity =OwnerMetaService.getInstance().getOwner(fileset.nameIdentifier(), fileset.type()).get();- Assertions.assertTrue(entity instanceof UserEntity);+ Assertions.assertInstanceOf(UserEntity.class, entity);Assertions.assertEquals("user", ((UserEntity) entity).name());entity = OwnerMetaService.getInstance().getOwner(role.nameIdentifier(), role.type()).get();- Assertions.assertTrue(entity instanceof UserEntity);+ Assertions.assertInstanceOf(UserEntity.class, entity);Assertions.assertEquals("user", ((UserEntity) entity).name());}- @Test+ @TestTemplatepublic void testDeleteMetadataObject() throws IOException {- String metalakeName = "metalake";- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);- backend.insert(catalog, false);-- SchemaEntity schema =- createSchemaEntity(- RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog"),- "schema",- auditInfo);- backend.insert(schema, false);+ createAndInsertMakeLake(METALAKE_NAME);+ CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, CATALOG_NAME);+ SchemaEntity schema = createAndInsertSchema(METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME);FilesetEntity fileset =createFilesetEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"fileset",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);TableEntity table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"table",- auditInfo);+ AUDIT_INFO);backend.insert(table, false);TopicEntity topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"topic",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);ModelEntity model =createModelEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"model","comment",1,null,- auditInfo);+ AUDIT_INFO);backend.insert(model, false);UserEntity user =createUserEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofUserNamespace(metalakeName),+ AuthorizationUtils.ofUserNamespace(METALAKE_NAME),"user",- auditInfo);+ AUDIT_INFO);backend.insert(user, false);OwnerMetaService.getInstance()@@ -329,47 +298,50 @@ class TestOwnerMetaService extends TestJDBCBackend {// Test to delete catalog with cascade modecatalog =createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);+ RandomIdGenerator.INSTANCE.nextId(),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME),+ CATALOG_NAME,+ AUDIT_INFO);backend.insert(catalog, false);schema =createSchemaEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog"),- "schema",- auditInfo);+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME),+ SCHEMA_NAME,+ AUDIT_INFO);backend.insert(schema, false);fileset =createFilesetEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"fileset",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"table",- auditInfo);+ AUDIT_INFO);backend.insert(table, false);topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"topic",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);model =createModelEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"model","comment",1,null,- auditInfo);+ AUDIT_INFO);backend.insert(model, false);OwnerMetaService.getInstance()@@ -392,50 +364,53 @@ class TestOwnerMetaService extends TestJDBCBackend {// Test to delete schema with cascade modecatalog =createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);+ RandomIdGenerator.INSTANCE.nextId(),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME),+ CATALOG_NAME,+ AUDIT_INFO);backend.insert(catalog, false);schema =createSchemaEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog"),- "schema",- auditInfo);+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME),+ SCHEMA_NAME,+ AUDIT_INFO);backend.insert(schema, false);fileset =createFilesetEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"fileset",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"table",- auditInfo);+ AUDIT_INFO);backend.insert(table, false);topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"topic",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);model =createModelEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"model","comment",1,null,- auditInfo);+ AUDIT_INFO);backend.insert(model, false);OwnerMetaService.getInstance()@@ -459,43 +434,43 @@ class TestOwnerMetaService extends TestJDBCBackend {schema =createSchemaEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog"),- "schema",- auditInfo);+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME),+ SCHEMA_NAME,+ AUDIT_INFO);backend.insert(schema, false);fileset =createFilesetEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"fileset",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"table",- auditInfo);+ AUDIT_INFO);backend.insert(table, false);topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"topic",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);model =createModelEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),"model","comment",1,null,- auditInfo);+ AUDIT_INFO);backend.insert(model, false);OwnerMetaService.getInstance()@@ -515,4 +490,34 @@ class TestOwnerMetaService extends TestJDBCBackend {Assertions.assertEquals(24, countAllOwnerRel(user.id()));Assertions.assertEquals(0, countActiveOwnerRel(user.id()));}++ private Integer countAllOwnerRel(Long ownerId) {+ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);+ Connection connection = sqlSession.getConnection();+ Statement statement1 = connection.createStatement();+ ResultSet rs1 =+ statement1.executeQuery(+ String.format("SELECT count(*) FROM owner_meta WHERE owner_id = %d", ownerId))) {+ if (rs1.next()) {+ return rs1.getInt(1);+ } else {+ throw new RuntimeException("Doesn't contain data");+ }+ } catch (SQLException se) {+ throw new RuntimeException("SQL execution failed", se);+ }+ }++ private GroupEntity createGroupEntity(+ Long id, Namespace namespace, String name, AuditInfo auditInfo) {+ return GroupEntity.builder()+ .withId(id)+ .withName(name)+ .withNamespace(namespace)+ .withRoleNames(null)+ .withRoleIds(null)+ .withAuditInfo(auditInfo)+ .build();+ }}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyMetaService.javaindex 23d06653c6..4e0739e287 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestPolicyMetaService.java@@ -18,6 +18,11 @@*/package org.apache.gravitino.storage.relational.service;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import com.google.common.collect.ImmutableMap;import com.google.common.collect.ImmutableSet;import java.io.IOException;@@ -27,6 +32,7 @@ import java.sql.SQLException;import java.sql.Statement;import java.time.Instant;import java.util.List;+import java.util.Map;import java.util.Set;import java.util.stream.Collectors;import org.apache.gravitino.Entity;@@ -35,7 +41,6 @@ import org.apache.gravitino.MetadataObject;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.exceptions.NoSuchEntityException;-import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.FilesetEntity;@@ -55,13 +60,10 @@ import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.NamespaceUtil;import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;public class TestPolicyMetaService extends TestJDBCBackend {- private final String metalakeName = "metalake_for_policy_test";-- private final AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();+ private static final String METALAKE_NAME = "metalake_for_policy_test";private final Set<MetadataObject.Type> supportedObjectTypes =ImmutableSet.of(@@ -74,11 +76,153 @@ public class TestPolicyMetaService extends TestJDBCBackend {private final PolicyContent content =PolicyContents.custom(ImmutableMap.of("filed1", 123), supportedObjectTypes, null);- @Test+ @TestTemplate+ public void testInsertAlreadyExistsException() throws IOException {+ createAndInsertMakeLake(METALAKE_NAME);++ PolicyEntity policy =+ createPolicy(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofPolicy(METALAKE_NAME),+ "policy",+ AUDIT_INFO);+ PolicyEntity policyCopy =+ createPolicy(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofPolicy(METALAKE_NAME),+ "policy",+ AUDIT_INFO);+ backend.insert(policy, false);+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(policyCopy, false));+ }++ @TestTemplate+ public void testUpdateAlreadyExistsException() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);+ PolicyEntity policy =+ createPolicy(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofPolicy(metalake.name()),+ "policy",+ AUDIT_INFO);+ PolicyEntity policy1 =+ createPolicy(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofPolicy(metalake.name()),+ "policy1",+ AUDIT_INFO);+ backend.insert(policy, false);+ backend.insert(policy1, false);+ assertThrows(+ EntityAlreadyExistsException.class,+ () ->+ backend.update(+ policy1.nameIdentifier(),+ Entity.EntityType.POLICY,+ e -> createPolicy(policy1.id(), policy1.namespace(), "policy", AUDIT_INFO)));+ }++ @TestTemplate+ public void testMetaLifeCycleFromCreationToDeletion() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);++ PolicyEntity policy =+ createPolicy(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofPolicy(metalake.name()),+ "policy",+ AUDIT_INFO);+ backend.insert(policy, false);+ // update policy enabled and version+ PolicyEntity policyV2 =+ PolicyEntity.builder()+ .withId(policy.id())+ .withNamespace(policy.namespace())+ .withName(policy.name())+ .withPolicyType(policy.policyType())+ .withComment(policy.comment())+ .withEnabled(!policy.enabled())+ .withContent(policy.content())+ .withAuditInfo(AUDIT_INFO)+ .build();+ backend.update(policy.nameIdentifier(), Entity.EntityType.POLICY, e -> policyV2);++ // another meta data creation+ String anotherMetaLakeName = METALAKE_NAME + "_another";+ BaseMetalake anotherMetaLake = createAndInsertMakeLake(anotherMetaLakeName);++ PolicyEntity anotherPolicy =+ createPolicy(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofPolicy(anotherMetaLake.name()),+ "another-policy",+ AUDIT_INFO);+ backend.insert(anotherPolicy, false);++ // update another policy enabled and version+ PolicyEntity anotherPolicyV2 =+ PolicyEntity.builder()+ .withId(anotherPolicy.id())+ .withNamespace(anotherPolicy.namespace())+ .withName(anotherPolicy.name())+ .withPolicyType(anotherPolicy.policyType())+ .withComment(anotherPolicy.comment())+ .withEnabled(!anotherPolicy.enabled())+ .withContent(anotherPolicy.content())+ .withAuditInfo(AUDIT_INFO)+ .build();+ backend.update(anotherPolicy.nameIdentifier(), Entity.EntityType.POLICY, e -> anotherPolicyV2);+ // update another policy comment and version+ PolicyEntity anotherPolicyV3 =+ PolicyEntity.builder()+ .withId(anotherPolicy.id())+ .withNamespace(anotherPolicy.namespace())+ .withName(anotherPolicy.name())+ .withPolicyType(anotherPolicy.policyType())+ .withComment("v3")+ .withEnabled(anotherPolicyV2.enabled())+ .withContent(anotherPolicy.content())+ .withAuditInfo(AUDIT_INFO)+ .build();+ backend.update(anotherPolicy.nameIdentifier(), Entity.EntityType.POLICY, e -> anotherPolicyV3);++ List<PolicyEntity> policies = backend.list(policy.namespace(), Entity.EntityType.POLICY, true);+ assertFalse(policies.contains(policy));+ assertTrue(policies.contains(policyV2));+ assertEquals(policyV2.enabled(), policies.get(policies.indexOf(policyV2)).enabled());++ // meta data soft delete+ backend.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE, true);++ // check existence after soft delete+ assertFalse(backend.exists(policy.nameIdentifier(), Entity.EntityType.POLICY));+ assertTrue(backend.exists(anotherPolicy.nameIdentifier(), Entity.EntityType.POLICY));+ // check legacy record after soft delete+ assertTrue(legacyRecordExistsInDB(policy.id(), Entity.EntityType.POLICY));+ assertEquals(2, listPolicyVersions(policy.id()).size());+ assertEquals(3, listPolicyVersions(anotherPolicy.id()).size());++ // meta data hard delete+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.hardDeleteLegacyData(entityType, Instant.now().toEpochMilli() + 1000);+ }+ assertFalse(legacyRecordExistsInDB(policy.id(), Entity.EntityType.POLICY));+ assertEquals(0, listPolicyVersions(policy.id()).size());+ assertEquals(3, listPolicyVersions(anotherPolicy.id()).size());++ // soft delete for old version policy+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.deleteOldVersionData(entityType, 1);+ }+ Map<Integer, Long> versionDeletedMap2 = listPolicyVersions(anotherPolicy.id());+ assertEquals(3, versionDeletedMap2.size());+ assertEquals(1, versionDeletedMap2.values().stream().filter(value -> value == 0L).count());+ assertEquals(2, versionDeletedMap2.values().stream().filter(value -> value != 0L).count());+ }++ @TestTemplatepublic void testInsertAndGetPolicyByIdentifier() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);// Test no policy entity.PolicyMetaService policyMetaService = PolicyMetaService.getInstance();@@ -87,27 +231,27 @@ public class TestPolicyMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->policyMetaService.getPolicyByIdentifier(- NameIdentifierUtil.ofPolicy(metalakeName, "policy1")));- Assertions.assertEquals("No such policy entity: policy1", excep.getMessage());+ NameIdentifierUtil.ofPolicy(metalake.name(), "policy1")));+ assertEquals("No such policy entity: policy1", excep.getMessage());// Test get policy entityPolicyEntity policyEntity =PolicyEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy1")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(metalake.name())).withComment("comment").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content).withEnabled(true)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();policyMetaService.insertPolicy(policyEntity, false);PolicyEntity resultpolicyEntity =policyMetaService.getPolicyByIdentifier(- NameIdentifierUtil.ofPolicy(metalakeName, "policy1"));- Assertions.assertEquals(policyEntity, resultpolicyEntity);+ NameIdentifierUtil.ofPolicy(metalake.name(), "policy1"));+ assertEquals(policyEntity, resultpolicyEntity);// Test with null comment and content properties.PolicyEntity PolicyEntity1 =@@ -115,16 +259,16 @@ public class TestPolicyMetaService extends TestJDBCBackend {.withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy2").withPolicyType(Policy.BuiltInType.CUSTOM)- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))- .withAuditInfo(auditInfo)+ .withNamespace(NamespaceUtil.ofPolicy(metalake.name()))+ .withAuditInfo(AUDIT_INFO).withContent(content).build();policyMetaService.insertPolicy(PolicyEntity1, false);PolicyEntity resultPolicyEntity1 =policyMetaService.getPolicyByIdentifier(- NameIdentifierUtil.ofPolicy(metalakeName, "policy2"));- Assertions.assertEquals(PolicyEntity1, resultPolicyEntity1);+ NameIdentifierUtil.ofPolicy(metalake.name(), "policy2"));+ assertEquals(PolicyEntity1, resultPolicyEntity1);Assertions.assertTrue(resultPolicyEntity1.enabled());Assertions.assertNull(resultPolicyEntity1.comment());Assertions.assertNull(resultPolicyEntity1.content().properties());@@ -134,11 +278,11 @@ public class TestPolicyMetaService extends TestJDBCBackend {PolicyEntity.builder().withId(PolicyEntity1.id()).withName("policy3")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(metalake.name())).withComment("comment").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Assertions.assertThrows(@@ -149,26 +293,24 @@ public class TestPolicyMetaService extends TestJDBCBackend {PolicyEntity resultPolicyEntity2 =policyMetaService.getPolicyByIdentifier(- NameIdentifierUtil.ofPolicy(metalakeName, "policy3"));- Assertions.assertEquals(PolicyEntity2, resultPolicyEntity2);+ NameIdentifierUtil.ofPolicy(metalake.name(), "policy3"));+ assertEquals(PolicyEntity2, resultPolicyEntity2);}- @Test+ @TestTemplatepublic void testCreateAndListPolicies() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ createAndInsertMakeLake(METALAKE_NAME);PolicyMetaService policyMetaService = PolicyMetaService.getInstance();PolicyEntity policyEntity1 =PolicyEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy1")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME)).withComment("comment").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();policyMetaService.insertPolicy(policyEntity1, false);@@ -176,37 +318,35 @@ public class TestPolicyMetaService extends TestJDBCBackend {PolicyEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy2")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME)).withComment("comment").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();policyMetaService.insertPolicy(policyEntity2, false);List<PolicyEntity> policyEntities =- policyMetaService.listPoliciesByNamespace(NamespaceUtil.ofPolicy(metalakeName));- Assertions.assertEquals(2, policyEntities.size());+ policyMetaService.listPoliciesByNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME));+ assertEquals(2, policyEntities.size());Assertions.assertTrue(policyEntities.contains(policyEntity1));Assertions.assertTrue(policyEntities.contains(policyEntity2));}- @Test+ @TestTemplatepublic void testUpdatePolicy() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ createAndInsertMakeLake(METALAKE_NAME);PolicyMetaService policyMetaService = PolicyMetaService.getInstance();PolicyEntity policyEntity1 =PolicyEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy1")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME)).withComment("comment").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();policyMetaService.insertPolicy(policyEntity1, false);@@ -216,41 +356,41 @@ public class TestPolicyMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->policyMetaService.updatePolicy(- NameIdentifierUtil.ofPolicy(metalakeName, "policy2"),+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"),policyEntity -> policyEntity));- Assertions.assertEquals("No such policy entity: policy2", excep.getMessage());+ assertEquals("No such policy entity: policy2", excep.getMessage());// Update policy entity.PolicyEntity policyEntity2 =PolicyEntity.builder().withId(policyEntity1.id()).withName("policy1")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME)).withComment("comment1").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();PolicyEntity updatedPolicyEntity =policyMetaService.updatePolicy(- NameIdentifierUtil.ofPolicy(metalakeName, "policy1"), policyEntity -> policyEntity2);- Assertions.assertEquals(policyEntity2, updatedPolicyEntity);+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1"), policyEntity -> policyEntity2);+ assertEquals(policyEntity2, updatedPolicyEntity);PolicyEntity loadedPolicyEntity =policyMetaService.getPolicyByIdentifier(- NameIdentifierUtil.ofPolicy(metalakeName, "policy1"));- Assertions.assertEquals(policyEntity2, loadedPolicyEntity);+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1"));+ assertEquals(policyEntity2, loadedPolicyEntity);// Update with different id.PolicyEntity policyEntity3 =PolicyEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy1")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME)).withComment("comment1").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Exception excep1 =@@ -258,9 +398,9 @@ public class TestPolicyMetaService extends TestJDBCBackend {IllegalArgumentException.class,() ->policyMetaService.updatePolicy(- NameIdentifierUtil.ofPolicy(metalakeName, "policy1"),+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1"),policyEntity -> policyEntity3));- Assertions.assertEquals(+ assertEquals("The updated policy entity id: "+ policyEntity3.id()+ " must have the same id as the old "@@ -270,34 +410,32 @@ public class TestPolicyMetaService extends TestJDBCBackend {PolicyEntity loadedPolicyEntity1 =policyMetaService.getPolicyByIdentifier(- NameIdentifierUtil.ofPolicy(metalakeName, "policy1"));- Assertions.assertEquals(policyEntity2, loadedPolicyEntity1);+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1"));+ assertEquals(policyEntity2, loadedPolicyEntity1);}- @Test+ @TestTemplatepublic void testDeletePolicy() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ createAndInsertMakeLake(METALAKE_NAME);PolicyMetaService policyMetaService = PolicyMetaService.getInstance();PolicyEntity policyEntity1 =PolicyEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy1")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME)).withComment("comment").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();policyMetaService.insertPolicy(policyEntity1, false);boolean deleted =- policyMetaService.deletePolicy(NameIdentifierUtil.ofPolicy(metalakeName, "policy1"));+ policyMetaService.deletePolicy(NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1"));Assertions.assertTrue(deleted);- deleted = policyMetaService.deletePolicy(NameIdentifierUtil.ofPolicy(metalakeName, "policy1"));+ deleted = policyMetaService.deletePolicy(NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1"));Assertions.assertFalse(deleted);Exception excep =@@ -305,26 +443,24 @@ public class TestPolicyMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->policyMetaService.getPolicyByIdentifier(- NameIdentifierUtil.ofPolicy(metalakeName, "policy1")));- Assertions.assertEquals("No such policy entity: policy1", excep.getMessage());+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1")));+ assertEquals("No such policy entity: policy1", excep.getMessage());}- @Test+ @TestTemplatepublic void testDeleteMetalake() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);PolicyMetaService policyMetaService = PolicyMetaService.getInstance();PolicyEntity policyEntity1 =PolicyEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy1")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME)).withComment("comment").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();policyMetaService.insertPolicy(policyEntity1, false);@@ -334,22 +470,22 @@ public class TestPolicyMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->policyMetaService.getPolicyByIdentifier(- NameIdentifierUtil.ofPolicy(metalakeName, "policy1")));+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1")));// Test delete metalake with cascade.BaseMetalake metalake1 =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName + "1", auditInfo);+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME + "1", AUDIT_INFO);backend.insert(metalake1, false);PolicyEntity policyEntity2 =PolicyEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy2")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName + "1"))+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME + "1")).withComment("comment").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();policyMetaService.insertPolicy(policyEntity2, false);@@ -359,34 +495,35 @@ public class TestPolicyMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->policyMetaService.getPolicyByIdentifier(- NameIdentifierUtil.ofPolicy(metalakeName + "1", "policy2")));+ NameIdentifierUtil.ofPolicy(METALAKE_NAME + "1", "policy2")));}- @Test+ @TestTemplatepublic void testAssociateAndDisassociatePoliciesWithMetadataObject() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ createAndInsertMakeLake(METALAKE_NAME);CatalogEntity catalog =createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog1", auditInfo);+ RandomIdGenerator.INSTANCE.nextId(),+ Namespace.of(METALAKE_NAME),+ "catalog1",+ AUDIT_INFO);backend.insert(catalog, false);SchemaEntity schema =createSchemaEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name()),+ Namespace.of(METALAKE_NAME, catalog.name()),"schema1",- auditInfo);+ AUDIT_INFO);backend.insert(schema, false);TableEntity table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"table1",- auditInfo);+ AUDIT_INFO);backend.insert(table, false);// Create policies to associate@@ -395,11 +532,11 @@ public class TestPolicyMetaService extends TestJDBCBackend {PolicyEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy1")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME)).withComment("comment").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();policyMetaService.insertPolicy(policyEntity1, false);@@ -407,11 +544,11 @@ public class TestPolicyMetaService extends TestJDBCBackend {PolicyEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy2")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME)).withComment("comment").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();policyMetaService.insertPolicy(policyEntity2, false);@@ -419,39 +556,39 @@ public class TestPolicyMetaService extends TestJDBCBackend {PolicyEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy3")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME)).withComment("comment").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();policyMetaService.insertPolicy(policyEntity3, false);// Test associate policies with metadata objectNameIdentifier[] policiesToAdd =new NameIdentifier[] {- NameIdentifierUtil.ofPolicy(metalakeName, "policy1"),- NameIdentifierUtil.ofPolicy(metalakeName, "policy2"),- NameIdentifierUtil.ofPolicy(metalakeName, "policy3")+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1"),+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"),+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy3")};List<PolicyEntity> policyEntities =policyMetaService.associatePoliciesWithMetadataObject(catalog.nameIdentifier(), catalog.type(), policiesToAdd, new NameIdentifier[0]);- Assertions.assertEquals(3, policyEntities.size());+ assertEquals(3, policyEntities.size());Assertions.assertTrue(policyEntities.contains(policyEntity1));Assertions.assertTrue(policyEntities.contains(policyEntity2));Assertions.assertTrue(policyEntities.contains(policyEntity3));// Test disassociate policies with metadata objectNameIdentifier[] policiesToRemove =- new NameIdentifier[] {NameIdentifierUtil.ofPolicy(metalakeName, "policy1")};+ new NameIdentifier[] {NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy1")};List<PolicyEntity> policyEntities1 =policyMetaService.associatePoliciesWithMetadataObject(catalog.nameIdentifier(), catalog.type(), new NameIdentifier[0], policiesToRemove);- Assertions.assertEquals(2, policyEntities1.size());+ assertEquals(2, policyEntities1.size());Assertions.assertFalse(policyEntities1.contains(policyEntity1));Assertions.assertTrue(policyEntities1.contains(policyEntity2));Assertions.assertTrue(policyEntities1.contains(policyEntity3));@@ -460,7 +597,7 @@ public class TestPolicyMetaService extends TestJDBCBackend {List<PolicyEntity> policyEntities2 =policyMetaService.associatePoliciesWithMetadataObject(catalog.nameIdentifier(), catalog.type(), new NameIdentifier[0], new NameIdentifier[0]);- Assertions.assertEquals(2, policyEntities2.size());+ assertEquals(2, policyEntities2.size());Assertions.assertFalse(policyEntities2.contains(policyEntity1));Assertions.assertTrue(policyEntities2.contains(policyEntity2));Assertions.assertTrue(policyEntities2.contains(policyEntity3));@@ -470,7 +607,7 @@ public class TestPolicyMetaService extends TestJDBCBackend {policyMetaService.associatePoliciesWithMetadataObject(catalog.nameIdentifier(), catalog.type(), policiesToRemove, policiesToRemove);- Assertions.assertEquals(2, policyEntities3.size());+ assertEquals(2, policyEntities3.size());Assertions.assertFalse(policyEntities3.contains(policyEntity1));Assertions.assertTrue(policyEntities3.contains(policyEntity2));Assertions.assertTrue(policyEntities3.contains(policyEntity3));@@ -478,21 +615,21 @@ public class TestPolicyMetaService extends TestJDBCBackend {// Test associate and disassociate in-existent policies with metadata objectNameIdentifier[] policiesToAdd1 =new NameIdentifier[] {- NameIdentifierUtil.ofPolicy(metalakeName, "policy4"),- NameIdentifierUtil.ofPolicy(metalakeName, "policy5")+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy4"),+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy5")};NameIdentifier[] policiesToRemove1 =new NameIdentifier[] {- NameIdentifierUtil.ofPolicy(metalakeName, "policy6"),- NameIdentifierUtil.ofPolicy(metalakeName, "policy7")+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy6"),+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy7")};List<PolicyEntity> policyEntities4 =policyMetaService.associatePoliciesWithMetadataObject(catalog.nameIdentifier(), catalog.type(), policiesToAdd1, policiesToRemove1);- Assertions.assertEquals(2, policyEntities4.size());+ assertEquals(2, policyEntities4.size());Assertions.assertTrue(policyEntities4.contains(policyEntity2));Assertions.assertTrue(policyEntities4.contains(policyEntity3));@@ -508,7 +645,7 @@ public class TestPolicyMetaService extends TestJDBCBackend {policyMetaService.associatePoliciesWithMetadataObject(catalog.nameIdentifier(), catalog.type(), new NameIdentifier[0], policiesToRemove);- Assertions.assertEquals(2, policyEntities5.size());+ assertEquals(2, policyEntities5.size());Assertions.assertTrue(policyEntities5.contains(policyEntity2));Assertions.assertTrue(policyEntities5.contains(policyEntity3));@@ -517,7 +654,7 @@ public class TestPolicyMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->policyMetaService.associatePoliciesWithMetadataObject(- NameIdentifier.of(metalakeName, "non-existent-catalog"),+ NameIdentifier.of(METALAKE_NAME, "non-existent-catalog"),catalog.type(),policiesToAdd,policiesToRemove));@@ -527,7 +664,7 @@ public class TestPolicyMetaService extends TestJDBCBackend {policyMetaService.associatePoliciesWithMetadataObject(schema.nameIdentifier(), schema.type(), policiesToAdd, policiesToRemove);- Assertions.assertEquals(2, policyEntities6.size());+ assertEquals(2, policyEntities6.size());Assertions.assertTrue(policyEntities6.contains(policyEntity2));Assertions.assertTrue(policyEntities6.contains(policyEntity3));@@ -536,12 +673,12 @@ public class TestPolicyMetaService extends TestJDBCBackend {policyMetaService.associatePoliciesWithMetadataObject(table.nameIdentifier(), table.type(), policiesToAdd, policiesToRemove);- Assertions.assertEquals(2, policyEntities7.size());+ assertEquals(2, policyEntities7.size());Assertions.assertTrue(policyEntities7.contains(policyEntity2));Assertions.assertTrue(policyEntities7.contains(policyEntity3));}- @Test+ @TestTemplatepublic void testListPoliciesForMetadataObject() throws IOException {testAssociateAndDisassociatePoliciesWithMetadataObject();@@ -550,8 +687,8 @@ public class TestPolicyMetaService extends TestJDBCBackend {// Test list policies for catalogList<PolicyEntity> policyEntities =policyMetaService.listPoliciesForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1"), Entity.EntityType.CATALOG);- Assertions.assertEquals(2, policyEntities.size());+ NameIdentifier.of(METALAKE_NAME, "catalog1"), Entity.EntityType.CATALOG);+ assertEquals(2, policyEntities.size());Assertions.assertTrue(policyEntities.stream().anyMatch(policyEntity -> policyEntity.name().equals("policy2")));Assertions.assertTrue(@@ -560,9 +697,9 @@ public class TestPolicyMetaService extends TestJDBCBackend {// Test list policies for schemaList<PolicyEntity> policyEntities1 =policyMetaService.listPoliciesForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1"), Entity.EntityType.SCHEMA);+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1"), Entity.EntityType.SCHEMA);- Assertions.assertEquals(2, policyEntities1.size());+ assertEquals(2, policyEntities1.size());Assertions.assertTrue(policyEntities1.stream().anyMatch(policyEntity -> policyEntity.name().equals("policy2")));Assertions.assertTrue(@@ -571,10 +708,10 @@ public class TestPolicyMetaService extends TestJDBCBackend {// Test list policies for tableList<PolicyEntity> policyEntities2 =policyMetaService.listPoliciesForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1", "table1"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table1"),Entity.EntityType.TABLE);- Assertions.assertEquals(2, policyEntities2.size());+ assertEquals(2, policyEntities2.size());Assertions.assertTrue(policyEntities2.stream().anyMatch(policyEntity -> policyEntity.name().equals("policy2")));Assertions.assertTrue(@@ -585,11 +722,11 @@ public class TestPolicyMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->policyMetaService.listPoliciesForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1", "table2"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table2"),Entity.EntityType.TABLE));}- @Test+ @TestTemplatepublic void testGetPolicyForMetadataObject() throws IOException {testAssociateAndDisassociatePoliciesWithMetadataObject();@@ -598,35 +735,35 @@ public class TestPolicyMetaService extends TestJDBCBackend {// Test get policy for catalogPolicyEntity policyEntity =policyMetaService.getPolicyForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1"),+ NameIdentifier.of(METALAKE_NAME, "catalog1"),Entity.EntityType.CATALOG,- NameIdentifierUtil.ofPolicy(metalakeName, "policy2"));- Assertions.assertEquals("policy2", policyEntity.name());+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"));+ assertEquals("policy2", policyEntity.name());// Test get policy for schemaPolicyEntity policyEntity1 =policyMetaService.getPolicyForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1"),Entity.EntityType.SCHEMA,- NameIdentifierUtil.ofPolicy(metalakeName, "policy3"));- Assertions.assertEquals("policy3", policyEntity1.name());+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy3"));+ assertEquals("policy3", policyEntity1.name());// Test get policy for tablePolicyEntity policyEntity2 =policyMetaService.getPolicyForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1", "table1"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table1"),Entity.EntityType.TABLE,- NameIdentifierUtil.ofPolicy(metalakeName, "policy2"));- Assertions.assertEquals("policy2", policyEntity2.name());+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"));+ assertEquals("policy2", policyEntity2.name());// Test get policy for non-existent metadata objectAssertions.assertThrows(NoSuchEntityException.class,() ->policyMetaService.getPolicyForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1", "table2"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table2"),Entity.EntityType.TABLE,- NameIdentifierUtil.ofPolicy(metalakeName, "policy2")));+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2")));// Test get policy for non-existent policyThrowable e =@@ -634,13 +771,13 @@ public class TestPolicyMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->policyMetaService.getPolicyForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1", "table1"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table1"),Entity.EntityType.TABLE,- NameIdentifierUtil.ofPolicy(metalakeName, "policy4")));+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy4")));Assertions.assertTrue(e.getMessage().contains("No such policy entity: policy4"));}- @Test+ @TestTemplatepublic void testListAssociatedEntitiesForPolicy() throws IOException {testAssociateAndDisassociatePoliciesWithMetadataObject();@@ -649,9 +786,9 @@ public class TestPolicyMetaService extends TestJDBCBackend {// Test list associated dummy entities for policy2List<GenericEntity> entities =policyMetaService.listAssociatedEntitiesForPolicy(- NameIdentifierUtil.ofPolicy(metalakeName, "policy2"));+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"));- Assertions.assertEquals(3, entities.size());+ assertEquals(3, entities.size());Set<Entity.EntityType> actualTypes =entities.stream().map(GenericEntity::type).collect(Collectors.toSet());Assertions.assertTrue(actualTypes.contains(Entity.EntityType.CATALOG));@@ -661,9 +798,9 @@ public class TestPolicyMetaService extends TestJDBCBackend {// Test list associated dummy entities for policy3List<GenericEntity> entities1 =policyMetaService.listAssociatedEntitiesForPolicy(- NameIdentifierUtil.ofPolicy(metalakeName, "policy3"));+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy3"));- Assertions.assertEquals(3, entities1.size());+ assertEquals(3, entities1.size());Set<Entity.EntityType> actualTypes1 =entities1.stream().map(GenericEntity::type).collect(Collectors.toSet());Assertions.assertTrue(actualTypes1.contains(Entity.EntityType.CATALOG));@@ -673,117 +810,115 @@ public class TestPolicyMetaService extends TestJDBCBackend {// Test list associated dummy entities for non-existent policyList<GenericEntity> entities2 =policyMetaService.listAssociatedEntitiesForPolicy(- NameIdentifierUtil.ofPolicy(metalakeName, "policy4"));- Assertions.assertEquals(0, entities2.size());+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy4"));+ assertEquals(0, entities2.size());// Test metadata object non-exist scenario.backend.delete(- NameIdentifier.of(metalakeName, "catalog1", "schema1", "table1"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table1"),Entity.EntityType.TABLE,false);List<GenericEntity> entities3 =policyMetaService.listAssociatedEntitiesForPolicy(- NameIdentifierUtil.ofPolicy(metalakeName, "policy2"));+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"));- Assertions.assertEquals(2, entities3.size());+ assertEquals(2, entities3.size());Set<Entity.EntityType> actualTypes3 =entities3.stream().map(GenericEntity::type).collect(Collectors.toSet());Assertions.assertTrue(actualTypes3.contains(Entity.EntityType.CATALOG));Assertions.assertTrue(actualTypes3.contains(Entity.EntityType.SCHEMA));backend.delete(- NameIdentifier.of(metalakeName, "catalog1", "schema1"), Entity.EntityType.SCHEMA, false);+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1"), Entity.EntityType.SCHEMA, false);List<GenericEntity> entities4 =policyMetaService.listAssociatedEntitiesForPolicy(- NameIdentifierUtil.ofPolicy(metalakeName, "policy2"));+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"));- Assertions.assertEquals(1, entities4.size());+ assertEquals(1, entities4.size());Set<Entity.EntityType> actualTypes4 =entities4.stream().map(GenericEntity::type).collect(Collectors.toSet());Assertions.assertTrue(actualTypes4.contains(Entity.EntityType.CATALOG));- backend.delete(NameIdentifier.of(metalakeName, "catalog1"), Entity.EntityType.CATALOG, false);+ backend.delete(NameIdentifier.of(METALAKE_NAME, "catalog1"), Entity.EntityType.CATALOG, false);List<GenericEntity> entities5 =policyMetaService.listAssociatedEntitiesForPolicy(- NameIdentifierUtil.ofPolicy(metalakeName, "policy2"));+ NameIdentifierUtil.ofPolicy(METALAKE_NAME, "policy2"));- Assertions.assertEquals(0, entities5.size());+ assertEquals(0, entities5.size());}- @Test+ @TestTemplatepublic void testDeleteMetadataObjectForPolicy() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ createAndInsertMakeLake(METALAKE_NAME);PolicyMetaService policyMetaService = PolicyMetaService.getInstance();PolicyEntity policyEntity1 =PolicyEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("policy1")- .withNamespace(NamespaceUtil.ofPolicy(metalakeName))+ .withNamespace(NamespaceUtil.ofPolicy(METALAKE_NAME)).withComment("comment").withPolicyType(Policy.BuiltInType.CUSTOM).withContent(content)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();policyMetaService.insertPolicy(policyEntity1, false);// 1. Test non-cascade deletionEntitiesToTest entities = createAndAssociateEntities("catalog1", "schema1", policyEntity1);- Assertions.assertEquals(6, countActivePolicyRel(policyEntity1.id()));- Assertions.assertEquals(6, countAllPolicyRel(policyEntity1.id()));+ assertEquals(6, countActivePolicyRel(policyEntity1.id()));+ assertEquals(6, countAllPolicyRel(policyEntity1.id()));// Test to delete a modelModelMetaService.getInstance().deleteModel(entities.model.nameIdentifier());- Assertions.assertEquals(5, countActivePolicyRel(policyEntity1.id()));- Assertions.assertEquals(6, countAllPolicyRel(policyEntity1.id()));+ assertEquals(5, countActivePolicyRel(policyEntity1.id()));+ assertEquals(6, countAllPolicyRel(policyEntity1.id()));// Test to drop a tableTableMetaService.getInstance().deleteTable(entities.table.nameIdentifier());- Assertions.assertEquals(4, countActivePolicyRel(policyEntity1.id()));- Assertions.assertEquals(6, countAllPolicyRel(policyEntity1.id()));+ assertEquals(4, countActivePolicyRel(policyEntity1.id()));+ assertEquals(6, countAllPolicyRel(policyEntity1.id()));// Test to drop a topicTopicMetaService.getInstance().deleteTopic(entities.topic.nameIdentifier());- Assertions.assertEquals(3, countActivePolicyRel(policyEntity1.id()));- Assertions.assertEquals(6, countAllPolicyRel(policyEntity1.id()));+ assertEquals(3, countActivePolicyRel(policyEntity1.id()));+ assertEquals(6, countAllPolicyRel(policyEntity1.id()));// Test to drop a filesetFilesetMetaService.getInstance().deleteFileset(entities.fileset.nameIdentifier());- Assertions.assertEquals(2, countActivePolicyRel(policyEntity1.id()));- Assertions.assertEquals(6, countAllPolicyRel(policyEntity1.id()));+ assertEquals(2, countActivePolicyRel(policyEntity1.id()));+ assertEquals(6, countAllPolicyRel(policyEntity1.id()));// Test to drop a schemaSchemaMetaService.getInstance().deleteSchema(entities.schema.nameIdentifier(), false);- Assertions.assertEquals(1, countActivePolicyRel(policyEntity1.id()));- Assertions.assertEquals(6, countAllPolicyRel(policyEntity1.id()));+ assertEquals(1, countActivePolicyRel(policyEntity1.id()));+ assertEquals(6, countAllPolicyRel(policyEntity1.id()));// Test to drop a catalogCatalogMetaService.getInstance().deleteCatalog(entities.catalog.nameIdentifier(), false);- Assertions.assertEquals(0, countActivePolicyRel(policyEntity1.id()));- Assertions.assertEquals(6, countAllPolicyRel(policyEntity1.id()));+ assertEquals(0, countActivePolicyRel(policyEntity1.id()));+ assertEquals(6, countAllPolicyRel(policyEntity1.id()));// 2. Test cascade deletion for catalogEntitiesToTest entitiesForCascadeCatalog =createAndAssociateEntities("catalog2", "schema2", policyEntity1);CatalogMetaService.getInstance().deleteCatalog(entitiesForCascadeCatalog.catalog.nameIdentifier(), true);- Assertions.assertEquals(0, countActivePolicyRel(policyEntity1.id()));+ assertEquals(0, countActivePolicyRel(policyEntity1.id()));// 6 from previous test + 6 from this test- Assertions.assertEquals(12, countAllPolicyRel(policyEntity1.id()));+ assertEquals(12, countAllPolicyRel(policyEntity1.id()));// 3. Test cascade deletion for schemaEntitiesToTest entitiesForCascadeSchema =createAndAssociateEntities("catalog3", "schema3", policyEntity1);SchemaMetaService.getInstance().deleteSchema(entitiesForCascadeSchema.schema.nameIdentifier(), true);- Assertions.assertEquals(1, countActivePolicyRel(policyEntity1.id()));+ assertEquals(1, countActivePolicyRel(policyEntity1.id()));// 12 from previous tests + 6 from this test- Assertions.assertEquals(18, countAllPolicyRel(policyEntity1.id()));+ assertEquals(18, countAllPolicyRel(policyEntity1.id()));}private static class EntitiesToTest {@@ -819,52 +954,52 @@ public class TestPolicyMetaService extends TestJDBCBackend {CatalogEntity catalog =createCatalog(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName),+ Namespace.of(METALAKE_NAME),catalogName,- auditInfo);+ AUDIT_INFO);backend.insert(catalog, false);SchemaEntity schema =createSchemaEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name()),+ Namespace.of(METALAKE_NAME, catalog.name()),schemaName,- auditInfo);+ AUDIT_INFO);backend.insert(schema, false);TableEntity table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"table1",- auditInfo);+ AUDIT_INFO);backend.insert(table, false);TopicEntity topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"topic1",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);FilesetEntity fileset =createFilesetEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"fileset1",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);ModelEntity model =createModelEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"model1","comment",1,null,- auditInfo);+ AUDIT_INFO);backend.insert(model, false);// Associate policy with all entitiesdiff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestRoleMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestRoleMetaService.javaindex ea6b31e1df..fbd17a31d7 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestRoleMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestRoleMetaService.java@@ -19,6 +19,11 @@package org.apache.gravitino.storage.relational.service;+import static org.apache.gravitino.SupportsRelationOperations.Type.OWNER_REL;+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 com.google.common.collect.ImmutableMap;import com.google.common.collect.Lists;import java.io.IOException;@@ -31,7 +36,9 @@ import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;+import java.util.Map;import java.util.function.Function;+import org.apache.gravitino.Entity;import org.apache.gravitino.EntityAlreadyExistsException;import org.apache.gravitino.Namespace;import org.apache.gravitino.authorization.AuthorizationUtils;@@ -45,7 +52,6 @@ import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.FilesetEntity;import org.apache.gravitino.meta.GroupEntity;import org.apache.gravitino.meta.RoleEntity;-import org.apache.gravitino.meta.SchemaEntity;import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.meta.TopicEntity;import org.apache.gravitino.meta.UserEntity;@@ -60,87 +66,208 @@ import org.apache.gravitino.storage.relational.utils.SessionUtils;import org.apache.gravitino.utils.CollectionUtils;import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;class TestRoleMetaService extends TestJDBCBackend {- String metalakeName = "metalake";+ private static final String METALAKE_NAME = "metalake_for_role_test";++ @TestTemplate+ public void testMetaLifeCycleFromCreationToDeletion() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);+ String catalogName = "catalog";+ createAndInsertCatalog(METALAKE_NAME, catalogName);++ String anotherMetalakeName = "another_metalake_for_role_test";+ String anotherCatalogName = "another_catalog";+ createAndInsertMakeLake(anotherMetalakeName);+ createAndInsertCatalog(anotherMetalakeName, anotherCatalogName);++ RoleEntity role =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),+ "role",+ AUDIT_INFO,+ catalogName);+ backend.insert(role, false);+ UserEntity user =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(METALAKE_NAME),+ "user",+ AUDIT_INFO,+ Lists.newArrayList(role.name()),+ Lists.newArrayList(role.id()));+ backend.insert(user, false);+ GroupEntity group =+ createGroupEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofGroupNamespace(METALAKE_NAME),+ "group",+ AUDIT_INFO,+ Lists.newArrayList(role.name()),+ Lists.newArrayList(role.id()));+ backend.insert(group, false);++ RoleEntity anotherRole =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(anotherMetalakeName),+ "another-role",+ AUDIT_INFO,+ anotherCatalogName);+ backend.insert(anotherRole, false);+ UserEntity anotherUser =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(anotherMetalakeName),+ "another-user",+ AUDIT_INFO,+ Lists.newArrayList(anotherRole.name()),+ Lists.newArrayList(anotherRole.id()));+ backend.insert(anotherUser, false);++ GroupEntity anotherGroup =+ createGroupEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofGroupNamespace(anotherMetalakeName),+ "another-group",+ AUDIT_INFO,+ Lists.newArrayList(anotherRole.name()),+ Lists.newArrayList(anotherRole.id()));+ backend.insert(anotherGroup, false);++ RoleEntity roleEntity = backend.get(role.nameIdentifier(), Entity.EntityType.ROLE);+ assertEquals(role, roleEntity);++ // meta data soft delete+ backend.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE, true);++ // check existence after soft delete+ assertFalse(backend.exists(role.nameIdentifier(), Entity.EntityType.ROLE));+ assertTrue(backend.exists(anotherRole.nameIdentifier(), Entity.EntityType.ROLE));++ // check legacy record after soft delete+ assertTrue(legacyRecordExistsInDB(role.id(), Entity.EntityType.ROLE));+ assertEquals(2, countRoleRels(role.id()));+ assertEquals(2, countRoleRels(anotherRole.id()));++ // meta data hard delete+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.hardDeleteLegacyData(entityType, Instant.now().toEpochMilli() + 1000);+ }+ assertFalse(legacyRecordExistsInDB(role.id(), Entity.EntityType.ROLE));+ assertEquals(0, countRoleRels(role.id()));+ assertEquals(2, countRoleRels(anotherRole.id()));+ }- @Test- void getRoleByIdentifier() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();+ @TestTemplate+ public void testGetRoleIdByMetalakeIdAndName() throws IOException {+ String catalogName = "catalog";+ String roleNameWithDot = "role.with.dot";+ String roleNameWithoutDot = "roleWithoutDot";+ createAndInsertMakeLake(METALAKE_NAME);+ createAndInsertCatalog(METALAKE_NAME, catalogName);- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);- backend.insert(catalog, false);+ RoleEntity roleWithDot =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),+ roleNameWithDot,+ AUDIT_INFO,+ catalogName);+ backend.insert(roleWithDot, false);- CatalogEntity anotherCatalog =- createCatalog(+ RoleEntity roleWithoutDot =+ createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake"),- "anotherCatalog",- auditInfo);- backend.insert(anotherCatalog, false);+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),+ roleNameWithoutDot,+ AUDIT_INFO,+ catalogName);+ backend.insert(roleWithoutDot, false);- RoleMetaService roleMetaService = RoleMetaService.getInstance();+ Long metalakeId = MetalakeMetaService.getInstance().getMetalakeIdByName(METALAKE_NAME);++ Long roleIdWithDot =+ RoleMetaService.getInstance().getRoleIdByMetalakeIdAndName(metalakeId, roleNameWithDot);+ assertEquals(roleWithDot.id(), roleIdWithDot);++ Long roleIdWithoutDot =+ RoleMetaService.getInstance().getRoleIdByMetalakeIdAndName(metalakeId, roleNameWithoutDot);+ assertEquals(roleWithoutDot.id(), roleIdWithoutDot);++ UserEntity user =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(METALAKE_NAME),+ "user",+ AUDIT_INFO);+ backend.insert(user, false);++ backend.insertRelation(+ OWNER_REL,+ roleWithoutDot.nameIdentifier(),+ roleWithoutDot.type(),+ user.nameIdentifier(),+ user.type(),+ true);+ assertEquals(1, countActiveOwnerRel(user.id()));+ }+ @TestTemplate+ void testGetRoleByIdentifier() throws IOException {+ createAndInsertMakeLake(METALAKE_NAME);+ String catalogName = "catalog";+ createAndInsertCatalog(METALAKE_NAME, catalogName);++ RoleMetaService roleMetaService = RoleMetaService.getInstance();// get not exist roleAssertions.assertThrows(NoSuchEntityException.class,() ->- roleMetaService.getRoleByIdentifier(AuthorizationUtils.ofRole(metalakeName, "role1")));+ roleMetaService.getRoleByIdentifier(AuthorizationUtils.ofRole(METALAKE_NAME, "role1")));// get roleRoleEntity role1 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role1",- auditInfo,+ AUDIT_INFO,SecurableObjects.ofCatalog(- "catalog", Lists.newArrayList(Privileges.UseCatalog.allow())),+ catalogName, Lists.newArrayList(Privileges.UseCatalog.allow())),ImmutableMap.of("k1", "v1"));-roleMetaService.insertRole(role1, false);- Assertions.assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));++ assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));}- @Test+ @TestTemplatevoid testListRoles() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);- backend.insert(catalog, false);+ createAndInsertMakeLake(METALAKE_NAME);+ String catalogName = "catalog";+ createAndInsertCatalog(METALAKE_NAME, catalogName);RoleEntity role1 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role1",- auditInfo,+ AUDIT_INFO,SecurableObjects.ofCatalog(- "catalog", Lists.newArrayList(Privileges.UseCatalog.allow())),+ catalogName, Lists.newArrayList(Privileges.UseCatalog.allow())),ImmutableMap.of("k1", "v1"));RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role2",- auditInfo,+ AUDIT_INFO,SecurableObjects.ofCatalog(- "catalog", Lists.newArrayList(Privileges.UseCatalog.allow())),+ catalogName, Lists.newArrayList(Privileges.UseCatalog.allow())),ImmutableMap.of("k1", "v1"));backend.insert(role1, false);@@ -148,73 +275,51 @@ class TestRoleMetaService extends TestJDBCBackend {RoleMetaService roleMetaService = RoleMetaService.getInstance();List<RoleEntity> actualRoles =- roleMetaService.listRolesByNamespace(AuthorizationUtils.ofRoleNamespace(metalakeName));+ roleMetaService.listRolesByNamespace(AuthorizationUtils.ofRoleNamespace(METALAKE_NAME));actualRoles.sort(Comparator.comparing(RoleEntity::name));List<RoleEntity> expectRoles = Lists.newArrayList(role1, role2);- Assertions.assertEquals(expectRoles.size(), actualRoles.size());+ assertEquals(expectRoles.size(), actualRoles.size());for (int index = 0; index < expectRoles.size(); index++) {RoleEntity expectRole = expectRoles.get(index);RoleEntity actualRole = actualRoles.get(index);- Assertions.assertEquals(expectRole.name(), actualRole.name());+ assertEquals(expectRole.name(), actualRole.name());}}- @Test- void insertRole() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);- backend.insert(catalog, false);- CatalogEntity anotherCatalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake"),- "anotherCatalog",- auditInfo);- backend.insert(anotherCatalog, false);- CatalogEntity overwriteCatalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake"),- "catalogOverwrite",- auditInfo);- backend.insert(overwriteCatalog, false);-- SchemaEntity schema =- createSchemaEntity(- RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog"),- "schema",- auditInfo);- backend.insert(schema, false);+ @TestTemplate+ void testInsertRole() throws IOException {+ createAndInsertMakeLake(METALAKE_NAME);+ String catalogName = "catalog";+ createAndInsertCatalog(METALAKE_NAME, catalogName);+ String anotherCatalogName = "anotherCatalog";+ createAndInsertCatalog(METALAKE_NAME, anotherCatalogName);+ String overwriteCatalogName = "catalogOverwrite";+ createAndInsertCatalog(METALAKE_NAME, overwriteCatalogName);+ String schemaName = "schema";+ createAndInsertSchema(METALAKE_NAME, catalogName, schemaName);TopicEntity topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(METALAKE_NAME, catalogName, schemaName),"topic",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);FilesetEntity fileset =createFilesetEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(METALAKE_NAME, catalogName, schemaName),"fileset",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);TableEntity table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(METALAKE_NAME, catalogName, schemaName),"table",- auditInfo);+ AUDIT_INFO);backend.insert(table, false);RoleMetaService roleMetaService = RoleMetaService.getInstance();@@ -222,15 +327,15 @@ class TestRoleMetaService extends TestJDBCBackend {// Test with different securable objectsSecurableObject metalakeObject =SecurableObjects.ofMetalake(- "metalake", Lists.newArrayList(Privileges.CreateCatalog.allow()));+ METALAKE_NAME, Lists.newArrayList(Privileges.CreateCatalog.allow()));SecurableObject catalogObject =SecurableObjects.ofCatalog(- "catalog",+ catalogName,Lists.newArrayList(Privileges.UseCatalog.allow(), Privileges.CreateSchema.deny()));SecurableObject schemaObject =SecurableObjects.ofSchema(catalogObject,- "schema",+ schemaName,Lists.newArrayList(Privileges.UseSchema.allow(), Privileges.CreateTable.allow()));SecurableObject topicObject =SecurableObjects.ofTopic(@@ -252,7 +357,7 @@ class TestRoleMetaService extends TestJDBCBackend {topicObject,tableObject,SecurableObjects.ofCatalog(- "anotherCatalog", Lists.newArrayList(Privileges.UseCatalog.allow())));+ anotherCatalogName, Lists.newArrayList(Privileges.UseCatalog.allow())));securableObjects.sort(Comparator.comparing(SecurableObject::fullName));@@ -260,26 +365,26 @@ class TestRoleMetaService extends TestJDBCBackend {RoleEntity role1 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role1",- auditInfo,+ AUDIT_INFO,securableObjects,ImmutableMap.of("k1", "v1"));Assertions.assertThrows(NoSuchEntityException.class,() -> roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));Assertions.assertDoesNotThrow(() -> roleMetaService.insertRole(role1, false));- Assertions.assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));+ assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));// insert duplicate roleRoleEntity role1Exist =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role1",- auditInfo,+ AUDIT_INFO,SecurableObjects.ofCatalog(- "catalog", Lists.newArrayList(Privileges.UseCatalog.allow())),+ catalogName, Lists.newArrayList(Privileges.UseCatalog.allow())),ImmutableMap.of("k1", "v1"));Assertions.assertThrows(EntityAlreadyExistsException.class, () -> roleMetaService.insertRole(role1Exist, false));@@ -288,31 +393,24 @@ class TestRoleMetaService extends TestJDBCBackend {RoleEntity role1Overwrite =createRoleEntity(role1.id(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role1Overwrite",- auditInfo,+ AUDIT_INFO,SecurableObjects.ofCatalog(- "catalogOverwrite", Lists.newArrayList(Privileges.UseCatalog.allow())),+ overwriteCatalogName, Lists.newArrayList(Privileges.UseCatalog.allow())),ImmutableMap.of("k2", "v2"));Assertions.assertDoesNotThrow(() -> roleMetaService.insertRole(role1Overwrite, true));- Assertions.assertEquals(+ assertEquals("role1Overwrite",roleMetaService.getRoleByIdentifier(role1Overwrite.nameIdentifier()).name());- Assertions.assertEquals(+ assertEquals(role1Overwrite, roleMetaService.getRoleByIdentifier(role1Overwrite.nameIdentifier()));}- @Test- void deleteRole() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);- backend.insert(catalog, false);+ @TestTemplate+ void testDeleteRole() throws IOException {+ createAndInsertMakeLake(METALAKE_NAME);+ createAndInsertCatalog(METALAKE_NAME, "catalog");UserMetaService userMetaService = UserMetaService.getInstance();GroupMetaService groupMetaService = GroupMetaService.getInstance();@@ -321,15 +419,15 @@ class TestRoleMetaService extends TestJDBCBackend {// delete not exist roleAssertions.assertThrows(NoSuchEntityException.class,- () -> roleMetaService.deleteRole(AuthorizationUtils.ofRole(metalakeName, "role1")));+ () -> roleMetaService.deleteRole(AuthorizationUtils.ofRole(METALAKE_NAME, "role1")));// delete roleRoleEntity role1 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role1",- auditInfo,+ AUDIT_INFO,SecurableObjects.ofCatalog("catalog", Lists.newArrayList(Privileges.UseCatalog.allow())),ImmutableMap.of("k1", "v1"));@@ -337,7 +435,7 @@ class TestRoleMetaService extends TestJDBCBackend {NoSuchEntityException.class,() -> roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));Assertions.assertDoesNotThrow(() -> roleMetaService.insertRole(role1, false));- Assertions.assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));+ assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));Assertions.assertTrue(roleMetaService.deleteRole(role1.nameIdentifier()));Assertions.assertThrows(NoSuchEntityException.class,@@ -347,9 +445,9 @@ class TestRoleMetaService extends TestJDBCBackend {RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role2",- auditInfo,+ AUDIT_INFO,SecurableObjects.ofCatalog("catalog", Lists.newArrayList(Privileges.UseCatalog.allow())),ImmutableMap.of("k1", "v1"));@@ -357,43 +455,42 @@ class TestRoleMetaService extends TestJDBCBackend {GroupEntity group1 =createGroupEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofGroupNamespace(metalakeName),+ AuthorizationUtils.ofGroupNamespace(METALAKE_NAME),"group1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role2.name()),Lists.newArrayList(role2.id()));GroupEntity group2 =createGroupEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofGroupNamespace(metalakeName),+ AuthorizationUtils.ofGroupNamespace(METALAKE_NAME),"group2",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role2.name()),Lists.newArrayList(role2.id()));groupMetaService.insertGroup(group1, false);groupMetaService.insertGroup(group2, false);- Assertions.assertEquals(+ assertEquals(group1.name(), groupMetaService.getGroupByIdentifier(group1.nameIdentifier()).name());- Assertions.assertEquals(+ assertEquals(group1.roleNames(),groupMetaService.getGroupByIdentifier(group1.nameIdentifier()).roleNames());- Assertions.assertEquals(+ assertEquals(group2.name(), groupMetaService.getGroupByIdentifier(group2.nameIdentifier()).name());- Assertions.assertEquals(+ assertEquals(group2.roleNames(),groupMetaService.getGroupByIdentifier(group2.nameIdentifier()).roleNames());UserEntity user1 =createUserEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofUserNamespace(metalakeName),+ AuthorizationUtils.ofUserNamespace(METALAKE_NAME),"user1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role2.name()),Lists.newArrayList(role2.id()));userMetaService.insertUser(user1, false);- Assertions.assertEquals(- user1.name(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).name());- Assertions.assertEquals(+ assertEquals(user1.name(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).name());+ assertEquals(user1.roleNames(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).roleNames());Assertions.assertTrue(roleMetaService.deleteRole(role2.nameIdentifier()));@@ -404,45 +501,36 @@ class TestRoleMetaService extends TestJDBCBackend {List<UserPO> userRoleRels =SessionUtils.doWithCommitAndFetchResult(UserMetaMapper.class, mapper -> mapper.listUsersByRoleId(role2.id()));- Assertions.assertEquals(- user1.name(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).name());+ assertEquals(user1.name(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).name());Assertions.assertTrue(userRoleRels.isEmpty());List<GroupPO> groupRoleRels =SessionUtils.doWithCommitAndFetchResult(GroupMetaMapper.class, mapper -> mapper.listGroupsByRoleId(role2.id()));- Assertions.assertEquals(+ assertEquals(group1.name(), groupMetaService.getGroupByIdentifier(group1.nameIdentifier()).name());Assertions.assertTrue(groupRoleRels.isEmpty());}- @Test+ @TestTemplatevoid listRolesBySecurableObject() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);- backend.insert(catalog, false);+ createAndInsertMakeLake(METALAKE_NAME);+ CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, "catalog");RoleEntity role1 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role1",- auditInfo,+ AUDIT_INFO,"catalog");RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role2",- auditInfo,+ AUDIT_INFO,"catalog");RoleMetaService roleMetaService = RoleMetaService.getInstance();@@ -452,21 +540,13 @@ class TestRoleMetaService extends TestJDBCBackend {List<RoleEntity> roleEntities =roleMetaService.listRolesByMetadataObject(catalog.nameIdentifier(), catalog.type(), true);roleEntities.sort(Comparator.comparing(RoleEntity::name));- Assertions.assertEquals(Lists.newArrayList(role1, role2), roleEntities);+ assertEquals(Lists.newArrayList(role1, role2), roleEntities);}- @Test- void deleteMetalake() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);- backend.insert(catalog, false);+ @TestTemplate+ void testDeleteMetalake() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);+ CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, "catalog");UserMetaService userMetaService = UserMetaService.getInstance();GroupMetaService groupMetaService = GroupMetaService.getInstance();@@ -475,31 +555,31 @@ class TestRoleMetaService extends TestJDBCBackend {RoleEntity role1 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role1",- auditInfo,+ AUDIT_INFO,"catalog");RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role2",- auditInfo,+ AUDIT_INFO,"catalog");GroupEntity group1 =createGroupEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofGroupNamespace(metalakeName),+ AuthorizationUtils.ofGroupNamespace(METALAKE_NAME),"group1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));UserEntity user1 =createUserEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofUserNamespace(metalakeName),+ AuthorizationUtils.ofUserNamespace(METALAKE_NAME),"user1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));roleMetaService.insertRole(role1, false);@@ -507,12 +587,11 @@ class TestRoleMetaService extends TestJDBCBackend {groupMetaService.insertGroup(group1, false);userMetaService.insertUser(user1, false);- Assertions.assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));- Assertions.assertEquals(role2, roleMetaService.getRoleByIdentifier(role2.nameIdentifier()));- Assertions.assertEquals(+ assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));+ assertEquals(role2, roleMetaService.getRoleByIdentifier(role2.nameIdentifier()));+ assertEquals(group1.name(), groupMetaService.getGroupByIdentifier(group1.nameIdentifier()).name());- Assertions.assertEquals(- user1.name(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).name());+ assertEquals(user1.name(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).name());List<UserPO> userRole1Rels =SessionUtils.doWithCommitAndFetchResult(@@ -526,10 +605,10 @@ class TestRoleMetaService extends TestJDBCBackend {List<GroupPO> groupRole2Rels =SessionUtils.doWithCommitAndFetchResult(GroupMetaMapper.class, mapper -> mapper.listGroupsByRoleId(role2.id()));- Assertions.assertEquals(1, userRole1Rels.size());- Assertions.assertEquals(1, userRole2Rels.size());- Assertions.assertEquals(1, groupRole1Rels.size());- Assertions.assertEquals(1, groupRole2Rels.size());+ assertEquals(1, userRole1Rels.size());+ assertEquals(1, userRole2Rels.size());+ assertEquals(1, groupRole1Rels.size());+ assertEquals(1, groupRole2Rels.size());Assertions.assertTrue(CatalogMetaService.getInstance().deleteCatalog(catalog.nameIdentifier(), false));@@ -568,26 +647,18 @@ class TestRoleMetaService extends TestJDBCBackend {.isEmpty());}- @Test+ @TestTemplatevoid testUpdateRole() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);- backend.insert(catalog, false);+ createAndInsertMakeLake(METALAKE_NAME);+ createAndInsertCatalog(METALAKE_NAME, "catalog");RoleMetaService roleMetaService = RoleMetaService.getInstance();RoleEntity roleEntity =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role1",- auditInfo,+ AUDIT_INFO,"catalog");roleMetaService.insertRole(roleEntity, false);@@ -605,7 +676,7 @@ class TestRoleMetaService extends TestJDBCBackend {List<SecurableObject> securableObjects = Lists.newArrayList(role.securableObjects());securableObjects.add(SecurableObjects.ofMetalake(- metalakeName, Lists.newArrayList(Privileges.CreateTable.allow())));+ METALAKE_NAME, Lists.newArrayList(Privileges.CreateTable.allow())));return RoleEntity.builder().withId(role.id())@@ -620,17 +691,17 @@ class TestRoleMetaService extends TestJDBCBackend {Assertions.assertNotNull(roleMetaService.updateRole(roleEntity.nameIdentifier(), grantUpdater));RoleEntity grantRole = roleMetaService.getRoleByIdentifier(roleEntity.nameIdentifier());- Assertions.assertEquals(grantRole.id(), roleEntity.id());- Assertions.assertEquals(grantRole.name(), roleEntity.name());- Assertions.assertEquals("creator", grantRole.auditInfo().creator());- Assertions.assertEquals("grantRole", grantRole.auditInfo().lastModifier());+ assertEquals(grantRole.id(), roleEntity.id());+ assertEquals(grantRole.name(), roleEntity.name());+ assertEquals("creator", grantRole.auditInfo().creator());+ assertEquals("grantRole", grantRole.auditInfo().lastModifier());Assertions.assertTrue(CollectionUtils.isEqualCollection(Lists.newArrayList(SecurableObjects.ofCatalog("catalog", Lists.newArrayList(Privileges.UseCatalog.allow())),SecurableObjects.ofMetalake(- metalakeName, Lists.newArrayList(Privileges.CreateTable.allow()))),+ METALAKE_NAME, Lists.newArrayList(Privileges.CreateTable.allow()))),grantRole.securableObjects()));// revoke privileges from the role@@ -663,14 +734,14 @@ class TestRoleMetaService extends TestJDBCBackend {roleMetaService.updateRole(roleEntity.nameIdentifier(), revokeUpdater);RoleEntity revokeRole = roleMetaService.getRoleByIdentifier(roleEntity.nameIdentifier());- Assertions.assertEquals(revokeRole.id(), roleEntity.id());- Assertions.assertEquals(revokeRole.name(), roleEntity.name());- Assertions.assertEquals("creator", revokeRole.auditInfo().creator());- Assertions.assertEquals("revokeRole", revokeRole.auditInfo().lastModifier());- Assertions.assertEquals(+ assertEquals(revokeRole.id(), roleEntity.id());+ assertEquals(revokeRole.name(), roleEntity.name());+ assertEquals("creator", revokeRole.auditInfo().creator());+ assertEquals("revokeRole", revokeRole.auditInfo().lastModifier());+ assertEquals(Lists.newArrayList(SecurableObjects.ofMetalake(- metalakeName, Lists.newArrayList(Privileges.CreateTable.allow()))),+ METALAKE_NAME, Lists.newArrayList(Privileges.CreateTable.allow()))),revokeRole.securableObjects());// grant and revoke privileges for the role@@ -703,11 +774,11 @@ class TestRoleMetaService extends TestJDBCBackend {roleMetaService.updateRole(roleEntity.nameIdentifier(), grantRevokeUpdater);RoleEntity grantRevokeRole = roleMetaService.getRoleByIdentifier(roleEntity.nameIdentifier());- Assertions.assertEquals(grantRevokeRole.id(), roleEntity.id());- Assertions.assertEquals(grantRevokeRole.name(), roleEntity.name());- Assertions.assertEquals("creator", grantRevokeRole.auditInfo().creator());- Assertions.assertEquals("grantRevokeRole", grantRevokeRole.auditInfo().lastModifier());- Assertions.assertEquals(+ assertEquals(grantRevokeRole.id(), roleEntity.id());+ assertEquals(grantRevokeRole.name(), roleEntity.name());+ assertEquals("creator", grantRevokeRole.auditInfo().creator());+ assertEquals("grantRevokeRole", grantRevokeRole.auditInfo().lastModifier());+ assertEquals(Lists.newArrayList(SecurableObjects.ofCatalog("catalog", Lists.newArrayList(Privileges.CreateTable.allow()))),@@ -739,24 +810,17 @@ class TestRoleMetaService extends TestJDBCBackend {roleMetaService.updateRole(roleEntity.nameIdentifier(), revokeMultipleUpdater);RoleEntity revokeMultipleRole =roleMetaService.getRoleByIdentifier(roleEntity.nameIdentifier());- Assertions.assertEquals(revokeMultipleRole.id(), roleEntity.id());- Assertions.assertEquals(revokeMultipleRole.name(), roleEntity.name());- Assertions.assertEquals("creator", revokeMultipleRole.auditInfo().creator());- Assertions.assertEquals("revokeMultiple", revokeMultipleRole.auditInfo().lastModifier());+ assertEquals(revokeMultipleRole.id(), roleEntity.id());+ assertEquals(revokeMultipleRole.name(), roleEntity.name());+ assertEquals("creator", revokeMultipleRole.auditInfo().creator());+ assertEquals("revokeMultiple", revokeMultipleRole.auditInfo().lastModifier());Assertions.assertTrue(revokeMultipleRole.securableObjects().isEmpty());}- @Test- void deleteMetalakeCascade() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);- backend.insert(catalog, false);+ @TestTemplate+ void testDeleteMetalakeCascade() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);+ createAndInsertCatalog(METALAKE_NAME, "catalog");UserMetaService userMetaService = UserMetaService.getInstance();GroupMetaService groupMetaService = GroupMetaService.getInstance();@@ -765,31 +829,31 @@ class TestRoleMetaService extends TestJDBCBackend {RoleEntity role1 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role1",- auditInfo,+ AUDIT_INFO,"catalog");RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role2",- auditInfo,+ AUDIT_INFO,"catalog");GroupEntity group1 =createGroupEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofGroupNamespace(metalakeName),+ AuthorizationUtils.ofGroupNamespace(METALAKE_NAME),"group1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));UserEntity user1 =createUserEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofUserNamespace(metalakeName),+ AuthorizationUtils.ofUserNamespace(METALAKE_NAME),"user1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));roleMetaService.insertRole(role1, false);@@ -797,12 +861,11 @@ class TestRoleMetaService extends TestJDBCBackend {groupMetaService.insertGroup(group1, false);userMetaService.insertUser(user1, false);- Assertions.assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));- Assertions.assertEquals(role2, roleMetaService.getRoleByIdentifier(role2.nameIdentifier()));- Assertions.assertEquals(+ assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));+ assertEquals(role2, roleMetaService.getRoleByIdentifier(role2.nameIdentifier()));+ assertEquals(group1.name(), groupMetaService.getGroupByIdentifier(group1.nameIdentifier()).name());- Assertions.assertEquals(- user1.name(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).name());+ assertEquals(user1.name(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).name());List<UserPO> userRole1Rels =SessionUtils.doWithCommitAndFetchResult(@@ -816,10 +879,10 @@ class TestRoleMetaService extends TestJDBCBackend {List<GroupPO> groupRole2Rels =SessionUtils.doWithCommitAndFetchResult(GroupMetaMapper.class, mapper -> mapper.listGroupsByRoleId(role2.id()));- Assertions.assertEquals(1, userRole1Rels.size());- Assertions.assertEquals(1, userRole2Rels.size());- Assertions.assertEquals(1, groupRole1Rels.size());- Assertions.assertEquals(1, groupRole2Rels.size());+ assertEquals(1, userRole1Rels.size());+ assertEquals(1, userRole2Rels.size());+ assertEquals(1, groupRole1Rels.size());+ assertEquals(1, groupRole2Rels.size());Assertions.assertTrue(MetalakeMetaService.getInstance().deleteMetalake(metalake.nameIdentifier(), true));@@ -855,17 +918,10 @@ class TestRoleMetaService extends TestJDBCBackend {.isEmpty());}- @Test- void deleteRoleMetasByLegacyTimeline() throws IOException {- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);- backend.insert(catalog, false);+ @TestTemplate+ void testDeleteRoleMetasByLegacyTimeline() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);+ createAndInsertCatalog(METALAKE_NAME, "catalog");UserMetaService userMetaService = UserMetaService.getInstance();GroupMetaService groupMetaService = GroupMetaService.getInstance();@@ -874,16 +930,16 @@ class TestRoleMetaService extends TestJDBCBackend {RoleEntity role1 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role1",- auditInfo,+ AUDIT_INFO,"catalog");RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace(metalakeName),+ AuthorizationUtils.ofRoleNamespace(METALAKE_NAME),"role2",- auditInfo,+ AUDIT_INFO,"catalog");roleMetaService.insertRole(role1, false);roleMetaService.insertRole(role2, false);@@ -891,9 +947,9 @@ class TestRoleMetaService extends TestJDBCBackend {UserEntity user1 =createUserEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofUserNamespace(metalakeName),+ AuthorizationUtils.ofUserNamespace(METALAKE_NAME),"user1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));userMetaService.insertUser(user1, false);@@ -901,9 +957,9 @@ class TestRoleMetaService extends TestJDBCBackend {GroupEntity group1 =createGroupEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofUserNamespace(metalakeName),+ AuthorizationUtils.ofUserNamespace(METALAKE_NAME),"group1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(role1.name(), role2.name()),Lists.newArrayList(role1.id(), role2.id()));groupMetaService.insertGroup(group1, false);@@ -911,19 +967,18 @@ class TestRoleMetaService extends TestJDBCBackend {// hard delete before soft deleteint deletedCount =roleMetaService.deleteRoleMetasByLegacyTimeline(Instant.now().toEpochMilli() + 1000, 4);- Assertions.assertEquals(0, deletedCount);+ assertEquals(0, deletedCount);- Assertions.assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));- Assertions.assertEquals(role2, roleMetaService.getRoleByIdentifier(role2.nameIdentifier()));- Assertions.assertEquals(+ assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));+ assertEquals(role2, roleMetaService.getRoleByIdentifier(role2.nameIdentifier()));+ assertEquals(group1.name(), groupMetaService.getGroupByIdentifier(group1.nameIdentifier()).name());- Assertions.assertEquals(- user1.name(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).name());- Assertions.assertEquals(2, roleMetaService.listRolesByUserId(user1.id()).size());- Assertions.assertEquals(2, roleMetaService.listRolesByGroupId(group1.id()).size());- Assertions.assertEquals(2, countRoles(metalake.id()));- Assertions.assertEquals(2, countUserRoleRels());- Assertions.assertEquals(2, countGroupRoleRels());+ assertEquals(user1.name(), userMetaService.getUserByIdentifier(user1.nameIdentifier()).name());+ assertEquals(2, roleMetaService.listRolesByUserId(user1.id()).size());+ assertEquals(2, roleMetaService.listRolesByGroupId(group1.id()).size());+ assertEquals(2, countRoles(metalake.id()));+ assertEquals(2, countUserRoleRels());+ assertEquals(2, countGroupRoleRels());// delete metalakeAssertions.assertTrue(@@ -941,30 +996,30 @@ class TestRoleMetaService extends TestJDBCBackend {Assertions.assertThrows(NoSuchEntityException.class,() -> userMetaService.getUserByIdentifier(user1.nameIdentifier()));- Assertions.assertEquals(0, roleMetaService.listRolesByGroupId(user1.id()).size());- Assertions.assertEquals(0, roleMetaService.listRolesByGroupId(group1.id()).size());- Assertions.assertEquals(2, countRoles(metalake.id()));- Assertions.assertEquals(2, countUserRoleRels());- Assertions.assertEquals(2, countGroupRoleRels());+ assertEquals(0, roleMetaService.listRolesByGroupId(user1.id()).size());+ assertEquals(0, roleMetaService.listRolesByGroupId(group1.id()).size());+ assertEquals(2, countRoles(metalake.id()));+ assertEquals(2, countUserRoleRels());+ assertEquals(2, countGroupRoleRels());// hard delete after soft deletedeletedCount =roleMetaService.deleteRoleMetasByLegacyTimeline(Instant.now().toEpochMilli() + 1000, 1);- Assertions.assertEquals(3, deletedCount); // delete 1 role + 1 userRoleRel + 1 groupRoleRel- Assertions.assertEquals(1, countRoles(metalake.id())); // 2 - 1- Assertions.assertEquals(1, countUserRoleRels()); // 2 - 1- Assertions.assertEquals(1, countGroupRoleRels()); // 2 - 1+ assertEquals(3, deletedCount); // delete 1 role + 1 userRoleRel + 1 groupRoleRel+ assertEquals(1, countRoles(metalake.id())); // 2 - 1+ assertEquals(1, countUserRoleRels()); // 2 - 1+ assertEquals(1, countGroupRoleRels()); // 2 - 1deletedCount =roleMetaService.deleteRoleMetasByLegacyTimeline(Instant.now().toEpochMilli() + 1000, 1);- Assertions.assertEquals(3, deletedCount);- Assertions.assertEquals(0, countRoles(metalake.id()));- Assertions.assertEquals(0, countUserRoleRels());- Assertions.assertEquals(0, countGroupRoleRels());+ assertEquals(3, deletedCount);+ assertEquals(0, countRoles(metalake.id()));+ assertEquals(0, countUserRoleRels());+ assertEquals(0, countGroupRoleRels());deletedCount =roleMetaService.deleteRoleMetasByLegacyTimeline(Instant.now().toEpochMilli() + 1000, 1);- Assertions.assertEquals(0, deletedCount); // no more to delete+ assertEquals(0, deletedCount); // no more to delete}private Integer countRoles(Long metalakeId) {@@ -1017,4 +1072,41 @@ class TestRoleMetaService extends TestJDBCBackend {}return count;}++ private RoleEntity createRoleEntity(+ Long id,+ Namespace namespace,+ String name,+ AuditInfo auditInfo,+ SecurableObject securableObject,+ Map<String, String> properties) {++ return createRoleEntity(+ id, namespace, name, auditInfo, Lists.newArrayList(securableObject), properties);+ }++ private Integer countRoleRels(Long roleId) {+ int count = 0;+ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);+ Connection connection = sqlSession.getConnection();+ Statement statement1 = connection.createStatement();+ ResultSet rs1 =+ statement1.executeQuery(+ String.format("SELECT count(*) FROM user_role_rel WHERE role_id = %d", roleId));+ Statement statement2 = connection.createStatement();+ ResultSet rs2 =+ statement2.executeQuery(+ String.format("SELECT count(*) FROM group_role_rel WHERE role_id = %d", roleId))) {+ while (rs1.next()) {+ count += rs1.getInt(1);+ }+ while (rs2.next()) {+ count += rs2.getInt(1);+ }+ } catch (SQLException e) {+ throw new RuntimeException("SQL execution failed", e);+ }+ return count;+ }}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.javanew file mode 100644index 0000000000..5525962c52--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSchemaMetaService.java@@ -0,0 +1,135 @@+/*+ * 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.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.io.IOException;+import java.time.Instant;+import java.util.List;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityAlreadyExistsException;+import org.apache.gravitino.meta.SchemaEntity;+import org.apache.gravitino.storage.RandomIdGenerator;+import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.utils.NameIdentifierUtil;+import org.apache.gravitino.utils.NamespaceUtil;+import org.junit.jupiter.api.TestTemplate;++public class TestSchemaMetaService extends TestJDBCBackend {+ private final String metalakeName = "metalake_for_catalog_test";+ private final String catalogName = "catalog_for_catalog_test";++ @TestTemplate+ public void testInsertAlreadyExistsException() throws IOException {+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);++ SchemaEntity schema =+ createSchemaEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofSchema(metalakeName, catalogName),+ "schema",+ AUDIT_INFO);+ SchemaEntity schemaCopy =+ createSchemaEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofSchema(metalakeName, catalogName),+ "schema",+ AUDIT_INFO);+ backend.insert(schema, false);+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(schemaCopy, false));+ }++ @TestTemplate+ public void testUpdateAlreadyExistsException() throws IOException {+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);++ SchemaEntity schema =+ createSchemaEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofSchema(metalakeName, catalogName),+ "schema",+ AUDIT_INFO);+ SchemaEntity schemaCopy =+ createSchemaEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofSchema(metalakeName, catalogName),+ "schema1",+ AUDIT_INFO);+ backend.insert(schema, false);+ backend.insert(schemaCopy, false);+ assertThrows(+ EntityAlreadyExistsException.class,+ () ->+ backend.update(+ schemaCopy.nameIdentifier(),+ Entity.EntityType.SCHEMA,+ e ->+ createSchemaEntity(+ schemaCopy.id(), schemaCopy.namespace(), "schema", AUDIT_INFO)));+ }++ @TestTemplate+ public void testMetaLifeCycleFromCreationToDeletion() throws IOException {+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);++ SchemaEntity schema =+ createSchemaEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofSchema(metalakeName, catalogName),+ "schema",+ AUDIT_INFO);+ backend.insert(schema, false);++ String anotherMetalakeName = "another-metalake";+ String anotherCatalogName = "another-catalog";+ createAndInsertMakeLake(anotherMetalakeName);+ createAndInsertCatalog(anotherMetalakeName, anotherCatalogName);+ SchemaEntity anotherSchema =+ createSchemaEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofSchema(anotherMetalakeName, anotherCatalogName),+ "another-schema",+ AUDIT_INFO);+ backend.insert(anotherSchema, false);++ List<SchemaEntity> schemas = backend.list(schema.namespace(), Entity.EntityType.SCHEMA, true);+ assertTrue(schemas.contains(schema));++ // meta data soft delete+ backend.delete(NameIdentifierUtil.ofMetalake(metalakeName), Entity.EntityType.METALAKE, true);++ // check existence after soft delete+ assertFalse(backend.exists(schema.nameIdentifier(), Entity.EntityType.SCHEMA));+ assertTrue(backend.exists(anotherSchema.nameIdentifier(), Entity.EntityType.SCHEMA));++ // check legacy record after soft delete+ assertTrue(legacyRecordExistsInDB(schema.id(), Entity.EntityType.SCHEMA));+ // meta data hard delete+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.hardDeleteLegacyData(entityType, Instant.now().toEpochMilli() + 1000);+ }+ assertFalse(legacyRecordExistsInDB(schema.id(), Entity.EntityType.SCHEMA));+ }+}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSecurableObjects.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSecurableObjects.javaindex fcfc34d9f2..8c074ee6ed 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSecurableObjects.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSecurableObjects.java@@ -21,7 +21,10 @@ package org.apache.gravitino.storage.relational.service;import com.google.common.collect.ImmutableMap;import com.google.common.collect.Lists;import java.io.IOException;-import java.time.Instant;+import java.sql.Connection;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;import java.util.ArrayList;import java.util.Comparator;import org.apache.gravitino.MetadataObject;@@ -30,7 +33,6 @@ import org.apache.gravitino.authorization.AuthorizationUtils;import org.apache.gravitino.authorization.Privileges;import org.apache.gravitino.authorization.SecurableObject;import org.apache.gravitino.authorization.SecurableObjects;-import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.FilesetEntity;@@ -41,25 +43,22 @@ import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.meta.TopicEntity;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;public class TestSecurableObjects extends TestJDBCBackend {- RoleMetaService roleMetaService = RoleMetaService.getInstance();+ private final RoleMetaService roleMetaService = RoleMetaService.getInstance();- @Test+ @TestTemplatepublic void testAllTypeSecurableObjects() throws IOException {String metalakeName = "metalake";- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();-- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ BaseMetalake metalake = createAndInsertMakeLake(metalakeName);CatalogEntity catalog =createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);+ RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog", AUDIT_INFO);backend.insert(catalog, false);CatalogEntity catalog2 =@@ -67,39 +66,39 @@ public class TestSecurableObjects extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake"),metalake.name(),- auditInfo);+ AUDIT_INFO);backend.insert(catalog2, false);SchemaEntity schema =createSchemaEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog"),+ Namespace.of(metalakeName, "catalog"),"schema",- auditInfo);+ AUDIT_INFO);backend.insert(schema, false);FilesetEntity fileset =createFilesetEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(metalakeName, "catalog", "schema"),"fileset",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);TableEntity table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(metalakeName, "catalog", "schema"),"table",- auditInfo);+ AUDIT_INFO);backend.insert(table, false);TopicEntity topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of("metalake", "catalog", "schema"),+ Namespace.of(metalakeName, "catalog", "schema"),"topic",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);SecurableObject metalakeObject =@@ -147,7 +146,7 @@ public class TestSecurableObjects extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",- auditInfo,+ AUDIT_INFO,securableObjects,ImmutableMap.of("k1", "v1"));@@ -155,18 +154,16 @@ public class TestSecurableObjects extends TestJDBCBackend {Assertions.assertEquals(role1, roleMetaService.getRoleByIdentifier(role1.nameIdentifier()));}- @Test+ @TestTemplatepublic void testDeleteMetadataObject() throws IOException {String metalakeName = "metalake";- AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, AUDIT_INFO);backend.insert(metalake, false);CatalogEntity catalog =createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);+ RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", AUDIT_INFO);backend.insert(catalog, false);SchemaEntity schema =@@ -174,7 +171,7 @@ public class TestSecurableObjects extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog"),"schema",- auditInfo);+ AUDIT_INFO);backend.insert(schema, false);FilesetEntity fileset =@@ -182,21 +179,21 @@ public class TestSecurableObjects extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema"),"fileset",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);TableEntity table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema"),"table",- auditInfo);+ AUDIT_INFO);backend.insert(table, false);TopicEntity topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema"),"topic",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);ModelEntity model =createModelEntity(@@ -206,7 +203,7 @@ public class TestSecurableObjects extends TestJDBCBackend {"comment",1,null,- auditInfo);+ AUDIT_INFO);backend.insert(model, false);SecurableObject catalogObject =@@ -235,7 +232,7 @@ public class TestSecurableObjects extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(catalogObject, schemaObject, tableObject, filesetObject, topicObject, modelObject),ImmutableMap.of("k1", "v1"));@@ -280,7 +277,7 @@ public class TestSecurableObjects extends TestJDBCBackend {// Test to delete catalog with cascade modecatalog =createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);+ RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", AUDIT_INFO);backend.insert(catalog, false);schema =@@ -288,7 +285,7 @@ public class TestSecurableObjects extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog"),"schema",- auditInfo);+ AUDIT_INFO);backend.insert(schema, false);fileset =@@ -296,14 +293,14 @@ public class TestSecurableObjects extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema"),"fileset",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema"),"table",- auditInfo);+ AUDIT_INFO);backend.insert(table, false);topic =@@ -311,7 +308,7 @@ public class TestSecurableObjects extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema"),"topic",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);model =@@ -322,7 +319,7 @@ public class TestSecurableObjects extends TestJDBCBackend {"comment",1,null,- auditInfo);+ AUDIT_INFO);backend.insert(model, false);role1 =@@ -330,7 +327,7 @@ public class TestSecurableObjects extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(catalogObject, schemaObject, tableObject, filesetObject, topicObject, modelObject),ImmutableMap.of("k1", "v1"));@@ -346,7 +343,7 @@ public class TestSecurableObjects extends TestJDBCBackend {// Test to delete schema with cascade modecatalog =createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", auditInfo);+ RandomIdGenerator.INSTANCE.nextId(), Namespace.of("metalake"), "catalog", AUDIT_INFO);backend.insert(catalog, false);schema =@@ -354,7 +351,7 @@ public class TestSecurableObjects extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog"),"schema",- auditInfo);+ AUDIT_INFO);backend.insert(schema, false);fileset =@@ -362,21 +359,21 @@ public class TestSecurableObjects extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema"),"fileset",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema"),"table",- auditInfo);+ AUDIT_INFO);backend.insert(table, false);topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema"),"topic",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);model =createModelEntity(@@ -386,7 +383,7 @@ public class TestSecurableObjects extends TestJDBCBackend {"comment",1,null,- auditInfo);+ AUDIT_INFO);backend.insert(model, false);role1 =@@ -394,7 +391,7 @@ public class TestSecurableObjects extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",- auditInfo,+ AUDIT_INFO,Lists.newArrayList(catalogObject, schemaObject, tableObject, filesetObject, topicObject, modelObject),ImmutableMap.of("k1", "v1"));@@ -405,4 +402,44 @@ public class TestSecurableObjects extends TestJDBCBackend {Assertions.assertEquals(6, countAllObjectRel(role1.id()));Assertions.assertEquals(1, countActiveObjectRel(role1.id()));}++ private Integer countAllObjectRel(Long roleId) {+ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);+ Connection connection = sqlSession.getConnection();+ Statement statement1 = connection.createStatement();+ ResultSet rs1 =+ statement1.executeQuery(+ String.format(+ "SELECT count(*) FROM role_meta_securable_object WHERE role_id = %d",+ roleId))) {+ if (rs1.next()) {+ return rs1.getInt(1);+ } else {+ throw new RuntimeException("Doesn't contain data");+ }+ } catch (SQLException se) {+ throw new RuntimeException("SQL execution failed", se);+ }+ }++ private Integer countActiveObjectRel(Long roleId) {+ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);+ Connection connection = sqlSession.getConnection();+ Statement statement1 = connection.createStatement();+ ResultSet rs1 =+ statement1.executeQuery(+ String.format(+ "SELECT count(*) FROM role_meta_securable_object WHERE role_id = %d AND deleted_at = 0",+ roleId))) {+ if (rs1.next()) {+ return rs1.getInt(1);+ } else {+ throw new RuntimeException("Doesn't contain data");+ }+ } catch (SQLException se) {+ throw new RuntimeException("SQL execution failed", se);+ }+ }}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestStatisticMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestStatisticMetaService.javaindex 1ffd191ae6..8675448ee9 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestStatisticMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestStatisticMetaService.java@@ -19,6 +19,10 @@package org.apache.gravitino.storage.relational.service;import com.google.common.collect.Lists;+import java.sql.Connection;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;import java.time.Instant;import java.util.List;import org.apache.gravitino.Entity;@@ -36,13 +40,15 @@ import org.apache.gravitino.meta.TopicEntity;import org.apache.gravitino.stats.StatisticValues;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;public class TestStatisticMetaService extends TestJDBCBackend {- StatisticMetaService statisticMetaService = StatisticMetaService.getInstance();+ private final StatisticMetaService statisticMetaService = StatisticMetaService.getInstance();- @Test+ @TestTemplatepublic void testStatisticsLifeCycle() throws Exception {String metalakeName = "metalake";AuditInfo auditInfo =@@ -107,7 +113,7 @@ public class TestStatisticMetaService extends TestJDBCBackend {Assertions.assertEquals(0, listEntities.size());}- @Test+ @TestTemplatepublic void testDeleteMetadataObject() throws Exception {String metalakeName = "metalake";AuditInfo auditInfo =@@ -392,7 +398,7 @@ public class TestStatisticMetaService extends TestJDBCBackend {Assertions.assertEquals(12, countAllStats(metalake.id()));}- private static StatisticEntity createStatisticEntity(AuditInfo auditInfo, long value) {+ private StatisticEntity createStatisticEntity(AuditInfo auditInfo, long value) {return TableStatisticEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("test")@@ -400,4 +406,43 @@ public class TestStatisticMetaService extends TestJDBCBackend {.withAuditInfo(auditInfo).build();}++ private Integer countAllStats(Long metalakeId) {+ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);+ Connection connection = sqlSession.getConnection();+ Statement statement1 = connection.createStatement();+ ResultSet rs1 =+ statement1.executeQuery(+ String.format(+ "SELECT count(*) FROM statistic_meta WHERE metalake_id = %d", metalakeId))) {+ if (rs1.next()) {+ return rs1.getInt(1);+ } else {+ throw new RuntimeException("Doesn't contain data");+ }+ } catch (SQLException se) {+ throw new RuntimeException("SQL execution failed", se);+ }+ }++ private Integer countActiveStats(Long metalakeId) {+ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);+ Connection connection = sqlSession.getConnection();+ Statement statement1 = connection.createStatement();+ ResultSet rs1 =+ statement1.executeQuery(+ String.format(+ "SELECT count(*) FROM statistic_meta WHERE metalake_id = %d AND deleted_at = 0",+ metalakeId))) {+ if (rs1.next()) {+ return rs1.getInt(1);+ } else {+ throw new RuntimeException("Doesn't contain data");+ }+ } catch (SQLException se) {+ throw new RuntimeException("SQL execution failed", se);+ }+ }}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableColumnMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableColumnMetaService.javaindex b6e1ef2843..1c138917c4 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableColumnMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTableColumnMetaService.java@@ -23,7 +23,6 @@ import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;-import java.time.Instant;import java.util.ArrayList;import java.util.List;import java.util.Map;@@ -32,7 +31,6 @@ import java.util.stream.Collectors;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.exceptions.NoSuchEntityException;-import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.ColumnEntity;import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.rel.expressions.literals.Literals;@@ -43,21 +41,18 @@ import org.apache.gravitino.storage.relational.mapper.TableColumnMapper;import org.apache.gravitino.storage.relational.po.ColumnPO;import org.apache.gravitino.storage.relational.session.SqlSessions;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;import org.testcontainers.shaded.com.google.common.collect.Lists;public class TestTableColumnMetaService extends TestJDBCBackend {private static final String METALAKE_NAME = "metalake_for_table_column_test";- private final AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();-- @Test+ @TestTemplatepublic void testInsertAndGetTableColumns() throws IOException {String catalogName = "catalog1";String schemaName = "schema1";- createParentEntities(METALAKE_NAME, catalogName, schemaName, auditInfo);+ createParentEntities(METALAKE_NAME, catalogName, schemaName, AUDIT_INFO);// Create a table entity without columnsTableEntity createdTable =@@ -65,7 +60,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),Namespace.of(METALAKE_NAME, catalogName, schemaName),"table1",- auditInfo);+ AUDIT_INFO);TableMetaService.getInstance().insertTable(createdTable, false);TableEntity retrievedTable =@@ -87,7 +82,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withNullable(true).withAutoIncrement(false).withDefaultValue(Literals.integerLiteral(1))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();ColumnEntity column2 =ColumnEntity.builder()@@ -99,7 +94,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withNullable(false).withAutoIncrement(false).withDefaultValue(Literals.stringLiteral("1"))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableEntity createdTable2 =TableEntity.builder()@@ -107,7 +102,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withName("table2").withNamespace(Namespace.of(METALAKE_NAME, catalogName, schemaName)).withColumns(Lists.newArrayList(column1, column2))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableMetaService.getInstance().insertTable(createdTable2, false);@@ -131,7 +126,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withNullable(true).withAutoIncrement(false).withDefaultValue(Literals.integerLiteral(1))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableEntity createdTable3 =@@ -140,7 +135,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withName("table3").withNamespace(Namespace.of(METALAKE_NAME, catalogName, schemaName)).withColumns(Lists.newArrayList(column3))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableMetaService.getInstance().insertTable(createdTable3, true);@@ -154,11 +149,11 @@ public class TestTableColumnMetaService extends TestJDBCBackend {compareTwoColumns(createdTable3.columns(), retrievedTable3.columns());}- @Test+ @TestTemplatepublic void testUpdateTable() throws IOException {String catalogName = "catalog1";String schemaName = "schema1";- createParentEntities(METALAKE_NAME, catalogName, schemaName, auditInfo);+ createParentEntities(METALAKE_NAME, catalogName, schemaName, AUDIT_INFO);// Create a table entity without columnsTableEntity createdTable =@@ -166,7 +161,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),Namespace.of(METALAKE_NAME, catalogName, schemaName),"table1",- auditInfo);+ AUDIT_INFO);TableMetaService.getInstance().insertTable(createdTable, false);// Test update table with new name@@ -176,7 +171,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withName("table2").withNamespace(createdTable.namespace()).withColumns(createdTable.columns())- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Function<TableEntity, TableEntity> updater = oldTable -> updatedTable;@@ -201,7 +196,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withNullable(true).withAutoIncrement(false).withDefaultValue(Literals.integerLiteral(1))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableEntity updatedTable2 =@@ -210,7 +205,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withName(updatedTable.name()).withNamespace(updatedTable.namespace()).withColumns(Lists.newArrayList(column1))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Function<TableEntity, TableEntity> updater2 = oldTable -> updatedTable2;@@ -237,7 +232,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withNullable(false).withAutoIncrement(false).withDefaultValue(Literals.stringLiteral("1"))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableEntity updatedTable3 =@@ -246,7 +241,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withName(updatedTable2.name()).withNamespace(updatedTable2.namespace()).withColumns(Lists.newArrayList(column1, column2))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Function<TableEntity, TableEntity> updater3 = oldTable -> updatedTable3;@@ -273,7 +268,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withNullable(column1.nullable()).withAutoIncrement(column1.autoIncrement()).withDefaultValue(null)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableEntity updatedTable4 =TableEntity.builder()@@ -281,7 +276,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withName(updatedTable3.name()).withNamespace(updatedTable3.namespace()).withColumns(Lists.newArrayList(updatedColumn1, column2))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Function<TableEntity, TableEntity> updater4 = oldTable -> updatedTable4;@@ -304,7 +299,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withName(updatedTable4.name()).withNamespace(updatedTable4.namespace()).withColumns(Lists.newArrayList(column2))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Function<TableEntity, TableEntity> updater5 = oldTable -> updatedTable5;@@ -320,7 +315,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withId(updatedTable5.id()).withName(updatedTable5.name()).withNamespace(updatedTable5.namespace())- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Function<TableEntity, TableEntity> updater6 = oldTable -> updatedTable6;@@ -331,11 +326,11 @@ public class TestTableColumnMetaService extends TestJDBCBackend {Assertions.assertTrue(retrievedTable6.columns().isEmpty());}- @Test+ @TestTemplatepublic void testCreateAndDeleteTable() throws IOException {String catalogName = "catalog1";String schemaName = "schema1";- createParentEntities(METALAKE_NAME, catalogName, schemaName, auditInfo);+ createParentEntities(METALAKE_NAME, catalogName, schemaName, AUDIT_INFO);// Create a table entity with columnColumnEntity column =@@ -348,7 +343,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withNullable(true).withAutoIncrement(false).withDefaultValue(Literals.integerLiteral(1))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableEntity createdTable =@@ -357,7 +352,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withName("table1").withNamespace(Namespace.of(METALAKE_NAME, catalogName, schemaName)).withColumns(Lists.newArrayList(column))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableMetaService.getInstance().insertTable(createdTable, false);@@ -378,11 +373,11 @@ public class TestTableColumnMetaService extends TestJDBCBackend {() -> TableMetaService.getInstance().getTableByIdentifier(retrievedTable.nameIdentifier()));}- @Test+ @TestTemplatepublic void testDeleteMetalake() throws IOException {String catalogName = "catalog1";String schemaName = "schema1";- createParentEntities(METALAKE_NAME, catalogName, schemaName, auditInfo);+ createParentEntities(METALAKE_NAME, catalogName, schemaName, AUDIT_INFO);// Create a table entity with columnColumnEntity column =@@ -395,7 +390,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withNullable(true).withAutoIncrement(false).withDefaultValue(Literals.integerLiteral(1))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableEntity createdTable =@@ -404,7 +399,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withName("table1").withNamespace(Namespace.of(METALAKE_NAME, catalogName, schemaName)).withColumns(Lists.newArrayList(column))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableMetaService.getInstance().insertTable(createdTable, false);@@ -425,11 +420,11 @@ public class TestTableColumnMetaService extends TestJDBCBackend {() -> TableMetaService.getInstance().getTableByIdentifier(retrievedTable.nameIdentifier()));}- @Test+ @TestTemplatepublic void testGetColumnIdAndPO() throws IOException {String catalogName = "catalog1";String schemaName = "schema1";- createParentEntities(METALAKE_NAME, catalogName, schemaName, auditInfo);+ createParentEntities(METALAKE_NAME, catalogName, schemaName, AUDIT_INFO);// Create a table entity with columnColumnEntity column =@@ -442,7 +437,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withNullable(true).withAutoIncrement(false).withDefaultValue(Literals.integerLiteral(1))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableEntity createdTable =@@ -451,7 +446,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withName("table1").withNamespace(Namespace.of(METALAKE_NAME, catalogName, schemaName)).withColumns(Lists.newArrayList(column))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableMetaService.getInstance().insertTable(createdTable, false);@@ -485,7 +480,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withNullable(column.nullable()).withAutoIncrement(column.autoIncrement()).withDefaultValue(column.defaultValue())- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableEntity updatedTable =@@ -555,11 +550,11 @@ public class TestTableColumnMetaService extends TestJDBCBackend {});}- @Test+ @TestTemplatepublic void testDeleteColumnsByLegacyTimeline() throws IOException {String catalogName = "catalog1";String schemaName = "schema1";- createParentEntities(METALAKE_NAME, catalogName, schemaName, auditInfo);+ createParentEntities(METALAKE_NAME, catalogName, schemaName, AUDIT_INFO);List<ColumnEntity> columns = new ArrayList<>();for (int i = 0; i < 5; i++) {@@ -572,7 +567,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withDataType(Types.StringType.get()).withNullable(true).withAutoIncrement(false)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build());}@@ -582,7 +577,7 @@ public class TestTableColumnMetaService extends TestJDBCBackend {.withName("legacy_table").withNamespace(Namespace.of(METALAKE_NAME, catalogName, schemaName)).withColumns(columns)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableMetaService.getInstance().insertTable(createdTable, false);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.javaindex 2f2e20f26f..9c4eea387a 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@@ -18,15 +18,22 @@*/package org.apache.gravitino.storage.relational.service;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import java.io.IOException;import java.time.Instant;import java.util.List;import java.util.Map;import java.util.function.Function;import java.util.stream.Collectors;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityAlreadyExistsException;import org.apache.gravitino.Namespace;import org.apache.gravitino.exceptions.NoSuchEntityException;-import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.BaseMetalake;+import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.ColumnEntity;import org.apache.gravitino.meta.SchemaEntity;import org.apache.gravitino.meta.TableEntity;@@ -34,19 +41,118 @@ import org.apache.gravitino.rel.expressions.literals.Literals;import org.apache.gravitino.rel.types.Types;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.utils.NamespaceUtil;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;public class TestTableMetaService extends TestJDBCBackend {private final String metalakeName = "metalake_for_table_test";- private final AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();+ private final String catalogName = "catalog_for_table_test";+ private final String schemaName = "schema_for_table_test";++ @TestTemplate+ public void testInsertAlreadyExistsException() throws IOException {+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);+ createAndInsertSchema(metalakeName, catalogName, schemaName);++ TableEntity table =+ createTableEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofTable(metalakeName, catalogName, schemaName),+ "table",+ AUDIT_INFO);+ TableEntity tableCopy =+ createTableEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofTable(metalakeName, catalogName, schemaName),+ "table",+ AUDIT_INFO);+ backend.insert(table, false);+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(tableCopy, false));+ }++ @TestTemplate+ public void testUpdateAlreadyExistsException() throws IOException {+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);+ createAndInsertSchema(metalakeName, catalogName, schemaName);++ TableEntity table =+ createTableEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofTable(metalakeName, catalogName, schemaName),+ "table",+ AUDIT_INFO);+ TableEntity tableCopy =+ createTableEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofTable(metalakeName, catalogName, schemaName),+ "table1",+ AUDIT_INFO);+ backend.insert(table, false);+ backend.insert(tableCopy, false);+ assertThrows(+ EntityAlreadyExistsException.class,+ () ->+ backend.update(+ tableCopy.nameIdentifier(),+ Entity.EntityType.TABLE,+ e ->+ createTableEntity(tableCopy.id(), tableCopy.namespace(), "table", AUDIT_INFO)));+ }++ @TestTemplate+ public void testMetaLifeCycleFromCreationToDeletion() throws IOException {+ BaseMetalake metalake =+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, AUDIT_INFO);+ backend.insert(metalake, false);++ CatalogEntity catalog =+ createCatalog(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofCatalog(metalakeName),+ catalogName,+ AUDIT_INFO);+ backend.insert(catalog, false);+ SchemaEntity schema =+ createSchemaEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofSchema(metalakeName, catalogName),+ schemaName,+ AUDIT_INFO);+ backend.insert(schema, false);++ TableEntity table =+ createTableEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofTable(metalakeName, catalogName, schemaName),+ "table",+ AUDIT_INFO);+ backend.insert(table, false);++ List<TableEntity> tables = backend.list(table.namespace(), Entity.EntityType.TABLE, true);+ assertTrue(tables.contains(table));++ // meta data soft delete+ backend.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE, true);+ assertFalse(backend.exists(table.nameIdentifier(), Entity.EntityType.TABLE));++ // check legacy record after soft delete+ assertTrue(legacyRecordExistsInDB(table.id(), Entity.EntityType.TABLE));++ // meta data hard delete+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.hardDeleteLegacyData(entityType, Instant.now().toEpochMilli() + 1000);+ }+ assertFalse(legacyRecordExistsInDB(table.id(), Entity.EntityType.TABLE));+ }- @Test+ @TestTemplatepublic void testUpdateTable() throws IOException {String catalogName = "catalog1";String schemaName = "schema1";- createParentEntities(metalakeName, catalogName, schemaName, auditInfo);+ createParentEntities(metalakeName, catalogName, schemaName, AUDIT_INFO);ColumnEntity column1 =ColumnEntity.builder()@@ -58,7 +164,7 @@ public class TestTableMetaService extends TestJDBCBackend {.withNullable(true).withAutoIncrement(false).withDefaultValue(Literals.integerLiteral(1))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableEntity createdTable =TableEntity.builder()@@ -66,7 +172,7 @@ public class TestTableMetaService extends TestJDBCBackend {.withName("table1").withNamespace(Namespace.of(metalakeName, catalogName, schemaName)).withColumns(List.of(column1))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TableMetaService.getInstance().insertTable(createdTable, false);@@ -77,7 +183,7 @@ public class TestTableMetaService extends TestJDBCBackend {.withName("table2").withNamespace(createdTable.namespace()).withColumns(createdTable.columns())- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Function<TableEntity, TableEntity> updater = oldTable -> updatedTable;TableMetaService.getInstance().updateTable(createdTable.nameIdentifier(), updater);@@ -99,7 +205,7 @@ public class TestTableMetaService extends TestJDBCBackend {.withName("table3").withNamespace(Namespace.of(metalakeName, catalogName, newSchemaName)).withColumns(updatedTable.columns())- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Function<TableEntity, TableEntity> updater2 = oldTable -> updatedTable2;Exception e =@@ -116,7 +222,7 @@ public class TestTableMetaService extends TestJDBCBackend {RandomIdGenerator.INSTANCE.nextId(),Namespace.of(metalakeName, catalogName),newSchemaName,- auditInfo);+ AUDIT_INFO);backend.insert(newSchema, false);TableMetaService.getInstance().updateTable(updatedTable.nameIdentifier(), updater2);diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.javaindex 91d40cb597..0642af1ce5 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTagMetaService.java@@ -18,9 +18,17 @@*/package org.apache.gravitino.storage.relational.service;+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 com.google.common.collect.ImmutableMap;import com.google.common.collect.Lists;import java.io.IOException;+import java.sql.Connection;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;import java.time.Instant;import java.util.List;import java.util.Map;@@ -29,7 +37,6 @@ import org.apache.gravitino.EntityAlreadyExistsException;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.exceptions.NoSuchEntityException;-import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.ColumnEntity;@@ -43,33 +50,76 @@ import org.apache.gravitino.meta.TopicEntity;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.session.SqlSessionFactoryHelper;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.NamespaceUtil;+import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;public class TestTagMetaService extends TestJDBCBackend {- private final String metalakeName = "metalake_for_tag_test";-- private final AuditInfo auditInfo =- AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();+ private static final String METALAKE_NAME = "metalake_for_tag_test";private final Map<String, String> props = ImmutableMap.of("k1", "v1");- @Test- public void testInsertAndGetTagByIdentifier() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ @TestTemplate+ public void testMetaLifeCycleFromCreationToDeletion() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);+ String anotherMetalakeName = METALAKE_NAME + "_another";+ BaseMetalake anotherMetaLake = createAndInsertMakeLake(anotherMetalakeName);++ TagEntity tag =+ TagEntity.builder()+ .withId(RandomIdGenerator.INSTANCE.nextId())+ .withName("tag")+ .withNamespace(NamespaceUtil.ofTag(metalake.name()))+ .withComment("tag comment")+ .withAuditInfo(AUDIT_INFO)+ .build();+ backend.insert(tag, false);++ TagEntity anotherTagEntity =+ TagEntity.builder()+ .withId(RandomIdGenerator.INSTANCE.nextId())+ .withName("another-tag")+ .withNamespace(NamespaceUtil.ofTag(anotherMetaLake.name()))+ .withComment("another-tag comment")+ .withAuditInfo(AUDIT_INFO)+ .build();+ backend.insert(anotherTagEntity, false);++ TagEntity tagEntity = backend.get(tag.nameIdentifier(), Entity.EntityType.TAG);+ assertEquals(tag, tagEntity);+ List<TagEntity> tags = backend.list(tag.namespace(), Entity.EntityType.TAG, true);+ assertTrue(tags.contains(tag));+ assertEquals(1, tags.size());++ // meta data soft delete+ backend.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE, true);++ // check existence after soft delete+ assertFalse(backend.exists(tag.nameIdentifier(), Entity.EntityType.TAG));+ assertTrue(backend.exists(anotherTagEntity.nameIdentifier(), Entity.EntityType.TAG));+ assertTrue(legacyRecordExistsInDB(tag.id(), Entity.EntityType.TAG));++ // meta data hard delete+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.hardDeleteLegacyData(entityType, Instant.now().toEpochMilli() + 1000);+ }+ assertFalse(legacyRecordExistsInDB(tag.id(), Entity.EntityType.TAG));+ }+ @TestTemplate+ public void testInsertAndGetTagByIdentifier() throws IOException {+ createAndInsertMakeLake(METALAKE_NAME);// Test no tag entity.TagMetaService tagMetaService = TagMetaService.getInstance();Exception excep =Assertions.assertThrows(NoSuchEntityException.class,() ->- tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(metalakeName, "tag1")));+ tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1")));Assertions.assertEquals("No such tag entity: tag1", excep.getMessage());// Test get tag entity@@ -77,15 +127,15 @@ public class TestTagMetaService extends TestJDBCBackend {TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag1")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment").withProperties(props)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();tagMetaService.insertTag(tagEntity, false);TagEntity resultTagEntity =- tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(metalakeName, "tag1"));+ tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1"));Assertions.assertEquals(tagEntity, resultTagEntity);// Test with null comment and properties.@@ -93,13 +143,13 @@ public class TestTagMetaService extends TestJDBCBackend {TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag2")- .withNamespace(NamespaceUtil.ofTag(metalakeName))- .withAuditInfo(auditInfo)+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME))+ .withAuditInfo(AUDIT_INFO).build();tagMetaService.insertTag(tagEntity1, false);TagEntity resultTagEntity1 =- tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(metalakeName, "tag2"));+ tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(METALAKE_NAME, "tag2"));Assertions.assertEquals(tagEntity1, resultTagEntity1);Assertions.assertNull(resultTagEntity1.comment());Assertions.assertNull(resultTagEntity1.properties());@@ -109,10 +159,10 @@ public class TestTagMetaService extends TestJDBCBackend {TagEntity.builder().withId(tagEntity1.id()).withName("tag3")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment").withProperties(props)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Assertions.assertThrows(Exception.class, () -> tagMetaService.insertTag(tagEntity2, false));@@ -120,25 +170,23 @@ public class TestTagMetaService extends TestJDBCBackend {tagMetaService.insertTag(tagEntity2, true);TagEntity resultTagEntity2 =- tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(metalakeName, "tag3"));+ tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(METALAKE_NAME, "tag3"));Assertions.assertEquals(tagEntity2, resultTagEntity2);}- @Test+ @TestTemplatepublic void testCreateAndListTags() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ createAndInsertMakeLake(METALAKE_NAME);TagMetaService tagMetaService = TagMetaService.getInstance();TagEntity tagEntity1 =TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag1")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment").withProperties(props)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();tagMetaService.insertTag(tagEntity1, false);@@ -146,35 +194,33 @@ public class TestTagMetaService extends TestJDBCBackend {TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag2")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment").withProperties(props)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();tagMetaService.insertTag(tagEntity2, false);List<TagEntity> tagEntities =- tagMetaService.listTagsByNamespace(NamespaceUtil.ofTag(metalakeName));+ tagMetaService.listTagsByNamespace(NamespaceUtil.ofTag(METALAKE_NAME));Assertions.assertEquals(2, tagEntities.size());Assertions.assertTrue(tagEntities.contains(tagEntity1));Assertions.assertTrue(tagEntities.contains(tagEntity2));}- @Test+ @TestTemplatepublic void testUpdateTag() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ createAndInsertMakeLake(METALAKE_NAME);TagMetaService tagMetaService = TagMetaService.getInstance();TagEntity tagEntity1 =TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag1")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment").withProperties(props)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();tagMetaService.insertTag(tagEntity1, false);@@ -184,7 +230,7 @@ public class TestTagMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->tagMetaService.updateTag(- NameIdentifierUtil.ofTag(metalakeName, "tag2"), tagEntity -> tagEntity));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag2"), tagEntity -> tagEntity));Assertions.assertEquals("No such tag entity: tag2", excep.getMessage());// Update tag entity.@@ -192,18 +238,18 @@ public class TestTagMetaService extends TestJDBCBackend {TagEntity.builder().withId(tagEntity1.id()).withName("tag1")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment1").withProperties(ImmutableMap.of("k2", "v2"))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();TagEntity updatedTagEntity =tagMetaService.updateTag(- NameIdentifierUtil.ofTag(metalakeName, "tag1"), tagEntity -> tagEntity2);+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1"), tagEntity -> tagEntity2);Assertions.assertEquals(tagEntity2, updatedTagEntity);TagEntity loadedTagEntity =- tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(metalakeName, "tag1"));+ tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1"));Assertions.assertEquals(tagEntity2, loadedTagEntity);// Update with different id.@@ -211,10 +257,10 @@ public class TestTagMetaService extends TestJDBCBackend {TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag1")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment1").withProperties(ImmutableMap.of("k2", "v2"))- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();Exception excep1 =@@ -222,7 +268,7 @@ public class TestTagMetaService extends TestJDBCBackend {IllegalArgumentException.class,() ->tagMetaService.updateTag(- NameIdentifierUtil.ofTag(metalakeName, "tag1"), tagEntity -> tagEntity3));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1"), tagEntity -> tagEntity3));Assertions.assertEquals("The updated tag entity id: "+ tagEntity3.id()@@ -232,57 +278,53 @@ public class TestTagMetaService extends TestJDBCBackend {excep1.getMessage());TagEntity loadedTagEntity1 =- tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(metalakeName, "tag1"));+ tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1"));Assertions.assertEquals(tagEntity2, loadedTagEntity1);}- @Test+ @TestTemplatepublic void testDeleteTag() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ createAndInsertMakeLake(METALAKE_NAME);TagMetaService tagMetaService = TagMetaService.getInstance();TagEntity tagEntity1 =TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag1")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment").withProperties(props)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();tagMetaService.insertTag(tagEntity1, false);- boolean deleted = tagMetaService.deleteTag(NameIdentifierUtil.ofTag(metalakeName, "tag1"));+ boolean deleted = tagMetaService.deleteTag(NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1"));Assertions.assertTrue(deleted);- deleted = tagMetaService.deleteTag(NameIdentifierUtil.ofTag(metalakeName, "tag1"));+ deleted = tagMetaService.deleteTag(NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1"));Assertions.assertFalse(deleted);Exception excep =Assertions.assertThrows(NoSuchEntityException.class,() ->- tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(metalakeName, "tag1")));+ tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1")));Assertions.assertEquals("No such tag entity: tag1", excep.getMessage());}- @Test+ @TestTemplatepublic void testDeleteMetalake() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);TagMetaService tagMetaService = TagMetaService.getInstance();TagEntity tagEntity1 =TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag1")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment").withProperties(props)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();tagMetaService.insertTag(tagEntity1, false);@@ -290,21 +332,21 @@ public class TestTagMetaService extends TestJDBCBackend {MetalakeMetaService.getInstance().deleteMetalake(metalake.nameIdentifier(), false));Assertions.assertThrows(NoSuchEntityException.class,- () -> tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(metalakeName, "tag1")));+ () -> tagMetaService.getTagByIdentifier(NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1")));// Test delete metalake with cascade.BaseMetalake metalake1 =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName + "1", auditInfo);+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME + "1", AUDIT_INFO);backend.insert(metalake1, false);TagEntity tagEntity2 =TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag2")- .withNamespace(NamespaceUtil.ofTag(metalakeName + "1"))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME + "1")).withComment("comment").withProperties(props)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();tagMetaService.insertTag(tagEntity2, false);@@ -314,34 +356,23 @@ public class TestTagMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->tagMetaService.getTagByIdentifier(- NameIdentifierUtil.ofTag(metalakeName + "1", "tag2")));+ NameIdentifierUtil.ofTag(METALAKE_NAME + "1", "tag2")));}- @Test+ @TestTemplatepublic void testAssociateAndDisassociateTagsWithMetadataObject() throws IOException {- BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);- backend.insert(metalake, false);-- CatalogEntity catalog =- createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog1", auditInfo);- backend.insert(catalog, false);-- SchemaEntity schema =- createSchemaEntity(- RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name()),- "schema1",- auditInfo);- backend.insert(schema, false);+ createAndInsertMakeLake(METALAKE_NAME);+ String catalogName = "catalog1";+ CatalogEntity catalog = createAndInsertCatalog(METALAKE_NAME, catalogName);+ String schemaName = "schema1";+ SchemaEntity schema = createAndInsertSchema(METALAKE_NAME, catalogName, schemaName);TableEntity table =createTableEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"table1",- auditInfo);+ AUDIT_INFO);backend.insert(table, false);// Create tags to associate@@ -350,10 +381,10 @@ public class TestTagMetaService extends TestJDBCBackend {TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag1")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment").withProperties(props)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();tagMetaService.insertTag(tagEntity1, false);@@ -361,10 +392,10 @@ public class TestTagMetaService extends TestJDBCBackend {TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag2")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment").withProperties(props)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();tagMetaService.insertTag(tagEntity2, false);@@ -372,19 +403,19 @@ public class TestTagMetaService extends TestJDBCBackend {TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag3")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment").withProperties(props)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();tagMetaService.insertTag(tagEntity3, false);// Test associate tags with metadata objectNameIdentifier[] tagsToAdd =new NameIdentifier[] {- NameIdentifierUtil.ofTag(metalakeName, "tag1"),- NameIdentifierUtil.ofTag(metalakeName, "tag2"),- NameIdentifierUtil.ofTag(metalakeName, "tag3")+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1"),+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag2"),+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag3")};List<TagEntity> tagEntities =@@ -397,7 +428,7 @@ public class TestTagMetaService extends TestJDBCBackend {// Test disassociate tags with metadata objectNameIdentifier[] tagsToRemove =- new NameIdentifier[] {NameIdentifierUtil.ofTag(metalakeName, "tag1")};+ new NameIdentifier[] {NameIdentifierUtil.ofTag(METALAKE_NAME, "tag1")};List<TagEntity> tagEntities1 =tagMetaService.associateTagsWithMetadataObject(@@ -430,14 +461,14 @@ public class TestTagMetaService extends TestJDBCBackend {// Test associate and disassociate in-existent tags with metadata objectNameIdentifier[] tagsToAdd1 =new NameIdentifier[] {- NameIdentifierUtil.ofTag(metalakeName, "tag4"),- NameIdentifierUtil.ofTag(metalakeName, "tag5")+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag4"),+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag5")};NameIdentifier[] tagsToRemove1 =new NameIdentifier[] {- NameIdentifierUtil.ofTag(metalakeName, "tag6"),- NameIdentifierUtil.ofTag(metalakeName, "tag7")+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag6"),+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag7")};List<TagEntity> tagEntities4 =@@ -469,7 +500,7 @@ public class TestTagMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->tagMetaService.associateTagsWithMetadataObject(- NameIdentifier.of(metalakeName, "non-existent-catalog"),+ NameIdentifier.of(METALAKE_NAME, "non-existent-catalog"),catalog.type(),tagsToAdd,tagsToRemove));@@ -493,7 +524,7 @@ public class TestTagMetaService extends TestJDBCBackend {Assertions.assertTrue(tagEntities7.contains(tagEntity3));}- @Test+ @TestTemplatepublic void testListTagsForMetadataObject() throws IOException {testAssociateAndDisassociateTagsWithMetadataObject();@@ -502,7 +533,7 @@ public class TestTagMetaService extends TestJDBCBackend {// Test list tags for catalogList<TagEntity> tagEntities =tagMetaService.listTagsForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1"), Entity.EntityType.CATALOG);+ NameIdentifier.of(METALAKE_NAME, "catalog1"), Entity.EntityType.CATALOG);Assertions.assertEquals(2, tagEntities.size());Assertions.assertTrue(tagEntities.stream().anyMatch(tagEntity -> tagEntity.name().equals("tag2")));@@ -512,7 +543,7 @@ public class TestTagMetaService extends TestJDBCBackend {// Test list tags for schemaList<TagEntity> tagEntities1 =tagMetaService.listTagsForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1"), Entity.EntityType.SCHEMA);+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1"), Entity.EntityType.SCHEMA);Assertions.assertEquals(2, tagEntities1.size());Assertions.assertTrue(@@ -523,7 +554,7 @@ public class TestTagMetaService extends TestJDBCBackend {// Test list tags for tableList<TagEntity> tagEntities2 =tagMetaService.listTagsForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1", "table1"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table1"),Entity.EntityType.TABLE);Assertions.assertEquals(2, tagEntities2.size());@@ -537,11 +568,11 @@ public class TestTagMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->tagMetaService.listTagsForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1", "table2"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table2"),Entity.EntityType.TABLE));}- @Test+ @TestTemplatepublic void testGetTagForMetadataObject() throws IOException {testAssociateAndDisassociateTagsWithMetadataObject();@@ -550,25 +581,25 @@ public class TestTagMetaService extends TestJDBCBackend {// Test get tag for catalogTagEntity tagEntity =tagMetaService.getTagForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1"),+ NameIdentifier.of(METALAKE_NAME, "catalog1"),Entity.EntityType.CATALOG,- NameIdentifierUtil.ofTag(metalakeName, "tag2"));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag2"));Assertions.assertEquals("tag2", tagEntity.name());// Test get tag for schemaTagEntity tagEntity1 =tagMetaService.getTagForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1"),Entity.EntityType.SCHEMA,- NameIdentifierUtil.ofTag(metalakeName, "tag3"));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag3"));Assertions.assertEquals("tag3", tagEntity1.name());// Test get tag for tableTagEntity tagEntity2 =tagMetaService.getTagForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1", "table1"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table1"),Entity.EntityType.TABLE,- NameIdentifierUtil.ofTag(metalakeName, "tag2"));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag2"));Assertions.assertEquals("tag2", tagEntity2.name());// Test get tag for non-existent metadata object@@ -576,9 +607,9 @@ public class TestTagMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->tagMetaService.getTagForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1", "table2"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table2"),Entity.EntityType.TABLE,- NameIdentifierUtil.ofTag(metalakeName, "tag2")));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag2")));// Test get tag for non-existent tagThrowable e =@@ -586,18 +617,13 @@ public class TestTagMetaService extends TestJDBCBackend {NoSuchEntityException.class,() ->tagMetaService.getTagForMetadataObject(- NameIdentifier.of(metalakeName, "catalog1", "schema1", "table1"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table1"),Entity.EntityType.TABLE,- NameIdentifierUtil.ofTag(metalakeName, "tag4")));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag4")));Assertions.assertTrue(e.getMessage().contains("No such tag entity: tag4"));}- private boolean containsGenericEntity(- List<GenericEntity> genericEntities, String name, Entity.EntityType entityType) {- return genericEntities.stream().anyMatch(e -> e.name().equals(name) && e.type() == entityType);- }-- @Test+ @TestTemplatepublic void testListAssociatedMetadataObjectsForTag() throws IOException {testAssociateAndDisassociateTagsWithMetadataObject();@@ -606,7 +632,7 @@ public class TestTagMetaService extends TestJDBCBackend {// Test list associated metadata objects for tag2List<GenericEntity> metadataObjects =tagMetaService.listAssociatedMetadataObjectsForTag(- NameIdentifierUtil.ofTag(metalakeName, "tag2"));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag2"));Assertions.assertEquals(3, metadataObjects.size());Assertions.assertTrue(@@ -619,7 +645,7 @@ public class TestTagMetaService extends TestJDBCBackend {// Test list associated metadata objects for tag3List<GenericEntity> metadataObjects1 =tagMetaService.listAssociatedMetadataObjectsForTag(- NameIdentifierUtil.ofTag(metalakeName, "tag3"));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag3"));Assertions.assertEquals(3, metadataObjects1.size());@@ -634,18 +660,18 @@ public class TestTagMetaService extends TestJDBCBackend {// Test list associated metadata objects for non-existent tagList<GenericEntity> metadataObjects2 =tagMetaService.listAssociatedMetadataObjectsForTag(- NameIdentifierUtil.ofTag(metalakeName, "tag4"));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag4"));Assertions.assertEquals(0, metadataObjects2.size());// Test metadata object non-exist scenario.backend.delete(- NameIdentifier.of(metalakeName, "catalog1", "schema1", "table1"),+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1", "table1"),Entity.EntityType.TABLE,false);List<GenericEntity> metadataObjects3 =tagMetaService.listAssociatedMetadataObjectsForTag(- NameIdentifierUtil.ofTag(metalakeName, "tag2"));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag2"));Assertions.assertEquals(2, metadataObjects3.size());@@ -655,42 +681,45 @@ public class TestTagMetaService extends TestJDBCBackend {containsGenericEntity(metadataObjects3, "catalog1.schema1", Entity.EntityType.SCHEMA));backend.delete(- NameIdentifier.of(metalakeName, "catalog1", "schema1"), Entity.EntityType.SCHEMA, false);+ NameIdentifier.of(METALAKE_NAME, "catalog1", "schema1"), Entity.EntityType.SCHEMA, false);List<GenericEntity> metadataObjects4 =tagMetaService.listAssociatedMetadataObjectsForTag(- NameIdentifierUtil.ofTag(metalakeName, "tag2"));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag2"));Assertions.assertEquals(1, metadataObjects4.size());Assertions.assertTrue(containsGenericEntity(metadataObjects4, "catalog1", Entity.EntityType.CATALOG));- backend.delete(NameIdentifier.of(metalakeName, "catalog1"), Entity.EntityType.CATALOG, false);+ backend.delete(NameIdentifier.of(METALAKE_NAME, "catalog1"), Entity.EntityType.CATALOG, false);List<GenericEntity> metadataObjects5 =tagMetaService.listAssociatedMetadataObjectsForTag(- NameIdentifierUtil.ofTag(metalakeName, "tag2"));+ NameIdentifierUtil.ofTag(METALAKE_NAME, "tag2"));Assertions.assertEquals(0, metadataObjects5.size());}- @Test+ @TestTemplatepublic void testDeleteMetadataObjectForTag() throws IOException {BaseMetalake metalake =- createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), metalakeName, auditInfo);+ createBaseMakeLake(RandomIdGenerator.INSTANCE.nextId(), METALAKE_NAME, AUDIT_INFO);backend.insert(metalake, false);CatalogEntity catalog =createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog1", auditInfo);+ RandomIdGenerator.INSTANCE.nextId(),+ Namespace.of(METALAKE_NAME),+ "catalog1",+ AUDIT_INFO);backend.insert(catalog, false);SchemaEntity schema =createSchemaEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name()),+ Namespace.of(METALAKE_NAME, catalog.name()),"schema1",- auditInfo);+ AUDIT_INFO);backend.insert(schema, false);ColumnEntity column =@@ -701,7 +730,7 @@ public class TestTagMetaService extends TestJDBCBackend {.withAutoIncrement(false).withNullable(false).withDataType(Types.IntegerType.get())- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();List<ColumnEntity> columns = Lists.newArrayList();@@ -710,10 +739,10 @@ public class TestTagMetaService extends TestJDBCBackend {TableEntity table =TableEntity.builder().withName("table")- .withNamespace(Namespace.of(metalakeName, catalog.name(), schema.name()))+ .withNamespace(Namespace.of(METALAKE_NAME, catalog.name(), schema.name())).withId(RandomIdGenerator.INSTANCE.nextId()).withColumns(columns)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();backend.insert(table, false);@@ -721,28 +750,28 @@ public class TestTagMetaService extends TestJDBCBackend {TopicEntity topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"topic1",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);FilesetEntity fileset =createFilesetEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"fileset1",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);ModelEntity model =createModelEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"model1","comment",1,null,- auditInfo);+ AUDIT_INFO);backend.insert(model, false);TagMetaService tagMetaService = TagMetaService.getInstance();@@ -750,10 +779,10 @@ public class TestTagMetaService extends TestJDBCBackend {TagEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("tag1")- .withNamespace(NamespaceUtil.ofTag(metalakeName))+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME)).withComment("comment").withProperties(props)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();tagMetaService.insertTag(tagEntity1, false);tagMetaService.associateTagsWithMetadataObject(@@ -830,15 +859,18 @@ public class TestTagMetaService extends TestJDBCBackend {// Test to drop a catalog using cascade modecatalog =createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog1", auditInfo);+ RandomIdGenerator.INSTANCE.nextId(),+ Namespace.of(METALAKE_NAME),+ "catalog1",+ AUDIT_INFO);backend.insert(catalog, false);schema =createSchemaEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name()),+ Namespace.of(METALAKE_NAME, catalog.name()),"schema1",- auditInfo);+ AUDIT_INFO);backend.insert(schema, false);column =@@ -849,7 +881,7 @@ public class TestTagMetaService extends TestJDBCBackend {.withAutoIncrement(false).withNullable(false).withDataType(Types.IntegerType.get())- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();columns = Lists.newArrayList();@@ -858,10 +890,10 @@ public class TestTagMetaService extends TestJDBCBackend {table =TableEntity.builder().withName("table")- .withNamespace(Namespace.of(metalakeName, catalog.name(), schema.name()))+ .withNamespace(Namespace.of(METALAKE_NAME, catalog.name(), schema.name())).withId(RandomIdGenerator.INSTANCE.nextId()).withColumns(columns)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();backend.insert(table, false);@@ -869,28 +901,28 @@ public class TestTagMetaService extends TestJDBCBackend {topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"topic1",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);fileset =createFilesetEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"fileset1",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);model =createModelEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"model1","comment",1,null,- auditInfo);+ AUDIT_INFO);backend.insert(model, false);tagMetaService.associateTagsWithMetadataObject(@@ -938,15 +970,18 @@ public class TestTagMetaService extends TestJDBCBackend {// Test to drop a schema using cascade modecatalog =createCatalog(- RandomIdGenerator.INSTANCE.nextId(), Namespace.of(metalakeName), "catalog1", auditInfo);+ RandomIdGenerator.INSTANCE.nextId(),+ Namespace.of(METALAKE_NAME),+ "catalog1",+ AUDIT_INFO);backend.insert(catalog, false);schema =createSchemaEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name()),+ Namespace.of(METALAKE_NAME, catalog.name()),"schema1",- auditInfo);+ AUDIT_INFO);backend.insert(schema, false);column =@@ -957,7 +992,7 @@ public class TestTagMetaService extends TestJDBCBackend {.withAutoIncrement(false).withNullable(false).withDataType(Types.IntegerType.get())- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();columns = Lists.newArrayList();@@ -966,10 +1001,10 @@ public class TestTagMetaService extends TestJDBCBackend {table =TableEntity.builder().withName("table")- .withNamespace(Namespace.of(metalakeName, catalog.name(), schema.name()))+ .withNamespace(Namespace.of(METALAKE_NAME, catalog.name(), schema.name())).withId(RandomIdGenerator.INSTANCE.nextId()).withColumns(columns)- .withAuditInfo(auditInfo)+ .withAuditInfo(AUDIT_INFO).build();backend.insert(table, false);@@ -977,28 +1012,28 @@ public class TestTagMetaService extends TestJDBCBackend {topic =createTopicEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"topic1",- auditInfo);+ AUDIT_INFO);backend.insert(topic, false);fileset =createFilesetEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"fileset1",- auditInfo);+ AUDIT_INFO);backend.insert(fileset, false);model =createModelEntity(RandomIdGenerator.INSTANCE.nextId(),- Namespace.of(metalakeName, catalog.name(), schema.name()),+ Namespace.of(METALAKE_NAME, catalog.name(), schema.name()),"model1","comment",1,null,- auditInfo);+ AUDIT_INFO);backend.insert(model, false);tagMetaService.associateTagsWithMetadataObject(@@ -1044,4 +1079,47 @@ public class TestTagMetaService extends TestJDBCBackend {Assertions.assertEquals(1, countActiveTagRel(tagEntity1.id()));Assertions.assertEquals(21, countAllTagRel(tagEntity1.id()));}++ private boolean containsGenericEntity(+ List<GenericEntity> genericEntities, String name, Entity.EntityType entityType) {+ return genericEntities.stream().anyMatch(e -> e.name().equals(name) && e.type() == entityType);+ }++ private Integer countAllTagRel(Long tagId) {+ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);+ Connection connection = sqlSession.getConnection();+ Statement statement1 = connection.createStatement();+ ResultSet rs1 =+ statement1.executeQuery(+ String.format("SELECT count(*) FROM tag_relation_meta WHERE tag_id = %d", tagId))) {+ if (rs1.next()) {+ return rs1.getInt(1);+ } else {+ throw new RuntimeException("Doesn't contain data");+ }+ } catch (SQLException se) {+ throw new RuntimeException("SQL execution failed", se);+ }+ }++ private Integer countActiveTagRel(Long tagId) {+ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);+ Connection connection = sqlSession.getConnection();+ Statement statement1 = connection.createStatement();+ ResultSet rs1 =+ statement1.executeQuery(+ String.format(+ "SELECT count(*) FROM tag_relation_meta WHERE tag_id = %d AND deleted_at = 0",+ tagId))) {+ if (rs1.next()) {+ return rs1.getInt(1);+ } else {+ throw new RuntimeException("Doesn't contain data");+ }+ } catch (SQLException se) {+ throw new RuntimeException("SQL execution failed", se);+ }+ }}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.javanew file mode 100644index 0000000000..7f4a263e8c--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestTopicMetaService.java@@ -0,0 +1,120 @@+/*+ * 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.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.io.IOException;+import java.time.Instant;+import java.util.List;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityAlreadyExistsException;+import org.apache.gravitino.meta.TopicEntity;+import org.apache.gravitino.storage.RandomIdGenerator;+import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.utils.NameIdentifierUtil;+import org.apache.gravitino.utils.NamespaceUtil;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.TestTemplate;++public class TestTopicMetaService extends TestJDBCBackend {+ private final String metalakeName = "metalake_for_topic_test";+ private final String catalogName = "catalog_for_topic_test";+ private final String schemaName = "schema_for_topic_test";++ @BeforeEach+ public void prepare() throws IOException {+ createAndInsertMakeLake(metalakeName);+ createAndInsertCatalog(metalakeName, catalogName);+ createAndInsertSchema(metalakeName, catalogName, schemaName);+ }++ @TestTemplate+ public void testInsertAlreadyExistsException() throws IOException {+ TopicEntity topic =+ createTopicEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName),+ "topic",+ AUDIT_INFO);+ TopicEntity topicCopy =+ createTopicEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName),+ "topic",+ AUDIT_INFO);+ backend.insert(topic, false);+ assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(topicCopy, false));+ }++ @TestTemplate+ public void testMetaLifeCycleFromCreationToDeletion() throws IOException {+ TopicEntity topic =+ createTopicEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName),+ "topic",+ AUDIT_INFO);+ backend.insert(topic, false);++ List<TopicEntity> topics = backend.list(topic.namespace(), Entity.EntityType.TOPIC, true);+ assertTrue(topics.contains(topic));++ // meta data soft delete+ backend.delete(NameIdentifierUtil.ofMetalake(metalakeName), Entity.EntityType.METALAKE, true);+ assertFalse(backend.exists(topic.nameIdentifier(), Entity.EntityType.TOPIC));++ // check legacy record after soft delete+ assertTrue(legacyRecordExistsInDB(topic.id(), Entity.EntityType.TOPIC));++ // meta data hard delete+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.hardDeleteLegacyData(entityType, Instant.now().toEpochMilli() + 1000);+ }+ assertFalse(legacyRecordExistsInDB(topic.id(), Entity.EntityType.TOPIC));+ }++ @TestTemplate+ public void testUpdateAlreadyExistsException() throws IOException {+ TopicEntity topic =+ createTopicEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName),+ "topic",+ AUDIT_INFO);+ TopicEntity topicCopy =+ createTopicEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(metalakeName, catalogName, schemaName),+ "topic1",+ AUDIT_INFO);+ backend.insert(topic, false);+ backend.insert(topicCopy, false);+ assertThrows(+ EntityAlreadyExistsException.class,+ () ->+ backend.update(+ topicCopy.nameIdentifier(),+ Entity.EntityType.TOPIC,+ e ->+ createTopicEntity(topicCopy.id(), topicCopy.namespace(), "topic", AUDIT_INFO)));+ }+}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestUserMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestUserMetaService.javaindex e93a83bafd..d174434ce3 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestUserMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestUserMetaService.java@@ -19,6 +19,11 @@package org.apache.gravitino.storage.relational.service;+import static org.apache.gravitino.SupportsRelationOperations.Type.OWNER_REL;+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 com.google.common.collect.Lists;import com.google.common.collect.Sets;import java.io.IOException;@@ -40,23 +45,188 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.CatalogEntity;+import org.apache.gravitino.meta.FilesetEntity;import org.apache.gravitino.meta.RoleEntity;+import org.apache.gravitino.meta.SchemaEntity;+import org.apache.gravitino.meta.TableEntity;+import org.apache.gravitino.meta.TopicEntity;import org.apache.gravitino.meta.UserEntity;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.TestJDBCBackend;import org.apache.gravitino.storage.relational.mapper.RoleMetaMapper;+import org.apache.gravitino.storage.relational.mapper.UserMetaMapper;import org.apache.gravitino.storage.relational.po.RolePO;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.Assertions;-import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestTemplate;class TestUserMetaService extends TestJDBCBackend {- String metalakeName = "metalake";+ private final String metalakeName = "metalake_for_user_test";++ @TestTemplate+ public void testMetaLifeCycleFromCreationToDeletion() throws IOException {+ BaseMetalake metalake = createAndInsertMakeLake(metalakeName);+ BaseMetalake anotherMetaLake = createAndInsertMakeLake("another-metalake");+ CatalogEntity catalog = createAndInsertCatalog(metalakeName, "catalog");+ createAndInsertCatalog("another-metalake", "another-catalog");++ RoleEntity role =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace(metalakeName),+ "role",+ AUDIT_INFO,+ "catalog");+ backend.insert(role, false);++ UserEntity user =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace(metalakeName),+ "user",+ AUDIT_INFO,+ Lists.newArrayList(role.name()),+ Lists.newArrayList(role.id()));+ backend.insert(user, false);++ RoleEntity anotherRole =+ createRoleEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofRoleNamespace("another-metalake"),+ "another-role",+ AUDIT_INFO,+ "another-catalog");+ backend.insert(anotherRole, false);++ UserEntity anotherUser =+ createUserEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ AuthorizationUtils.ofUserNamespace("another-metalake"),+ "another-user",+ AUDIT_INFO,+ Lists.newArrayList(anotherRole.name()),+ Lists.newArrayList(anotherRole.id()));+ backend.insert(anotherUser, false);++ assertEquals(1, RoleMetaService.getInstance().listRolesByUserId(user.id()).size());++ UserEntity userEntity = backend.get(user.nameIdentifier(), Entity.EntityType.USER);+ assertEquals(user, userEntity);+ assertEquals(+ 1,+ SessionUtils.doWithCommitAndFetchResult(+ UserMetaMapper.class, mapper -> mapper.listUsersByRoleId(role.id()))+ .size());++ backend.insertRelation(+ OWNER_REL,+ metalake.nameIdentifier(),+ metalake.type(),+ user.nameIdentifier(),+ user.type(),+ true);++ backend.insertRelation(+ OWNER_REL,+ anotherMetaLake.nameIdentifier(),+ anotherMetaLake.type(),+ anotherUser.nameIdentifier(),+ anotherUser.type(),+ true);++ backend.insertRelation(+ OWNER_REL,+ catalog.nameIdentifier(),+ catalog.type(),+ user.nameIdentifier(),+ user.type(),+ true);++ SchemaEntity schema =+ createSchemaEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofSchema(metalakeName, "catalog"),+ "schema",+ AUDIT_INFO);+ backend.insert(schema, false);+ backend.insertRelation(+ OWNER_REL,+ schema.nameIdentifier(),+ schema.type(),+ user.nameIdentifier(),+ user.type(),+ true);++ TableEntity table =+ createTableEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofTable(metalakeName, "catalog", "schema"),+ "table",+ AUDIT_INFO);+ backend.insert(table, false);+ backend.insertRelation(+ OWNER_REL, table.nameIdentifier(), table.type(), user.nameIdentifier(), user.type(), true);++ TopicEntity topic =+ createTopicEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(metalakeName, "catalog", "schema"),+ "topic",+ AUDIT_INFO);+ backend.insert(topic, false);+ backend.insertRelation(+ OWNER_REL, topic.nameIdentifier(), topic.type(), user.nameIdentifier(), user.type(), true);++ FilesetEntity fileset =+ createFilesetEntity(+ RandomIdGenerator.INSTANCE.nextId(),+ NamespaceUtil.ofFileset(metalakeName, "catalog", "schema"),+ "fileset",+ AUDIT_INFO);+ backend.insert(fileset, false);+ backend.insertRelation(+ OWNER_REL,+ fileset.nameIdentifier(),+ fileset.type(),+ user.nameIdentifier(),+ user.type(),+ true);++ backend.insertRelation(+ OWNER_REL, role.nameIdentifier(), role.type(), user.nameIdentifier(), user.type(), true);++ // meta data soft delete+ backend.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE, true);++ // check existence after soft delete+ assertEquals(0, RoleMetaService.getInstance().listRolesByUserId(user.id()).size());+ assertFalse(backend.exists(user.nameIdentifier(), Entity.EntityType.USER));+ assertEquals(+ 0,+ SessionUtils.doWithCommitAndFetchResult(+ UserMetaMapper.class, mapper -> mapper.listUsersByRoleId(role.id()))+ .size());+ assertTrue(backend.exists(anotherUser.nameIdentifier(), Entity.EntityType.USER));++ // check legacy record after soft delete+ assertTrue(legacyRecordExistsInDB(user.id(), Entity.EntityType.USER));+ assertEquals(7, countOwnerRel(metalake.id()));+ assertEquals(1, countOwnerRel(anotherMetaLake.id()));++ // meta data hard delete+ for (Entity.EntityType entityType : Entity.EntityType.values()) {+ backend.hardDeleteLegacyData(entityType, Instant.now().toEpochMilli() + 1000);+ }+ assertFalse(legacyRecordExistsInDB(user.id(), Entity.EntityType.USER));+ assertEquals(0, countOwnerRel(metalake.id()));+ assertEquals(1, countOwnerRel(anotherMetaLake.id()));+ }- @Test+ @TestTemplatevoid getUserByIdentifier() throws IOException {AuditInfo auditInfo =AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();@@ -120,7 +290,7 @@ class TestUserMetaService extends TestJDBCBackend {Sets.newHashSet(user2.roleNames()), Sets.newHashSet(actualUser.roleNames()));}- @Test+ @TestTemplatevoid testListUsers() throws IOException {AuditInfo auditInfo =AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();@@ -143,7 +313,7 @@ class TestUserMetaService extends TestJDBCBackend {RoleEntity role1 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace("metalake"),+ AuthorizationUtils.ofRoleNamespace(metalakeName),"role1",auditInfo,"catalog");@@ -152,7 +322,7 @@ class TestUserMetaService extends TestJDBCBackend {RoleEntity role2 =createRoleEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofRoleNamespace("metalake"),+ AuthorizationUtils.ofRoleNamespace(metalakeName),"role2",auditInfo,"catalog");@@ -161,7 +331,7 @@ class TestUserMetaService extends TestJDBCBackend {UserEntity user2 =createUserEntity(RandomIdGenerator.INSTANCE.nextId(),- AuthorizationUtils.ofUserNamespace("metalake"),+ AuthorizationUtils.ofUserNamespace(metalakeName),"user2",auditInfo,Lists.newArrayList(role1.name(), role2.name()),@@ -218,7 +388,7 @@ class TestUserMetaService extends TestJDBCBackend {Assertions.assertEquals(expectUsers.size(), actualUsers.size());}- @Test+ @TestTemplatevoid insertUser() throws IOException {AuditInfo auditInfo =AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();@@ -370,7 +540,7 @@ class TestUserMetaService extends TestJDBCBackend {Assertions.assertNull(actualOverwriteUser4.roleNames());}- @Test+ @TestTemplatevoid deleteUser() throws IOException {AuditInfo auditInfo =AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();@@ -460,7 +630,7 @@ class TestUserMetaService extends TestJDBCBackend {Assertions.assertEquals(0, rolePOs.size());}- @Test+ @TestTemplatevoid updateUser() throws IOException {AuditInfo auditInfo =AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();@@ -680,7 +850,7 @@ class TestUserMetaService extends TestJDBCBackend {Assertions.assertEquals(Sets.newHashSet("role4"), Sets.newHashSet(userEntity.roleNames()));}- @Test+ @TestTemplatevoid deleteMetalake() throws IOException {AuditInfo auditInfo =AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();@@ -761,7 +931,7 @@ class TestUserMetaService extends TestJDBCBackend {Assertions.assertEquals(0, roleMetaService.listRolesByUserId(user2.id()).size());}- @Test+ @TestTemplatevoid deleteMetalakeCascade() throws IOException {AuditInfo auditInfo =AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();@@ -840,7 +1010,7 @@ class TestUserMetaService extends TestJDBCBackend {Assertions.assertEquals(0, roleMetaService.listRolesByUserId(user2.id()).size());}- @Test+ @TestTemplatevoid deleteUserMetasByLegacyTimeline() throws IOException {AuditInfo auditInfo =AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();