Skip to content

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

[#13882] feat(core): Add Domain entity and metadata storage (#14281)

Jerry Shao08e68c30fa4f
diff --git a/core/src/main/java/org/apache/gravitino/Entity.java b/core/src/main/java/org/apache/gravitino/Entity.java
index 62b0e8acde..61b96551ea 100644
--- a/core/src/main/java/org/apache/gravitino/Entity.java
+++ b/core/src/main/java/org/apache/gravitino/Entity.java
@@ -60,6 +60,9 @@ public interface Entity extends Serializable {
String JOB_SCHEMA_NAME = "job";
+ /** The domain schema name in the system catalog. */
+ String DOMAIN_SCHEMA_NAME = "domain";
+
/** Enumeration defining the types of entities in the Gravitino framework. */
@Getter
enum EntityType {
@@ -83,7 +86,8 @@ public interface Entity extends Serializable {
JOB_TEMPLATE,
JOB,
AUDIT,
- FUNCTION;
+ FUNCTION,
+ DOMAIN;
}
/**
diff --git a/core/src/main/java/org/apache/gravitino/EntityFieldLimits.java b/core/src/main/java/org/apache/gravitino/EntityFieldLimits.java
index 52de6f9b6b..6a912e7776 100644
--- a/core/src/main/java/org/apache/gravitino/EntityFieldLimits.java
+++ b/core/src/main/java/org/apache/gravitino/EntityFieldLimits.java
@@ -39,6 +39,9 @@ public final class EntityFieldLimits {
/** The maximum number of characters of an entity comment stored in a 256-character column. */
public static final int MAX_COMMENT_LENGTH = 256;
+ /** The maximum number of characters of a tag value, as stored in a tag relation. */
+ public static final int MAX_TAG_VALUE_LENGTH = 256;
+
/** The maximum number of characters of a column comment. */
public static final int MAX_COLUMN_COMMENT_LENGTH = 4096;
diff --git a/core/src/main/java/org/apache/gravitino/meta/DomainEntity.java b/core/src/main/java/org/apache/gravitino/meta/DomainEntity.java
new file mode 100644
index 0000000000..1c7831c4d0
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/meta/DomainEntity.java
@@ -0,0 +1,200 @@
+/*
+ * 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.meta;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import lombok.AccessLevel;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import lombok.experimental.Accessors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.Audit;
+import org.apache.gravitino.Auditable;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityFieldLimits;
+import org.apache.gravitino.Field;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.tag.TagValue;
+
+/**
+ * The stored form of a {@link Domain}. It holds the domain's data only; the operations on {@link
+ * Domain} are served by the domain manager.
+ *
+ * <p>The backing tag is stored with the domain as the ID of the tag and an optional value; the tag
+ * name is read from the tag when the domain is read. If the tag is deleted, the ID stays on the
+ * domain but has no name, so the domain has no backing tag. The parent is not stored with the
+ * domain: it comes from the sub-domain relation and is set on the entity when it is read.
+ */
+@Getter
+@Accessors(fluent = true)
+@EqualsAndHashCode
+@ToString
+public class DomainEntity implements Entity, Auditable, HasIdentifier {
+
+ /** The unique id of the domain entity. */
+ public static final Field ID =
+ Field.required("id", Long.class, "The unique id of the domain entity.");
+
+ /** The name of the domain entity. */
+ public static final Field NAME =
+ Field.required("name", "The name of the domain entity.", EntityFieldLimits.MAX_NAME_LENGTH);
+
+ /** The comment of the domain entity. */
+ public static final Field COMMENT =
+ Field.optional(
+ "comment", "The comment of the domain entity.", EntityFieldLimits.MAX_COMMENT_LENGTH);
+
+ /** The properties of the domain entity. */
+ public static final Field PROPERTIES =
+ Field.optional("properties", Map.class, "The properties of the domain entity.");
+
+ /** The status of the domain entity. */
+ public static final Field STATUS =
+ Field.required("status", Domain.Status.class, "The status of the domain entity.");
+
+ /** The ID of the backing tag of the domain entity. */
+ public static final Field BACKING_TAG_ID =
+ Field.optional(
+ "backing_tag_id", Long.class, "The ID of the backing tag of the domain entity.");
+
+ /** The value of the backing tag of the domain entity. */
+ public static final Field BACKING_TAG_VALUE =
+ Field.optional(
+ "backing_tag_value",
+ "The value of the backing tag of the domain entity.",
+ EntityFieldLimits.MAX_TAG_VALUE_LENGTH);
+
+ /** The audit details of the domain entity. */
+ public static final Field AUDIT_INFO =
+ Field.required("audit_info", Audit.class, "The audit details of the domain entity.");
+
+ private final Long id;
+ private final String name;
+ private final Namespace namespace;
+ @Nullable private final String comment;
+ private final Map<String, String> properties;
+ private final Domain.Status status;
+
+ @Getter(AccessLevel.NONE)
+ @Nullable
+ private final String parent;
+
+ /** The ID of the backing tag, or null if the domain has none. */
+ @Nullable private final Long backingTagId;
+
+ /** The name of the backing tag, or null if the domain has none or the tag is deleted. */
+ @Getter(AccessLevel.NONE)
+ @Nullable
+ private final String backingTagName;
+
+ /** The value of the backing tag, or null if the tag is bound without a value. */
+ @Nullable private final String backingTagValue;
+
+ private final Audit auditInfo;
+
+ @lombok.Builder(setterPrefix = "with", toBuilder = true)
+ private DomainEntity(
+ Long id,
+ String name,
+ Namespace namespace,
+ @Nullable String comment,
+ Map<String, String> properties,
+ Domain.Status status,
+ @Nullable String parent,
+ @Nullable Long backingTagId,
+ @Nullable String backingTagName,
+ @Nullable String backingTagValue,
+ Audit auditInfo) {
+ this.id = id;
+ this.name = name;
+ this.namespace = namespace;
+ this.comment = comment;
+ this.properties = properties;
+ this.status = status;
+ this.parent = parent;
+ this.backingTagId = backingTagId;
+ // The name is read from the bound tag, so it follows the ID: clearing the ID unbinds the tag.
+ this.backingTagName = backingTagId == null ? null : backingTagName;
+ this.backingTagValue = backingTagValue;
+ this.auditInfo = auditInfo;
+ validate();
+ Preconditions.checkArgument(
+ backingTagId != null || backingTagValue == null,
+ "The backing tag value of domain %s needs a backing tag ID",
+ name);
+ // A tag bound without a value is stored as NULL, so the value is never blank.
+ Preconditions.checkArgument(
+ backingTagValue == null || StringUtils.isNotBlank(backingTagValue),
+ "The backing tag value of domain %s must not be blank",
+ name);
+ }
+
+ @Override
+ public Map<Field, Object> fields() {
+ Map<Field, Object> fields = Maps.newHashMap();
+ fields.put(ID, id);
+ fields.put(NAME, name);
+ fields.put(COMMENT, comment);
+ fields.put(PROPERTIES, properties);
+ fields.put(STATUS, status);
+ fields.put(BACKING_TAG_ID, backingTagId);
+ fields.put(BACKING_TAG_VALUE, backingTagValue);
+ fields.put(AUDIT_INFO, auditInfo);
+
+ return Collections.unmodifiableMap(fields);
+ }
+
+ @Override
+ public EntityType type() {
+ return EntityType.DOMAIN;
+ }
+
+ /**
+ * Returns the name of the parent domain.
+ *
+ * @return The name of the parent domain, or empty if the domain is top-level.
+ */
+ public Optional<String> parent() {
+ return Optional.ofNullable(parent);
+ }
+
+ /**
+ * Returns the backing tag of the domain. It is empty if the domain has no backing tag or the tag
+ * has been deleted.
+ *
+ * @return The backing tag of the domain.
+ */
+ public Optional<TagValue> backingTag() {
+ if (backingTagName == null) {
+ return Optional.empty();
+ }
+ return Optional.of(
+ backingTagValue == null
+ ? TagValue.noValue(backingTagName)
+ : TagValue.of(backingTagName, backingTagValue));
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
index 6615a651ac..ee083d14ab 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
@@ -53,6 +53,7 @@ import org.apache.gravitino.cache.BaseEntityCache;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.DomainEntity;
import org.apache.gravitino.meta.FilesetEntity;
import org.apache.gravitino.meta.FunctionEntity;
import org.apache.gravitino.meta.GenericEntity;
@@ -76,6 +77,7 @@ import org.apache.gravitino.storage.relational.converters.SQLExceptionConverterF
import org.apache.gravitino.storage.relational.database.H2Database;
import org.apache.gravitino.storage.relational.po.cache.OperateType;
import org.apache.gravitino.storage.relational.service.CatalogMetaService;
+import org.apache.gravitino.storage.relational.service.DomainMetaService;
import org.apache.gravitino.storage.relational.service.FilesetMetaService;
import org.apache.gravitino.storage.relational.service.FunctionMetaService;
import org.apache.gravitino.storage.relational.service.GroupMetaService;
@@ -182,6 +184,8 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
case JOB_TEMPLATE:
return (List<E>)
JobTemplateMetaService.getInstance().listJobTemplatesByNamespace(namespace);
+ case DOMAIN:
+ return (List<E>) DomainMetaService.getInstance().listDomainsByNamespace(namespace);
case JOB:
return (List<E>) JobMetaService.getInstance().listJobsByNamespace(namespace);
case TABLE_STATISTIC:
@@ -295,6 +299,8 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
return (E) PolicyMetaService.getInstance().getPolicyByIdentifier(ident);
case JOB_TEMPLATE:
return (E) JobTemplateMetaService.getInstance().getJobTemplateByIdentifier(ident);
+ case DOMAIN:
+ return (E) DomainMetaService.getInstance().getDomainByIdentifier(ident);
case JOB:
return (E) JobMetaService.getInstance().getJobByIdentifier(ident);
case VIEW:
@@ -345,6 +351,8 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
case JOB_TEMPLATE:
return (List<E>)
JobTemplateMetaService.getInstance().batchGetJobTemplateByIdentifier(identifiers);
+ case DOMAIN:
+ return (List<E>) DomainMetaService.getInstance().batchGetDomainByIdentifier(identifiers);
case USER:
// TODO: Add true batch SQL operations for users, roles, and views
List<E> users = Lists.newArrayList();
@@ -536,6 +544,10 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
return SemanticModelMetaService.getInstance()
.deleteSemanticModelMetasByLegacyTimeline(
legacyTimeline, GARBAGE_COLLECTOR_SINGLE_DELETION_LIMIT);
+ case DOMAIN:
+ return DomainMetaService.getInstance()
+ .deleteDomainMetasByLegacyTimeline(
+ legacyTimeline, GARBAGE_COLLECTOR_SINGLE_DELETION_LIMIT);
case AUDIT:
return 0;
// TODO: Implement hard delete logic for these entity types.
@@ -573,6 +585,7 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
case JOB_TEMPLATE:
case JOB:
case VIEW:
+ case DOMAIN:
// These entity types have not implemented multi-versions, so we can skip.
return 0;
@@ -1054,6 +1067,8 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
PolicyMetaService.getInstance().insertPolicy((PolicyEntity) e, overwritten);
} else if (e instanceof JobTemplateEntity) {
JobTemplateMetaService.getInstance().insertJobTemplate((JobTemplateEntity) e, overwritten);
+ } else if (e instanceof DomainEntity) {
+ DomainMetaService.getInstance().insertDomain((DomainEntity) e, overwritten);
} else if (e instanceof JobEntity) {
JobMetaService.getInstance().insertJob((JobEntity) e, overwritten);
} else if (e instanceof ViewEntity) {
@@ -1105,6 +1120,8 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
return (E) PolicyMetaService.getInstance().updatePolicy(ident, updater);
case JOB_TEMPLATE:
return (E) JobTemplateMetaService.getInstance().updateJobTemplate(ident, updater);
+ case DOMAIN:
+ return (E) DomainMetaService.getInstance().updateDomain(ident, updater);
case JOB:
return (E) JobMetaService.getInstance().updateJob(ident, updater);
case VIEW:
@@ -1150,6 +1167,8 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
return PolicyMetaService.getInstance().deletePolicy(ident);
case JOB_TEMPLATE:
return JobTemplateMetaService.getInstance().deleteJobTemplate(ident);
+ case DOMAIN:
+ return DomainMetaService.getInstance().deleteDomain(ident);
case JOB:
return JobMetaService.getInstance().deleteJob(ident);
case VIEW:
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStoreIdResolver.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStoreIdResolver.java
index e5a4aae6fb..2bb8a96553 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStoreIdResolver.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStoreIdResolver.java
@@ -28,6 +28,7 @@ import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.storage.relational.helper.CatalogIds;
import org.apache.gravitino.storage.relational.helper.SchemaIds;
import org.apache.gravitino.storage.relational.service.CatalogMetaService;
+import org.apache.gravitino.storage.relational.service.DomainMetaService;
import org.apache.gravitino.storage.relational.service.FilesetMetaService;
import org.apache.gravitino.storage.relational.service.FunctionMetaService;
import org.apache.gravitino.storage.relational.service.GroupMetaService;
@@ -56,7 +57,8 @@ public class RelationalEntityStoreIdResolver implements EntityIdResolver {
Entity.EntityType.TAG,
Entity.EntityType.POLICY,
Entity.EntityType.JOB,
- Entity.EntityType.JOB_TEMPLATE);
+ Entity.EntityType.JOB_TEMPLATE,
+ Entity.EntityType.DOMAIN);
private static final Set<Entity.EntityType> ENTITY_TYPES_REQUIRING_CATALOG_IDS =
ImmutableSet.of(Entity.EntityType.CATALOG);
@@ -159,6 +161,12 @@ public class RelationalEntityStoreIdResolver implements EntityIdResolver {
.getJobTemplateIdByMetalakeIdAndName(metalakeId, nameIdentifier.name());
return new NamespacedEntityId(jobTemplateId, metalakeId);
+ case DOMAIN:
+ long domainId =
+ DomainMetaService.getInstance()
+ .getDomainIdByMetalakeIdAndName(metalakeId, nameIdentifier.name());
+ return new NamespacedEntityId(domainId, metalakeId);
+
case JOB:
long jobId =
Long.parseLong(nameIdentifier.name().substring(JobHandle.JOB_ID_PREFIX.length()));
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaMapper.java
new file mode 100644
index 0000000000..59cf4ad530
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaMapper.java
@@ -0,0 +1,196 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.mapper;
+
+import java.util.List;
+import org.apache.gravitino.storage.relational.po.DomainPO;
+import org.apache.ibatis.annotations.DeleteProvider;
+import org.apache.ibatis.annotations.InsertProvider;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+import org.apache.ibatis.annotations.SelectProvider;
+import org.apache.ibatis.annotations.UpdateProvider;
+
+/** MyBatis mapper of the {@code domain_meta} table. */
+public interface DomainMetaMapper {
+
+ /** The name of the domain table. */
+ String DOMAIN_TABLE_NAME = "domain_meta";
+
+ /**
+ * Counts deleted rows that still reserve the requested domain ID.
+ *
+ * @param domainId The domain ID.
+ * @return The number of deleted rows with this ID.
+ */
+ @Select(
+ "SELECT COUNT(*) FROM "
+ + DOMAIN_TABLE_NAME
+ + " WHERE domain_id = #{domainId} AND deleted_at > 0")
+ int countDeletedDomainMetasById(@Param("domainId") Long domainId);
+
+ /**
+ * Lists the active domains of a metalake.
+ *
+ * @param metalakeName The metalake name.
+ * @return The active domains.
+ */
+ @SelectProvider(type = DomainMetaSQLProviderFactory.class, method = "listDomainPOsByMetalake")
+ List<DomainPO> listDomainPOsByMetalake(@Param("metalakeName") String metalakeName);
+
+ /**
+ * Selects an active domain by metalake name and domain name.
+ *
+ * @param metalakeName The metalake name.
+ * @param domainName The domain name.
+ * @return The domain, or null if it is not active.
+ */
+ @SelectProvider(
+ type = DomainMetaSQLProviderFactory.class,
+ method = "selectDomainMetaByMetalakeAndName")
+ DomainPO selectDomainMetaByMetalakeAndName(
+ @Param("metalakeName") String metalakeName, @Param("domainName") String domainName);
+
+ /**
+ * Selects an active domain by metalake ID and domain name, for ID lookups. The backing tag name
+ * is not read.
+ *
+ * @param metalakeId The metalake ID.
+ * @param domainName The domain name.
+ * @return The domain, or null if it is not active.
+ */
+ @SelectProvider(
+ type = DomainMetaSQLProviderFactory.class,
+ method = "selectDomainMetaByMetalakeIdAndName")
+ DomainPO selectDomainMetaByMetalakeIdAndName(
+ @Param("metalakeId") Long metalakeId, @Param("domainName") String domainName);
+
+ /**
+ * Selects and exclusively locks an active domain by its natural key. The backing tag name is not
+ * read, so that no tag row is locked.
+ *
+ * @param metalakeId The metalake ID.
+ * @param domainName The domain name.
+ * @return The locked domain, or null if the natural key is not active.
+ */
+ @SelectProvider(
+ type = DomainMetaSQLProviderFactory.class,
+ method = "selectDomainMetaByMetalakeIdAndNameForUpdate")
+ DomainPO selectDomainMetaByMetalakeIdAndNameForUpdate(
+ @Param("metalakeId") Long metalakeId, @Param("domainName") String domainName);
+
+ /**
+ * Selects an active domain by ID.
+ *
+ * @param domainId The domain ID.
+ * @return The domain, or null if it is not active.
+ */
+ @SelectProvider(type = DomainMetaSQLProviderFactory.class, method = "selectDomainMetaById")
+ DomainPO selectDomainMetaById(@Param("domainId") Long domainId);
+
+ /**
+ * Selects and exclusively locks an active domain by ID. The backing tag name is not read, so that
+ * no tag row is locked.
+ *
+ * @param domainId The domain ID.
+ * @return The locked domain, or null if it is not active.
+ */
+ @SelectProvider(
+ type = DomainMetaSQLProviderFactory.class,
+ method = "selectDomainMetaByIdForUpdate")
+ DomainPO selectDomainMetaByIdForUpdate(@Param("domainId") Long domainId);
+
+ /**
+ * Lists the active domains with the given IDs, for name lookups. The backing tag name is not
+ * read.
+ *
+ * @param domainIds The domain IDs.
+ * @return The active domains.
+ */
+ @SelectProvider(type = DomainMetaSQLProviderFactory.class, method = "listDomainPOsByDomainIds")
+ List<DomainPO> listDomainPOsByDomainIds(@Param("domainIds") List<Long> domainIds);
+
+ /**
+ * Lists the active domains of a metalake with the given names.
+ *
+ * @param metalakeName The metalake name.
+ * @param domainNames The domain names.
+ * @return The active domains.
+ */
+ @SelectProvider(
+ type = DomainMetaSQLProviderFactory.class,
+ method = "listDomainPOsByMetalakeAndDomainNames")
+ List<DomainPO> listDomainPOsByMetalakeAndDomainNames(
+ @Param("metalakeName") String metalakeName, @Param("domainNames") List<String> domainNames);
+
+ /**
+ * Inserts a domain.
+ *
+ * @param domainPO The domain to insert.
+ */
+ @InsertProvider(type = DomainMetaSQLProviderFactory.class, method = "insertDomainMeta")
+ void insertDomainMeta(@Param("domainMeta") DomainPO domainPO);
+
+ /**
+ * Updates an active domain when its version still matches the observed one.
+ *
+ * @param newDomainPO The new domain row.
+ * @param oldDomainPO The domain row observed by the caller.
+ * @return The number of affected rows.
+ */
+ @UpdateProvider(type = DomainMetaSQLProviderFactory.class, method = "updateDomainMeta")
+ Integer updateDomainMeta(
+ @Param("newDomainMeta") DomainPO newDomainPO, @Param("oldDomainMeta") DomainPO oldDomainPO);
+
+ /**
+ * Soft-deletes an active domain when its version still matches.
+ *
+ * @param domainId The domain ID.
+ * @param currentVersion The version observed by the caller.
+ * @return The number of affected rows.
+ */
+ @UpdateProvider(
+ type = DomainMetaSQLProviderFactory.class,
+ method = "softDeleteDomainMetaByIdAndVersion")
+ Integer softDeleteDomainMetaByIdAndVersion(
+ @Param("domainId") Long domainId, @Param("currentVersion") Long currentVersion);
+
+ /**
+ * Soft-deletes all active domains of a metalake.
+ *
+ * @param metalakeId The metalake ID.
+ */
+ @UpdateProvider(
+ type = DomainMetaSQLProviderFactory.class,
+ method = "softDeleteDomainMetasByMetalakeId")
+ void softDeleteDomainMetasByMetalakeId(@Param("metalakeId") Long metalakeId);
+
+ /**
+ * Hard-deletes domains soft-deleted before the given time.
+ *
+ * @param legacyTimeline The time before which soft-deleted rows are removed.
+ * @param limit The maximum number of rows to remove.
+ * @return The number of removed rows.
+ */
+ @DeleteProvider(
+ type = DomainMetaSQLProviderFactory.class,
+ method = "deleteDomainMetasByLegacyTimeline")
+ Integer deleteDomainMetasByLegacyTimeline(
+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit);
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaSQLProviderFactory.java
new file mode 100644
index 0000000000..e81342d898
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/DomainMetaSQLProviderFactory.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.mapper;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;
+import org.apache.gravitino.storage.relational.mapper.provider.base.DomainMetaBaseSQLProvider;
+import org.apache.gravitino.storage.relational.mapper.provider.postgresql.DomainMetaPostgreSQLProvider;
+import org.apache.gravitino.storage.relational.po.DomainPO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.ibatis.annotations.Param;
+
+/** Selects the SQL of the {@code domain_meta} table for the configured backend. */
+public class DomainMetaSQLProviderFactory {
+
+ private static final Map<JDBCBackendType, DomainMetaBaseSQLProvider>
+ DOMAIN_META_SQL_PROVIDER_MAP =
+ ImmutableMap.of(
+ JDBCBackendType.MYSQL, new DomainMetaMySQLProvider(),
+ JDBCBackendType.H2, new DomainMetaH2Provider(),
+ JDBCBackendType.POSTGRESQL, new DomainMetaPostgreSQLProvider());
+
+ /**
+ * Returns the SQL provider of the configured backend.
+ *
+ * @return The SQL provider.
+ */
+ public static DomainMetaBaseSQLProvider getProvider() {
+ String databaseId =
+ SqlSessionFactoryHelper.getInstance()
+ .getSqlSessionFactory()
+ .getConfiguration()
+ .getDatabaseId();
+
+ JDBCBackendType jdbcBackendType = JDBCBackendType.fromString(databaseId);
+ return DOMAIN_META_SQL_PROVIDER_MAP.get(jdbcBackendType);
+ }
+
+ static class DomainMetaMySQLProvider extends DomainMetaBaseSQLProvider {}
+
+ static class DomainMetaH2Provider extends DomainMetaBaseSQLProvider {}
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#listDomainPOsByMetalake}. */
+ public static String listDomainPOsByMetalake(@Param("metalakeName") String metalakeName) {
+ return getProvider().listDomainPOsByMetalake(metalakeName);
+ }
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#selectDomainMetaByMetalakeAndName}. */
+ public static String selectDomainMetaByMetalakeAndName(
+ @Param("metalakeName") String metalakeName, @Param("domainName") String domainName) {
+ return getProvider().selectDomainMetaByMetalakeAndName(metalakeName, domainName);
+ }
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#selectDomainMetaByMetalakeIdAndName}. */
+ public static String selectDomainMetaByMetalakeIdAndName(
+ @Param("metalakeId") Long metalakeId, @Param("domainName") String domainName) {
+ return getProvider().selectDomainMetaByMetalakeIdAndName(metalakeId, domainName);
+ }
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#selectDomainMetaByMetalakeIdAndNameForUpdate}. */
+ public static String selectDomainMetaByMetalakeIdAndNameForUpdate(
+ @Param("metalakeId") Long metalakeId, @Param("domainName") String domainName) {
+ return getProvider().selectDomainMetaByMetalakeIdAndNameForUpdate(metalakeId, domainName);
+ }
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#selectDomainMetaById}. */
+ public static String selectDomainMetaById(@Param("domainId") Long domainId) {
+ return getProvider().selectDomainMetaById(domainId);
+ }
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#selectDomainMetaByIdForUpdate}. */
+ public static String selectDomainMetaByIdForUpdate(@Param("domainId") Long domainId) {
+ return getProvider().selectDomainMetaByIdForUpdate(domainId);
+ }
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#listDomainPOsByDomainIds}. */
+ public static String listDomainPOsByDomainIds(@Param("domainIds") List<Long> domainIds) {
+ return getProvider().listDomainPOsByDomainIds(domainIds);
+ }
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#listDomainPOsByMetalakeAndDomainNames}. */
+ public static String listDomainPOsByMetalakeAndDomainNames(
+ @Param("metalakeName") String metalakeName, @Param("domainNames") List<String> domainNames) {
+ return getProvider().listDomainPOsByMetalakeAndDomainNames(metalakeName, domainNames);
+ }
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#insertDomainMeta}. */
+ public static String insertDomainMeta(@Param("domainMeta") DomainPO domainPO) {
+ return getProvider().insertDomainMeta(domainPO);
+ }
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#updateDomainMeta}. */
+ public static String updateDomainMeta(
+ @Param("newDomainMeta") DomainPO newDomainPO, @Param("oldDomainMeta") DomainPO oldDomainPO) {
+ return getProvider().updateDomainMeta(newDomainPO, oldDomainPO);
+ }
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#softDeleteDomainMetaByIdAndVersion}. */
+ public static String softDeleteDomainMetaByIdAndVersion(
+ @Param("domainId") Long domainId, @Param("currentVersion") Long currentVersion) {
+ return getProvider().softDeleteDomainMetaByIdAndVersion(domainId, currentVersion);
+ }
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#softDeleteDomainMetasByMetalakeId}. */
+ public static String softDeleteDomainMetasByMetalakeId(@Param("metalakeId") Long metalakeId) {
+ return getProvider().softDeleteDomainMetasByMetalakeId(metalakeId);
+ }
+
+ /** Delegates {@link DomainMetaBaseSQLProvider#deleteDomainMetasByLegacyTimeline}. */
+ public static String deleteDomainMetasByLegacyTimeline(
+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {
+ return getProvider().deleteDomainMetasByLegacyTimeline(legacyTimeline, limit);
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/LiveEndpointSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/LiveEndpointSQLProvider.java
index 4f1b85e7d1..48e42a1397 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/LiveEndpointSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/LiveEndpointSQLProvider.java
@@ -96,6 +96,10 @@ public class LiveEndpointSQLProvider {
table = JobTemplateMetaMapper.TABLE_NAME;
idColumn = "job_template_id";
break;
+ case DOMAIN:
+ table = DomainMetaMapper.DOMAIN_TABLE_NAME;
+ idColumn = "domain_id";
+ break;
case JOB:
table = JobMetaMapper.TABLE_NAME;
idColumn = "job_run_id";
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OwnerMetaSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OwnerMetaSQLProviderFactory.java
index bcdd7da2a8..c96d4ef018 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OwnerMetaSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/OwnerMetaSQLProviderFactory.java
@@ -117,6 +117,10 @@ public class OwnerMetaSQLProviderFactory {
table = JobTemplateMetaMapper.TABLE_NAME;
idColumn = "job_template_id";
break;
+ case DOMAIN:
+ table = DomainMetaMapper.DOMAIN_TABLE_NAME;
+ idColumn = "domain_id";
+ break;
case JOB:
table = JobMetaMapper.TABLE_NAME;
idColumn = "job_run_id";
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
index ab433bb5cf..934b7af174 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.storage.relational.mapper.provider;
import com.google.common.collect.ImmutableList;
import java.util.List;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.DomainMetaMapper;
import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
@@ -66,6 +67,7 @@ public class DefaultMapperPackageProvider implements MapperPackageProvider {
public List<Class<?>> getMapperClasses() {
return ImmutableList.of(
CatalogMetaMapper.class,
+ DomainMetaMapper.class,
EntityChangeLogMapper.class,
FilesetMetaMapper.class,
FilesetVersionMapper.class,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/DomainMetaBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/DomainMetaBaseSQLProvider.java
new file mode 100644
index 0000000000..0cf22b34ff
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/DomainMetaBaseSQLProvider.java
@@ -0,0 +1,302 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.mapper.provider.base;
+
+import static org.apache.gravitino.storage.relational.mapper.DomainMetaMapper.DOMAIN_TABLE_NAME;
+
+import java.util.List;
+import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.TagMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.po.DomainPO;
+import org.apache.ibatis.annotations.Param;
+
+/** The SQL of the {@code domain_meta} table shared by all backends. */
+public class DomainMetaBaseSQLProvider {
+
+ private static final String DOMAIN_COLUMNS =
+ "dm.domain_id as domainId, dm.domain_name as domainName,"
+ + " dm.metalake_id as metalakeId,"
+ + " dm.domain_comment as comment,"
+ + " dm.domain_status as status,"
+ + " dm.backing_tag_id as backingTagId,"
+ + " dm.backing_tag_value as backingTagValue,"
+ + " dm.properties as properties,"
+ + " dm.audit_info as auditInfo,"
+ + " dm.current_version as currentVersion,"
+ + " dm.last_version as lastVersion,"
+ + " dm.deleted_at as deletedAt";
+
+ // Reads take the backing tag name from the live tag, so a deleted tag reads as no backing tag.
+ // Locking reads do not join: they must lock the domain row only, and PostgreSQL rejects FOR
+ // UPDATE on the nullable side of an outer join.
+ private static final String DOMAIN_COLUMNS_WITH_BACKING_TAG_NAME =
+ DOMAIN_COLUMNS + ", bt.tag_name as backingTagName";
+
+ private static final String BACKING_TAG_JOIN =
+ " LEFT JOIN "
+ + TagMetaMapper.TAG_TABLE_NAME
+ + " bt ON dm.backing_tag_id = bt.tag_id AND dm.metalake_id = bt.metalake_id"
+ + " AND bt.deleted_at = 0";
+
+ /**
+ * Returns SQL that lists the active domains of a metalake.
+ *
+ * @param metalakeName The metalake name.
+ * @return The SQL.
+ */
+ public String listDomainPOsByMetalake(@Param("metalakeName") String metalakeName) {
+ return "SELECT "
+ + DOMAIN_COLUMNS_WITH_BACKING_TAG_NAME
+ + " FROM "
+ + DOMAIN_TABLE_NAME
+ + " dm JOIN "
+ + MetalakeMetaMapper.TABLE_NAME
+ + " mm ON dm.metalake_id = mm.metalake_id"
+ + BACKING_TAG_JOIN
+ + " WHERE mm.metalake_name = #{metalakeName} AND dm.deleted_at = 0 AND mm.deleted_at = 0";
+ }
+
+ /**
+ * Returns SQL that selects an active domain by metalake name and domain name.
+ *
+ * @param metalakeName The metalake name.
+ * @param domainName The domain name.
+ * @return The SQL.
+ */
+ public String selectDomainMetaByMetalakeAndName(
+ @Param("metalakeName") String metalakeName, @Param("domainName") String domainName) {
+ return "SELECT "
+ + DOMAIN_COLUMNS_WITH_BACKING_TAG_NAME
+ + " FROM "
+ + DOMAIN_TABLE_NAME
+ + " dm JOIN "
+ + MetalakeMetaMapper.TABLE_NAME
+ + " mm ON dm.metalake_id = mm.metalake_id"
+ + BACKING_TAG_JOIN
+ + " WHERE mm.metalake_name = #{metalakeName} AND dm.domain_name = #{domainName}"
+ + " AND dm.deleted_at = 0 AND mm.deleted_at = 0";
+ }
+
+ /**
+ * Returns SQL that selects an active domain by metalake ID and domain name.
+ *
+ * @param metalakeId The metalake ID.
+ * @param domainName The domain name.
+ * @return The SQL.
+ */
+ public String selectDomainMetaByMetalakeIdAndName(
+ @Param("metalakeId") Long metalakeId, @Param("domainName") String domainName) {
+ return "SELECT "
+ + DOMAIN_COLUMNS
+ + " FROM "
+ + DOMAIN_TABLE_NAME
+ + " dm WHERE dm.metalake_id = #{metalakeId} AND dm.domain_name = #{domainName}"
+ + " AND dm.deleted_at = 0";
+ }
+
+ /**
+ * Returns SQL that selects and exclusively locks an active domain by its natural key.
+ *
+ * @param metalakeId The metalake ID.
+ * @param domainName The domain name.
+ * @return The SQL.
+ */
+ public String selectDomainMetaByMetalakeIdAndNameForUpdate(
+ @Param("metalakeId") Long metalakeId, @Param("domainName") String domainName) {
+ return selectDomainMetaByMetalakeIdAndName(metalakeId, domainName) + " FOR UPDATE";
+ }
+
+ /**
+ * Returns SQL that selects an active domain by ID.
+ *
+ * @param domainId The domain ID.
+ * @return The SQL.
+ */
+ public String selectDomainMetaById(@Param("domainId") Long domainId) {
+ return "SELECT "
+ + DOMAIN_COLUMNS_WITH_BACKING_TAG_NAME
+ + " FROM "
+ + DOMAIN_TABLE_NAME
+ + " dm"
+ + BACKING_TAG_JOIN
+ + " WHERE dm.domain_id = #{domainId} AND dm.deleted_at = 0";
+ }
+
+ /**
+ * Returns SQL that selects and exclusively locks an active domain by ID.
+ *
+ * @param domainId The domain ID.
+ * @return The SQL.
+ */
+ public String selectDomainMetaByIdForUpdate(@Param("domainId") Long domainId) {
+ return "SELECT "
+ + DOMAIN_COLUMNS
+ + " FROM "
+ + DOMAIN_TABLE_NAME
+ + " dm WHERE dm.domain_id = #{domainId} AND dm.deleted_at = 0 FOR UPDATE";
+ }
+
+ /**
+ * Returns SQL that lists the active domains with the given IDs.
+ *
+ * @param domainIds The domain IDs.
+ * @return The SQL.
+ */
+ public String listDomainPOsByDomainIds(@Param("domainIds") List<Long> domainIds) {
+ return "<script>"
+ + "SELECT "
+ + DOMAIN_COLUMNS
+ + " FROM "
+ + DOMAIN_TABLE_NAME
+ + " dm WHERE dm.deleted_at = 0"
+ + " AND dm.domain_id IN ("
+ + "<foreach collection='domainIds' item='domainId' separator=','>"
+ + "#{domainId}"
+ + "</foreach>"
+ + ")"
+ + "</script>";
+ }
+
+ /**
+ * Returns SQL that lists the active domains of a metalake with the given names.
+ *
+ * @param metalakeName The metalake name.
+ * @param domainNames The domain names.
+ * @return The SQL.
+ */
+ public String listDomainPOsByMetalakeAndDomainNames(
+ @Param("metalakeName") String metalakeName, @Param("domainNames") List<String> domainNames) {
+ return "<script>"
+ + "SELECT "
+ + DOMAIN_COLUMNS_WITH_BACKING_TAG_NAME
+ + " FROM "
+ + DOMAIN_TABLE_NAME
+ + " dm JOIN "
+ + MetalakeMetaMapper.TABLE_NAME
+ + " mm ON dm.metalake_id = mm.metalake_id"
+ + BACKING_TAG_JOIN
+ + " WHERE mm.metalake_name = #{metalakeName}"
+ + " AND dm.domain_name IN ("
+ + "<foreach collection='domainNames' item='domainName' separator=','>"
+ + "#{domainName}"
+ + "</foreach>"
+ + ")"
+ + " AND dm.deleted_at = 0 AND mm.deleted_at = 0"
+ + "</script>";
+ }
+
+ /**
+ * Returns SQL that inserts a domain.
+ *
+ * @param domainPO The domain to insert.
+ * @return The SQL.
+ */
+ public String insertDomainMeta(@Param("domainMeta") DomainPO domainPO) {
+ return "INSERT INTO "
+ + DOMAIN_TABLE_NAME
+ + " (domain_id, domain_name, metalake_id, domain_comment, domain_status, backing_tag_id,"
+ + " backing_tag_value, properties, audit_info, current_version, last_version, deleted_at)"
+ + " VALUES ("
+ + " #{domainMeta.domainId},"
+ + " #{domainMeta.domainName},"
+ + " #{domainMeta.metalakeId},"
+ + " #{domainMeta.comment},"
+ + " #{domainMeta.status},"
+ + " #{domainMeta.backingTagId},"
+ + " #{domainMeta.backingTagValue},"
+ + " #{domainMeta.properties},"
+ + " #{domainMeta.auditInfo},"
+ + " #{domainMeta.currentVersion},"
+ + " #{domainMeta.lastVersion},"
+ + " #{domainMeta.deletedAt}"
+ + " )";
+ }
+
+ /**
+ * Returns SQL that updates an active domain when its version still matches the observed one.
+ *
+ * @param newDomainPO The new domain row.
+ * @param oldDomainPO The domain row observed by the caller.
+ * @return The SQL.
+ */
+ public String updateDomainMeta(
+ @Param("newDomainMeta") DomainPO newDomainPO, @Param("oldDomainMeta") DomainPO oldDomainPO) {
+ return "UPDATE "
+ + DOMAIN_TABLE_NAME
+ + " SET domain_name = #{newDomainMeta.domainName},"
+ + " domain_comment = #{newDomainMeta.comment},"
+ + " domain_status = #{newDomainMeta.status},"
+ + " backing_tag_id = #{newDomainMeta.backingTagId},"
+ + " backing_tag_value = #{newDomainMeta.backingTagValue},"
+ + " properties = #{newDomainMeta.properties},"
+ + " audit_info = #{newDomainMeta.auditInfo},"
+ + " current_version = #{newDomainMeta.currentVersion},"
+ + " last_version = #{newDomainMeta.lastVersion},"
+ + " deleted_at = #{newDomainMeta.deletedAt}"
+ + " WHERE domain_id = #{oldDomainMeta.domainId}"
+ + " AND current_version = #{oldDomainMeta.currentVersion}"
+ + " AND deleted_at = 0";
+ }
+
+ /**
+ * Returns SQL that soft-deletes a domain using its ID and observed version.
+ *
+ * @param domainId The domain ID.
+ * @param currentVersion The version observed by the caller.
+ * @return The SQL.
+ */
+ public String softDeleteDomainMetaByIdAndVersion(
+ @Param("domainId") Long domainId, @Param("currentVersion") Long currentVersion) {
+ return "UPDATE "
+ + DOMAIN_TABLE_NAME
+ + " SET deleted_at = "
+ + DatabaseTimeSQL.MYSQL
+ + " WHERE domain_id = #{domainId} AND current_version = #{currentVersion}"
+ + " AND deleted_at = 0";
+ }
+
+ /**
+ * Returns SQL that soft-deletes all active domains of a metalake.
+ *
+ * @param metalakeId The metalake ID.
+ * @return The SQL.
+ */
+ public String softDeleteDomainMetasByMetalakeId(@Param("metalakeId") Long metalakeId) {
+ return "UPDATE "
+ + DOMAIN_TABLE_NAME
+ + " SET deleted_at = "
+ + DatabaseTimeSQL.MYSQL
+ + " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";
+ }
+
+ /**
+ * Returns SQL that hard-deletes domains soft-deleted before the given time.
+ *
+ * @param legacyTimeline The time before which soft-deleted rows are removed.
+ * @param limit The maximum number of rows to remove.
+ * @return The SQL.
+ */
+ public String deleteDomainMetasByLegacyTimeline(
+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {
+ return "DELETE FROM "
+ + DOMAIN_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/DomainMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/DomainMetaPostgreSQLProvider.java
new file mode 100644
index 0000000000..6aa2a0b6da
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/DomainMetaPostgreSQLProvider.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.mapper.provider.postgresql;
+
+import static org.apache.gravitino.storage.relational.mapper.DomainMetaMapper.DOMAIN_TABLE_NAME;
+
+import org.apache.gravitino.storage.relational.mapper.provider.DatabaseTimeSQL;
+import org.apache.gravitino.storage.relational.mapper.provider.base.DomainMetaBaseSQLProvider;
+import org.apache.ibatis.annotations.Param;
+
+/** The SQL of the {@code domain_meta} table for PostgreSQL. */
+public class DomainMetaPostgreSQLProvider extends DomainMetaBaseSQLProvider {
+
+ @Override
+ public String softDeleteDomainMetaByIdAndVersion(
+ @Param("domainId") Long domainId, @Param("currentVersion") Long currentVersion) {
+ return "UPDATE "
+ + DOMAIN_TABLE_NAME
+ + " SET deleted_at = "
+ + DatabaseTimeSQL.POSTGRESQL
+ + " WHERE domain_id = #{domainId} AND current_version = #{currentVersion}"
+ + " AND deleted_at = 0";
+ }
+
+ @Override
+ public String softDeleteDomainMetasByMetalakeId(@Param("metalakeId") Long metalakeId) {
+ return "UPDATE "
+ + DOMAIN_TABLE_NAME
+ + " SET deleted_at = "
+ + DatabaseTimeSQL.POSTGRESQL
+ + " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";
+ }
+
+ @Override
+ public String deleteDomainMetasByLegacyTimeline(
+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {
+ return "DELETE FROM "
+ + DOMAIN_TABLE_NAME
+ + " WHERE domain_id IN (SELECT domain_id FROM "
+ + DOMAIN_TABLE_NAME
+ + " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit})";
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/DomainPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/DomainPO.java
new file mode 100644
index 0000000000..6afb443ba6
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/DomainPO.java
@@ -0,0 +1,200 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.po;
+
+import static org.apache.gravitino.storage.relational.utils.POConverters.DEFAULT_DELETED_AT;
+import static org.apache.gravitino.storage.relational.utils.POConverters.INIT_VERSION;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.base.Preconditions;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import lombok.experimental.Accessors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.DomainEntity;
+
+/**
+ * The persistent object of a row in {@code domain_meta}. The backing tag name is not a column of
+ * the row: reads that join the live tag fill it, and it is null when the domain has no backing tag
+ * or the tag is deleted.
+ *
+ * <p>A tag bound without a value has a NULL {@code backing_tag_value}, while {@code
+ * tag_relation_meta.tag_value} stores the empty string for an assignment without a value. A lookup
+ * from tag assignments to the domains they back must map the empty string to NULL instead of
+ * comparing the two columns directly.
+ */
+@Getter
+@Accessors(fluent = true)
+@EqualsAndHashCode
+@ToString
+public class DomainPO {
+
+ private Long domainId;
+ private String domainName;
+ private Long metalakeId;
+ private String comment;
+ private String status;
+ private Long backingTagId;
+ private String backingTagName;
+ private String backingTagValue;
+ private String properties;
+ private String auditInfo;
+ private Long currentVersion;
+ private Long lastVersion;
+ private Long deletedAt;
+
+ /** Creates an empty domain persistent object, used by MyBatis to map result rows. */
+ public DomainPO() {}
+
+ @lombok.Builder(setterPrefix = "with")
+ private DomainPO(
+ Long domainId,
+ String domainName,
+ Long metalakeId,
+ String comment,
+ String status,
+ Long backingTagId,
+ String backingTagValue,
+ String properties,
+ String auditInfo,
+ Long currentVersion,
+ Long lastVersion,
+ Long deletedAt) {
+ Preconditions.checkArgument(domainId != null, "domainId cannot be null");
+ Preconditions.checkArgument(StringUtils.isNotBlank(domainName), "domainName cannot be blank");
+ Preconditions.checkArgument(metalakeId != null, "metalakeId cannot be null");
+ Preconditions.checkArgument(StringUtils.isNotBlank(status), "status cannot be blank");
+ Preconditions.checkArgument(
+ backingTagId != null || backingTagValue == null,
+ "backingTagValue cannot be set without backingTagId");
+ Preconditions.checkArgument(StringUtils.isNotBlank(auditInfo), "auditInfo cannot be blank");
+ Preconditions.checkArgument(currentVersion != null, "currentVersion cannot be null");
+ Preconditions.checkArgument(lastVersion != null, "lastVersion cannot be null");
+ Preconditions.checkArgument(deletedAt != null, "deletedAt cannot be null");
+
+ this.domainId = domainId;
+ this.domainName = domainName;
+ this.metalakeId = metalakeId;
+ this.comment = comment;
+ this.status = status;
+ this.backingTagId = backingTagId;
+ this.backingTagValue = backingTagValue;
+ this.properties = properties;
+ this.auditInfo = auditInfo;
+ this.currentVersion = currentVersion;
+ this.lastVersion = lastVersion;
+ this.deletedAt = deletedAt;
+ }
+
+ /**
+ * Creates the first version of the persistent object of a new domain.
+ *
+ * @param domainEntity The domain entity.
+ * @param metalakeId The ID of the metalake of the domain.
+ * @return The domain persistent object.
+ */
+ public static DomainPO initializeDomainPO(DomainEntity domainEntity, Long metalakeId) {
+ return toDomainPO(domainEntity, domainEntity.id(), metalakeId, INIT_VERSION);
+ }
+
+ /**
+ * Creates the next version of the persistent object of a domain from its updated entity.
+ *
+ * @param oldDomainPO The domain persistent object observed by the caller.
+ * @param newDomainEntity The updated domain entity.
+ * @return The domain persistent object with the next version.
+ */
+ public static DomainPO updateDomainPO(DomainPO oldDomainPO, DomainEntity newDomainEntity) {
+ Long nextVersion = oldDomainPO.currentVersion() + 1;
+ return toDomainPO(
+ newDomainEntity, oldDomainPO.domainId(), oldDomainPO.metalakeId(), nextVersion);
+ }
+
+ /**
+ * Converts a domain persistent object to a domain entity. The parent is not stored in the domain
+ * row, so it is not set. The backing tag name is set only when the read joined the live tag.
+ *
+ * @param domainPO The domain persistent object.
+ * @param namespace The namespace of the domain.
+ * @return The domain entity.
+ */
+ @SuppressWarnings("unchecked")
+ public static DomainEntity fromDomainPO(DomainPO domainPO, Namespace namespace) {
+ try {
+ return DomainEntity.builder()
+ .withId(domainPO.domainId())
+ .withName(domainPO.domainName())
+ .withNamespace(namespace)
+ .withComment(domainPO.comment())
+ .withStatus(Domain.Status.valueOf(domainPO.status()))
+ .withBackingTagId(domainPO.backingTagId())
+ .withBackingTagName(domainPO.backingTagName())
+ .withBackingTagValue(domainPO.backingTagValue())
+ .withProperties(JsonUtils.anyFieldMapper().readValue(domainPO.properties(), Map.class))
+ .withAuditInfo(
+ JsonUtils.anyFieldMapper().readValue(domainPO.auditInfo(), AuditInfo.class))
+ .build();
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException("Failed to deserialize domain PO", e);
+ }
+ }
+
+ /**
+ * Converts domain persistent objects to domain entities.
+ *
+ * @param domainPOs The domain persistent objects.
+ * @param namespace The namespace of the domains.
+ * @return The domain entities.
+ */
+ public static List<DomainEntity> fromDomainPOs(List<DomainPO> domainPOs, Namespace namespace) {
+ return domainPOs.stream().map(po -> fromDomainPO(po, namespace)).collect(Collectors.toList());
+ }
+
+ // Returns the built PO rather than the lombok builder: javadoc runs before lombok, so a
+ // signature that names the generated builder class fails the javadoc task.
+ private static DomainPO toDomainPO(
+ DomainEntity domainEntity, Long domainId, Long metalakeId, Long version) {
+ try {
+ return builder()
+ .withDomainId(domainId)
+ .withMetalakeId(metalakeId)
+ .withDomainName(domainEntity.name())
+ .withComment(domainEntity.comment())
+ .withStatus(domainEntity.status().name())
+ .withBackingTagId(domainEntity.backingTagId())
+ .withBackingTagValue(domainEntity.backingTagValue())
+ .withProperties(JsonUtils.anyFieldMapper().writeValueAsString(domainEntity.properties()))
+ .withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(domainEntity.auditInfo()))
+ .withCurrentVersion(version)
+ .withLastVersion(version)
+ .withDeletedAt(DEFAULT_DELETED_AT)
+ .build();
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException("Failed to serialize domain entity", e);
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/DomainMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/DomainMetaService.java
new file mode 100644
index 0000000000..ebee5d7bfd
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/DomainMetaService.java
@@ -0,0 +1,485 @@
+/*
+ * 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.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityAlreadyExistsException;
+import org.apache.gravitino.HasIdentifier;
+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.DomainEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.DomainMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
+import org.apache.gravitino.storage.relational.po.DomainPO;
+import org.apache.gravitino.storage.relational.po.MetalakePO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+
+/** The service that stores domains in the {@code domain_meta} table. */
+public class DomainMetaService {
+
+ private static final DomainMetaService INSTANCE = new DomainMetaService();
+
+ private DomainMetaService() {}
+
+ /**
+ * Returns the singleton service instance.
+ *
+ * @return The domain meta service.
+ */
+ public static DomainMetaService getInstance() {
+ return INSTANCE;
+ }
+
+ /**
+ * Lists the domains of a metalake.
+ *
+ * @param ns The domain namespace of the metalake.
+ * @return The domains of the metalake.
+ */
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "listDomainsByNamespace")
+ public List<DomainEntity> listDomainsByNamespace(Namespace ns) {
+ String metalakeName = ns.level(0);
+ List<DomainPO> domainPOs =
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class, mapper -> mapper.listDomainPOsByMetalake(metalakeName));
+ return DomainPO.fromDomainPOs(domainPOs, ns);
+ }
+
+ /**
+ * Gets a domain by its identifier.
+ *
+ * @param ident The domain identifier.
+ * @return The domain.
+ * @throws NoSuchEntityException If the domain does not exist.
+ */
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "getDomainByIdentifier")
+ public DomainEntity getDomainByIdentifier(NameIdentifier ident) {
+ String metalakeName = ident.namespace().level(0);
+ DomainPO domainPO = getDomainPOByMetalakeAndName(metalakeName, ident.name());
+ return DomainPO.fromDomainPO(domainPO, ident.namespace());
+ }
+
+ /**
+ * Gets the domains with the given identifiers. Identifiers of domains that do not exist are
+ * skipped.
+ *
+ * @param identifiers The domain identifiers, all in the same metalake.
+ * @return The domains that exist.
+ */
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "batchGetDomainByIdentifier")
+ public List<DomainEntity> batchGetDomainByIdentifier(List<NameIdentifier> identifiers) {
+ if (identifiers.isEmpty()) {
+ return Collections.emptyList();
+ }
+ NameIdentifier firstIdent = identifiers.get(0);
+ String metalakeName = firstIdent.namespace().level(0);
+ List<String> domainNames =
+ identifiers.stream().map(NameIdentifier::name).collect(Collectors.toList());
+
+ List<DomainPO> domainPOs =
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.listDomainPOsByMetalakeAndDomainNames(metalakeName, domainNames));
+ return DomainPO.fromDomainPOs(domainPOs, firstIdent.namespace());
+ }
+
+ /**
+ * Inserts a domain.
+ *
+ * @param domainEntity The domain to insert.
+ * @param overwritten Whether to replace an active domain with the same name or ID.
+ * @throws IOException If the domain cannot be stored.
+ * @throws EntityAlreadyExistsException If a domain with the same name exists and {@code
+ * overwritten} is false.
+ */
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "insertDomain")
+ public void insertDomain(DomainEntity domainEntity, boolean overwritten) throws IOException {
+ Namespace ns = domainEntity.namespace();
+ String metalakeName = ns.level(0);
+
+ try {
+ MetalakePO metalakePO =
+ SessionUtils.getWithoutCommit(
+ MetalakeMetaMapper.class, mapper -> mapper.selectMetalakeMetaByName(metalakeName));
+ if (metalakePO == null) {
+ throw new NoSuchEntityException(
+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+ Entity.EntityType.METALAKE.name().toLowerCase(),
+ metalakeName);
+ }
+
+ DomainPO domainPO = DomainPO.initializeDomainPO(domainEntity, metalakePO.getMetalakeId());
+
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ lockMetalakeForDomainWrite(metalakePO.getMetalakeName(), metalakePO.getMetalakeId()),
+ () -> insertDomainWithoutCommit(domainEntity, domainPO, overwritten));
+ } catch (RuntimeException e) {
+ try {
+ ExceptionUtils.checkSQLException(
+ e, Entity.EntityType.DOMAIN, domainEntity.nameIdentifier().toString());
+ } catch (EntityAlreadyExistsException duplicate) {
+ if (overwritten) {
+ // A missing-row locking read does not fence a concurrent insert at READ_COMMITTED.
+ // Propagate the conflict so the whole transaction is rolled back before retrying.
+ throw ExceptionUtils.concurrentModification(
+ Entity.EntityType.DOMAIN, domainEntity.nameIdentifier());
+ }
+ throw duplicate;
+ }
+ throw e;
+ }
+ }
+
+ /**
+ * Updates a domain. The domain row is locked before the updater runs, so the updater is given the
+ * current domain and concurrent alters apply one after another instead of failing on each other.
+ * The write still compares the locked version as a backstop.
+ *
+ * <p>The updater runs inside this transaction, after the metalake is locked in shared mode and
+ * while the domain row is locked. Any lock the updater takes, such as on the backing tag, must
+ * follow the order metalake, then domains, then tags.
+ *
+ * <p>The name is resolved before the row is locked. If the domain is dropped and a new one is
+ * created with the same name in between, this call reports the domain as missing instead of
+ * changing the new domain; a later call with the name acts on the new domain.
+ *
+ * <p>The returned domain is read back in the same transaction, so its backing tag name comes from
+ * the tag it is now bound to rather than from the updater's entity.
+ *
+ * @param identifier The domain identifier.
+ * @param updater The function that returns the updated domain.
+ * @param <E> The entity type.
+ * @return The updated domain, as stored.
+ * @throws IOException If the domain cannot be stored.
+ * @throws NoSuchEntityException If the domain does not exist.
+ * @throws EntityAlreadyExistsException If the domain is renamed to a name that is in use.
+ */
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "updateDomain")
+ public <E extends Entity & HasIdentifier> DomainEntity updateDomain(
+ NameIdentifier identifier, Function<E, E> updater) throws IOException {
+ String metalakeName = identifier.namespace().level(0);
+
+ try {
+ DomainPO observedDomainPO = getDomainPOByMetalakeAndName(metalakeName, identifier.name());
+ DomainPO[] storedDomainPO = new DomainPO[1];
+ SessionUtils.doWithCommit(
+ DomainMetaMapper.class,
+ mapper -> {
+ // The metalake fence comes before the domain row, as in every domain write: the
+ // updater may lock tag rows, and dropping the metalake locks tags before domains.
+ lockMetalakeForDomainWrite(metalakeName, observedDomainPO.metalakeId());
+ lockAndGetDomainPO(identifier, observedDomainPO);
+ // The locking read cannot join the tag table, so the locked row is read again with the
+ // name of its backing tag.
+ DomainPO lockedDomainPO = mapper.selectDomainMetaById(observedDomainPO.domainId());
+ DomainEntity oldDomainEntity =
+ DomainPO.fromDomainPO(lockedDomainPO, identifier.namespace());
+ DomainEntity updatedDomainEntity = (DomainEntity) updater.apply((E) oldDomainEntity);
+ Preconditions.checkArgument(
+ Objects.equals(oldDomainEntity.id(), updatedDomainEntity.id()),
+ "The updated domain entity id: %s must have the same id as the old entity id %s",
+ updatedDomainEntity.id(),
+ oldDomainEntity.id());
+
+ DomainPO newDomainPO = DomainPO.updateDomainPO(lockedDomainPO, updatedDomainEntity);
+ updateDomainWithVersion(identifier, mapper, lockedDomainPO, newDomainPO);
+ storedDomainPO[0] = mapper.selectDomainMetaById(lockedDomainPO.domainId());
+ });
+
+ return DomainPO.fromDomainPO(storedDomainPO[0], identifier.namespace());
+ } catch (RuntimeException e) {
+ ExceptionUtils.checkSQLException(e, Entity.EntityType.DOMAIN, identifier.toString());
+ throw e;
+ }
+ }
+
+ /**
+ * Deletes a domain, together with its owner and the privileges granted on it. The backing tag and
+ * its assignments are kept.
+ *
+ * @param identifier The domain identifier.
+ * @return True if the domain is deleted, false if it does not exist.
+ */
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "deleteDomain")
+ public boolean deleteDomain(NameIdentifier identifier) {
+ DomainPO domainPO;
+ try {
+ domainPO = getDomainPOByMetalakeAndName(identifier.namespace().level(0), identifier.name());
+ } catch (NoSuchEntityException e) {
+ return false;
+ }
+ return deleteDomain(identifier, domainPO);
+ }
+
+ /**
+ * Hard-deletes the domains soft-deleted before the given time.
+ *
+ * @param legacyTimeline The time before which soft-deleted domains are removed.
+ * @param limit The maximum number of domains to remove.
+ * @return The number of removed domains.
+ */
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "deleteDomainMetasByLegacyTimeline")
+ public int deleteDomainMetasByLegacyTimeline(long legacyTimeline, int limit) {
+ return SessionUtils.doWithCommitAndFetchResult(
+ DomainMetaMapper.class,
+ mapper -> mapper.deleteDomainMetasByLegacyTimeline(legacyTimeline, limit));
+ }
+
+ /**
+ * Gets the ID of a domain.
+ *
+ * @param metalakeId The metalake ID.
+ * @param domainName The domain name.
+ * @return The domain ID.
+ * @throws NoSuchEntityException If the domain does not exist.
+ */
+ public Long getDomainIdByMetalakeIdAndName(Long metalakeId, String domainName) {
+ DomainPO domainPO =
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.selectDomainMetaByMetalakeIdAndName(metalakeId, domainName));
+
+ if (domainPO == null) {
+ throw new NoSuchEntityException(
+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+ Entity.EntityType.DOMAIN.name().toLowerCase(),
+ domainName);
+ }
+ return domainPO.domainId();
+ }
+
+ /**
+ * Deletes the domain the caller observed. The domain row is locked first, so a domain that was
+ * only altered since it was read is still deleted, and the dependent rows are cleaned up in the
+ * same transaction as the domain row itself. If another transaction deletes or renames the
+ * observed domain first, this method returns {@code false}, also when a new domain has taken the
+ * name meanwhile.
+ *
+ * <p>The observed row is a parameter so that a test can hand in a stale one; production callers
+ * use {@link #deleteDomain(NameIdentifier)}, which reads it first.
+ */
+ @VisibleForTesting
+ boolean deleteDomain(NameIdentifier identifier, DomainPO domainPO) {
+ long domainId = domainPO.domainId();
+
+ // The metalake lock comes first. Dropping the metalake soft-deletes the privileges before the
+ // domains, while this delete changes the domain row before its privileges; without the lock
+ // the two could deadlock on a domain with privileges. The domain row is locked next, and a row
+ // that is gone or renamed makes the delete report the domain as missing before any dependent
+ // row is touched. The version-checked delete keeps the version as a backstop. The cleanups that
+ // follow are blanket soft deletes for this domain ID, so their row counts carry no information
+ // and are not checked.
+ try {
+ SessionUtils.doMultipleWithCommit(
+ () -> lockMetalakeForDomainWrite(identifier.namespace().level(0), domainPO.metalakeId()),
+ () -> deleteDomainWithVersion(identifier, lockAndGetDomainPO(identifier, domainPO)),
+ () ->
+ SessionUtils.doWithoutCommit(
+ OwnerMetaMapper.class,
+ mapper ->
+ mapper.softDeleteOwnerRelByMetadataObjectIdAndType(
+ domainId, MetadataObject.Type.DOMAIN.name())),
+ () ->
+ SessionUtils.doWithoutCommit(
+ SecurableObjectMapper.class,
+ mapper ->
+ mapper.softDeleteObjectRelsByMetadataObject(
+ domainId, MetadataObject.Type.DOMAIN.name())));
+ } catch (NoSuchEntityException e) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Holds the parent metalake row for the rest of the transaction, so a domain cannot be created,
+ * altered or deleted while the metalake is being dropped. The lock is shared, so domains under
+ * the same metalake can be written at the same time, while dropping the metalake takes an
+ * exclusive lock on the row. A metalake that is gone or renamed is reported as missing.
+ */
+ private void lockMetalakeForDomainWrite(String metalakeName, Long metalakeId) {
+ OccWriteSupport.lockParentForChildWrite(
+ metalakeName,
+ Entity.EntityType.METALAKE,
+ () ->
+ SessionUtils.getWithoutCommit(
+ MetalakeMetaMapper.class,
+ mapper -> mapper.selectMetalakeMetaByIdForShare(metalakeId)),
+ null,
+ current -> Objects.equals(current.getMetalakeName(), metalakeName));
+ }
+
+ /**
+ * Writes a new domain or replaces the active domain selected by name or stable ID. The overwrite
+ * path uses locking reads instead of a database-specific upsert, which keeps the stored domain ID
+ * and version stable across all databases.
+ */
+ private void insertDomainWithoutCommit(
+ DomainEntity domainEntity, DomainPO initializedDomainPO, boolean overwritten) {
+ if (!overwritten) {
+ insertNewDomainWithoutCommit(initializedDomainPO);
+ return;
+ }
+
+ DomainPO existingDomainPO = findAndLockDomainForOverwrite(initializedDomainPO);
+ if (existingDomainPO == null) {
+ if (SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.countDeletedDomainMetasById(initializedDomainPO.domainId()))
+ > 0) {
+ throw new EntityAlreadyExistsException(
+ "The domain ID %s is reserved by a deleted domain; use a new ID",
+ initializedDomainPO.domainId());
+ }
+ insertNewDomainWithoutCommit(initializedDomainPO);
+ return;
+ }
+
+ DomainPO replacementDomainPO = DomainPO.updateDomainPO(existingDomainPO, domainEntity);
+ NameIdentifier observedIdentifier =
+ NameIdentifier.of(domainEntity.namespace(), existingDomainPO.domainName());
+ SessionUtils.doWithoutCommit(
+ DomainMetaMapper.class,
+ mapper ->
+ updateDomainWithVersion(
+ observedIdentifier, mapper, existingDomainPO, replacementDomainPO));
+ }
+
+ private void insertNewDomainWithoutCommit(DomainPO domainPO) {
+ SessionUtils.doWithoutCommit(
+ DomainMetaMapper.class, mapper -> mapper.insertDomainMeta(domainPO));
+ }
+
+ private DomainPO findAndLockDomainForOverwrite(DomainPO initializedDomainPO) {
+ return OccWriteSupport.findAndLockForOverwrite(
+ () ->
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper ->
+ mapper.selectDomainMetaByMetalakeIdAndNameForUpdate(
+ initializedDomainPO.metalakeId(), initializedDomainPO.domainName())),
+ () ->
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.selectDomainMetaByIdForUpdate(initializedDomainPO.domainId())),
+ current -> Objects.equals(current.metalakeId(), initializedDomainPO.metalakeId()));
+ }
+
+ /**
+ * Locks the row of the domain the caller observed and returns it. The row is the same domain only
+ * if it still has the observed name and metalake; otherwise the domain is reported as missing.
+ * The returned row does not carry the backing tag name.
+ */
+ private DomainPO lockAndGetDomainPO(NameIdentifier identifier, DomainPO observedDomainPO) {
+ return OccWriteSupport.lockParentForChildWrite(
+ identifier.name(),
+ Entity.EntityType.DOMAIN,
+ () ->
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.selectDomainMetaByIdForUpdate(observedDomainPO.domainId())),
+ null,
+ current ->
+ Objects.equals(current.domainName(), observedDomainPO.domainName())
+ && Objects.equals(current.metalakeId(), observedDomainPO.metalakeId()));
+ }
+
+ private void updateDomainWithVersion(
+ NameIdentifier identifier,
+ DomainMetaMapper mapper,
+ DomainPO oldDomainPO,
+ DomainPO newDomainPO) {
+ OccWriteSupport.updateWithVersion(
+ () -> mapper.updateDomainMeta(newDomainPO, oldDomainPO),
+ () -> domainWriteFailure(identifier, oldDomainPO));
+ }
+
+ private void deleteDomainWithVersion(NameIdentifier identifier, DomainPO observedDomainPO) {
+ OccWriteSupport.deleteWithVersion(
+ () ->
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper ->
+ mapper.softDeleteDomainMetaByIdAndVersion(
+ observedDomainPO.domainId(), observedDomainPO.currentVersion())),
+ () -> domainWriteFailure(identifier, observedDomainPO));
+ }
+
+ private RuntimeException domainWriteFailure(
+ NameIdentifier identifier, DomainPO observedDomainPO) {
+ return OccWriteSupport.writeFailure(
+ identifier,
+ Entity.EntityType.DOMAIN,
+ () ->
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.selectDomainMetaByIdForUpdate(observedDomainPO.domainId())),
+ null,
+ current ->
+ Objects.equals(current.domainName(), observedDomainPO.domainName())
+ && Objects.equals(current.metalakeId(), observedDomainPO.metalakeId()));
+ }
+
+ private DomainPO getDomainPOByMetalakeAndName(String metalakeName, String domainName) {
+ DomainPO domainPO =
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.selectDomainMetaByMetalakeAndName(metalakeName, domainName));
+
+ if (domainPO == null) {
+ throw new NoSuchEntityException(
+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+ Entity.EntityType.DOMAIN.name().toLowerCase(),
+ domainName);
+ }
+ return domainPO;
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/MetadataObjectService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/MetadataObjectService.java
index 9bd2c2c89f..55e3dc20ad 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/MetadataObjectService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/MetadataObjectService.java
@@ -36,6 +36,7 @@ import org.apache.gravitino.job.JobHandle;
import org.apache.gravitino.meta.GenericEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.DomainMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.JobTemplateMetaMapper;
@@ -51,6 +52,7 @@ import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
import org.apache.gravitino.storage.relational.po.CatalogPO;
import org.apache.gravitino.storage.relational.po.ColumnPO;
+import org.apache.gravitino.storage.relational.po.DomainPO;
import org.apache.gravitino.storage.relational.po.FilesetPO;
import org.apache.gravitino.storage.relational.po.FunctionPO;
import org.apache.gravitino.storage.relational.po.JobTemplatePO;
@@ -99,6 +101,7 @@ public class MetadataObjectService {
.put(
MetadataObject.Type.JOB_TEMPLATE,
MetadataObjectService::getJobTemplateObjectsFullName)
+ .put(MetadataObject.Type.DOMAIN, MetadataObjectService::getDomainObjectsFullName)
.build();
static final Map<MetadataObject.Type, BasePOStorageOps<?, ?>> TYPE_TO_STORAGE_OPS_MAP =
@@ -183,6 +186,23 @@ public class MetadataObjectService {
return tagIdAndNameMap;
}
+ private static Map<Long, String> getDomainObjectsFullName(List<Long> domainIds) {
+ if (domainIds == null || domainIds.isEmpty()) {
+ return Maps.newHashMap();
+ }
+
+ List<DomainPO> domainPOs =
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class, mapper -> mapper.listDomainPOsByDomainIds(domainIds));
+
+ HashMap<Long, String> domainIdAndNameMap = new HashMap<>();
+ if (domainPOs != null) {
+ domainPOs.forEach(
+ domainPO -> domainIdAndNameMap.put(domainPO.domainId(), domainPO.domainName()));
+ }
+ return domainIdAndNameMap;
+ }
+
private MetadataObjectService() {}
@Monitored(
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java
index beeba0556f..f7f97e93b9 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/MetalakeMetaService.java
@@ -35,6 +35,7 @@ import org.apache.gravitino.exceptions.NonEmptyEntityException;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.DomainMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
@@ -283,6 +284,10 @@ public class MetalakeMetaService {
SessionUtils.doWithoutCommit(
RoleMetaMapper.class,
mapper -> mapper.softDeleteRoleMetasByMetalakeId(metalakeId)),
+ () ->
+ SessionUtils.doWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.softDeleteDomainMetasByMetalakeId(metalakeId)),
() ->
SessionUtils.doWithoutCommit(
TagMetadataObjectRelMapper.class,
@@ -399,6 +404,10 @@ public class MetalakeMetaService {
SessionUtils.doWithoutCommit(
RoleMetaMapper.class,
mapper -> mapper.softDeleteRoleMetasByMetalakeId(metalakeId)),
+ () ->
+ SessionUtils.doWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.softDeleteDomainMetasByMetalakeId(metalakeId)),
() ->
SessionUtils.doWithoutCommit(
TagMetadataObjectRelMapper.class,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/OrphanedMetadataObjectRelationService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/OrphanedMetadataObjectRelationService.java
index 8910bce4e8..5dc98de4e9 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/OrphanedMetadataObjectRelationService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/OrphanedMetadataObjectRelationService.java
@@ -23,6 +23,7 @@ import com.google.common.collect.ImmutableMap;
import java.util.Map;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.DomainMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
import org.apache.gravitino.storage.relational.mapper.JobMetaMapper;
@@ -81,6 +82,9 @@ public class OrphanedMetadataObjectRelationService {
.put(
MetadataObject.Type.FUNCTION,
new EntityTable(FunctionMetaMapper.TABLE_NAME, "function_id"))
+ .put(
+ MetadataObject.Type.DOMAIN,
+ new EntityTable(DomainMetaMapper.DOMAIN_TABLE_NAME, "domain_id"))
.build();
private OrphanedMetadataObjectRelationService() {}
diff --git a/core/src/main/java/org/apache/gravitino/utils/EntityClassMapper.java b/core/src/main/java/org/apache/gravitino/utils/EntityClassMapper.java
index c2ac21e80f..d627446981 100644
--- a/core/src/main/java/org/apache/gravitino/utils/EntityClassMapper.java
+++ b/core/src/main/java/org/apache/gravitino/utils/EntityClassMapper.java
@@ -26,6 +26,7 @@ import org.apache.gravitino.HasIdentifier;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
import org.apache.gravitino.meta.ColumnEntity;
+import org.apache.gravitino.meta.DomainEntity;
import org.apache.gravitino.meta.FilesetEntity;
import org.apache.gravitino.meta.FunctionEntity;
import org.apache.gravitino.meta.GroupEntity;
@@ -68,6 +69,7 @@ public class EntityClassMapper {
.put(Entity.EntityType.ROLE, RoleEntity.class)
.put(Entity.EntityType.POLICY, PolicyEntity.class)
.put(Entity.EntityType.JOB_TEMPLATE, JobTemplateEntity.class)
+ .put(Entity.EntityType.DOMAIN, DomainEntity.class)
.put(Entity.EntityType.JOB, JobEntity.class)
.put(Entity.EntityType.SEMANTIC_MODEL, SemanticModelEntity.class)
.build();
diff --git a/core/src/main/java/org/apache/gravitino/utils/MetadataObjectUtil.java b/core/src/main/java/org/apache/gravitino/utils/MetadataObjectUtil.java
index 30566a0a98..7b02380b57 100644
--- a/core/src/main/java/org/apache/gravitino/utils/MetadataObjectUtil.java
+++ b/core/src/main/java/org/apache/gravitino/utils/MetadataObjectUtil.java
@@ -67,6 +67,7 @@ public class MetadataObjectUtil {
.put(MetadataObject.Type.VIEW, Entity.EntityType.VIEW)
.put(MetadataObject.Type.SEMANTIC_MODEL, Entity.EntityType.SEMANTIC_MODEL)
.put(MetadataObject.Type.FUNCTION, Entity.EntityType.FUNCTION)
+ .put(MetadataObject.Type.DOMAIN, Entity.EntityType.DOMAIN)
.build();
private MetadataObjectUtil() {}
@@ -138,6 +139,8 @@ public class MetadataObjectUtil {
return NameIdentifierUtil.ofJob(metalakeName, metadataObject.name());
case JOB_TEMPLATE:
return NameIdentifierUtil.ofJobTemplate(metalakeName, metadataObject.name());
+ case DOMAIN:
+ return NameIdentifierUtil.ofDomain(metalakeName, metadataObject.name());
case VIEW:
case SEMANTIC_MODEL:
case CATALOG:
diff --git a/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java b/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java
index a8dd00bd95..8546ed2051 100644
--- a/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java
+++ b/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.utils;
+import static org.apache.gravitino.Entity.EntityType.DOMAIN;
import static org.apache.gravitino.Entity.EntityType.GROUP;
import static org.apache.gravitino.Entity.EntityType.JOB;
import static org.apache.gravitino.Entity.EntityType.JOB_TEMPLATE;
@@ -57,7 +58,7 @@ public class NameIdentifierUtil {
private NameIdentifierUtil() {}
private static final Set<Entity.EntityType> SUPPORT_VIRTUAL_NAMESPACE_TYPES =
- ImmutableSet.of(USER, GROUP, ROLE, TAG, POLICY, JOB, JOB_TEMPLATE);
+ ImmutableSet.of(USER, GROUP, ROLE, TAG, POLICY, JOB, JOB_TEMPLATE, DOMAIN);
/**
* Create the metalake {@link NameIdentifierUtil} with the given name.
@@ -349,6 +350,17 @@ public class NameIdentifierUtil {
return NameIdentifier.of(NamespaceUtil.ofJobTemplate(metalake), jobTemplateName);
}
+ /**
+ * Create the domain {@link NameIdentifier} with the given metalake and domain name.
+ *
+ * @param metalake The metalake name
+ * @param domainName The domain name
+ * @return The created domain {@link NameIdentifier}
+ */
+ public static NameIdentifier ofDomain(String metalake, String domainName) {
+ return NameIdentifier.of(NamespaceUtil.ofDomain(metalake), domainName);
+ }
+
/**
* Create the job {@link NameIdentifier} with the given metalake and job name.
*
@@ -618,6 +630,17 @@ public class NameIdentifierUtil {
NamespaceUtil.checkJobTemplate(ident.namespace());
}
+ /**
+ * Check the given {@link NameIdentifier} is a domain identifier. Throw an {@link
+ * IllegalNameIdentifierException} if it's not.
+ *
+ * @param ident The domain {@link NameIdentifier} to check.
+ */
+ public static void checkDomain(NameIdentifier ident) {
+ NameIdentifier.check(ident != null, "Domain identifier must not be null");
+ NamespaceUtil.checkDomain(ident.namespace());
+ }
+
/**
* Check whether the metadata object name can be represented in a qualified metadata object name.
*
@@ -732,6 +755,10 @@ public class NameIdentifierUtil {
checkJobTemplate(ident);
return MetadataObjects.of(null, ident.name(), MetadataObject.Type.JOB_TEMPLATE);
+ case DOMAIN:
+ checkDomain(ident);
+ return MetadataObjects.of(null, ident.name(), MetadataObject.Type.DOMAIN);
+
default:
throw new IllegalArgumentException(
"Entity type " + entityType + " is not supported to convert to MetadataObject");
@@ -998,6 +1025,7 @@ public class NameIdentifierUtil {
case POLICY:
case JOB:
case JOB_TEMPLATE:
+ case DOMAIN:
return Entity.EntityType.METALAKE;
case METALAKE:
@@ -1044,6 +1072,8 @@ public class NameIdentifierUtil {
return NamespaceUtil.ofJob(metalake);
case JOB_TEMPLATE:
return NamespaceUtil.ofJobTemplate(metalake);
+ case DOMAIN:
+ return NamespaceUtil.ofDomain(metalake);
default:
throw new IllegalArgumentException("Unsupported virtual namespace type: " + type);
}
diff --git a/core/src/main/java/org/apache/gravitino/utils/NamespaceUtil.java b/core/src/main/java/org/apache/gravitino/utils/NamespaceUtil.java
index bd98e2bfcf..cf0ae0fdc0 100644
--- a/core/src/main/java/org/apache/gravitino/utils/NamespaceUtil.java
+++ b/core/src/main/java/org/apache/gravitino/utils/NamespaceUtil.java
@@ -232,6 +232,16 @@ public class NamespaceUtil {
metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.JOB_TEMPLATE_SCHEMA_NAME);
}
+ /**
+ * Create a namespace for domain.
+ *
+ * @param metalake The metalake name
+ * @return A namespace for domain
+ */
+ public static Namespace ofDomain(String metalake) {
+ return Namespace.of(metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.DOMAIN_SCHEMA_NAME);
+ }
+
/**
* Create a namespace for job.
*
@@ -424,6 +434,19 @@ public class NamespaceUtil {
namespace);
}
+ /**
+ * Check if the given domain namespace is legal, throw an {@link IllegalNamespaceException} if
+ * it's illegal.
+ *
+ * @param namespace The domain namespace
+ */
+ public static void checkDomain(Namespace namespace) {
+ check(
+ namespace != null && namespace.length() == 3,
+ "Domain namespace must be non-null and have 3 levels, the input namespace is %s",
+ namespace);
+ }
+
/**
* Check if the given job namespace is legal, throw an {@link IllegalNamespaceException}
*
diff --git a/core/src/test/java/org/apache/gravitino/meta/TestDomainEntity.java b/core/src/test/java/org/apache/gravitino/meta/TestDomainEntity.java
new file mode 100644
index 0000000000..2072e30a1c
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/meta/TestDomainEntity.java
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.meta;
+
+import com.google.common.collect.ImmutableMap;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityFieldLimits;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.tag.TagValue;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestDomainEntity {
+
+ @Test
+ public void testDomainEntity() {
+ DomainEntity domain =
+ DomainEntity.builder()
+ .withId(1L)
+ .withName("Finance/Trading")
+ .withNamespace(NamespaceUtil.ofDomain("metalake"))
+ .withComment("comment")
+ .withProperties(ImmutableMap.of("k", "v"))
+ .withStatus(Domain.Status.DRAFT)
+ .withParent("Finance")
+ .withBackingTagId(100L)
+ .withBackingTagName("dept")
+ .withBackingTagValue("trading")
+ .withAuditInfo(AuditInfo.EMPTY)
+ .build();
+
+ Assertions.assertEquals(Entity.EntityType.DOMAIN, domain.type());
+ Assertions.assertEquals(1L, domain.id());
+ Assertions.assertEquals("Finance/Trading", domain.name());
+ Assertions.assertEquals("comment", domain.comment());
+ Assertions.assertEquals(ImmutableMap.of("k", "v"), domain.properties());
+ Assertions.assertEquals(Domain.Status.DRAFT, domain.status());
+ Assertions.assertEquals("Finance", domain.parent().orElse(null));
+ Assertions.assertEquals(TagValue.of("dept", "trading"), domain.backingTag().orElse(null));
+ Assertions.assertEquals(100L, domain.backingTagId());
+ Assertions.assertEquals("trading", domain.backingTagValue());
+ Assertions.assertEquals(AuditInfo.EMPTY, domain.auditInfo());
+
+ // The parent and the backing tag name are not stored with the domain.
+ Assertions.assertEquals(
+ ImmutableMap.builder()
+ .put(DomainEntity.ID, 1L)
+ .put(DomainEntity.NAME, "Finance/Trading")
+ .put(DomainEntity.COMMENT, "comment")
+ .put(DomainEntity.PROPERTIES, ImmutableMap.of("k", "v"))
+ .put(DomainEntity.STATUS, Domain.Status.DRAFT)
+ .put(DomainEntity.BACKING_TAG_ID, 100L)
+ .put(DomainEntity.BACKING_TAG_VALUE, "trading")
+ .put(DomainEntity.AUDIT_INFO, AuditInfo.EMPTY)
+ .build(),
+ domain.fields());
+ }
+
+ @Test
+ public void testDomainEntityBackingTag() {
+ DomainEntity domain = newDomain();
+ Assertions.assertFalse(domain.backingTag().isPresent());
+ Assertions.assertNull(domain.backingTagId());
+
+ DomainEntity valueless =
+ domain.toBuilder().withBackingTagId(100L).withBackingTagName("Finance").build();
+ Assertions.assertEquals(TagValue.noValue("Finance"), valueless.backingTag().orElse(null));
+ Assertions.assertNull(valueless.backingTagValue());
+
+ // A deleted tag keeps its ID on the domain but has no name, so there is no backing tag.
+ DomainEntity deletedTag =
+ domain.toBuilder().withBackingTagId(100L).withBackingTagValue("trading").build();
+ Assertions.assertFalse(deletedTag.backingTag().isPresent());
+ Assertions.assertEquals(100L, deletedTag.backingTagId());
+ Assertions.assertEquals("trading", deletedTag.backingTagValue());
+
+ // Clearing the tag ID unbinds the tag, without clearing the name read from the tag.
+ DomainEntity unbound = valueless.toBuilder().withBackingTagId(null).build();
+ Assertions.assertFalse(unbound.backingTag().isPresent());
+ Assertions.assertEquals(domain, unbound);
+ Assertions.assertFalse(
+ domain.toBuilder().withBackingTagName("Finance").build().backingTag().isPresent());
+
+ // A tag value needs the tag ID.
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> domain.toBuilder().withBackingTagValue("trading").build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domain.toBuilder()
+ .withBackingTagId(100L)
+ .withBackingTagValue(
+ StringUtils.repeat("a", EntityFieldLimits.MAX_TAG_VALUE_LENGTH + 1))
+ .build());
+
+ // A tag bound without a value is stored as NULL, never as a blank value.
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> domain.toBuilder().withBackingTagId(100L).withBackingTagValue("").build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> domain.toBuilder().withBackingTagId(100L).withBackingTagValue(" ").build());
+ }
+
+ @Test
+ public void testDomainEntityValidation() {
+ Assertions.assertDoesNotThrow(() -> newDomain().toBuilder().withComment(null).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> newDomain().toBuilder().withId(null).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> newDomain().toBuilder().withName(null).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> newDomain().toBuilder().withStatus(null).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> newDomain().toBuilder().withAuditInfo(null).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ newDomain().toBuilder()
+ .withName(StringUtils.repeat("a", EntityFieldLimits.MAX_NAME_LENGTH + 1))
+ .build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ newDomain().toBuilder()
+ .withComment(StringUtils.repeat("a", EntityFieldLimits.MAX_COMMENT_LENGTH + 1))
+ .build());
+ }
+
+ @Test
+ public void testDomainEntityCopyAndEquality() {
+ DomainEntity domain = newDomain();
+ DomainEntity copy = domain.toBuilder().build();
+ Assertions.assertEquals(domain, copy);
+ Assertions.assertEquals(domain.hashCode(), copy.hashCode());
+
+ Assertions.assertNotEquals(
+ domain, domain.toBuilder().withStatus(Domain.Status.PUBLISHED).build());
+ Assertions.assertNotEquals(domain, domain.toBuilder().withParent("Markets").build());
+ Assertions.assertNotEquals(domain, domain.toBuilder().withBackingTagId(100L).build());
+ }
+
+ private DomainEntity newDomain() {
+ return DomainEntity.builder()
+ .withId(1L)
+ .withName("Trading")
+ .withNamespace(NamespaceUtil.ofDomain("metalake"))
+ .withStatus(Domain.Status.DRAFT)
+ .withParent("Finance")
+ .withAuditInfo(AuditInfo.EMPTY)
+ .build();
+ }
+}
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.java
index bce9a024e3..43e46a6e37 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
@@ -218,6 +218,10 @@ public abstract class TestJDBCBackend {
tableName = "semantic_model_meta";
idColumnName = "semantic_model_id";
break;
+ case DOMAIN:
+ tableName = "domain_meta";
+ idColumnName = "domain_id";
+ break;
default:
throw new IllegalArgumentException("Unsupported entity type: " + entityType);
}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/po/TestDomainPO.java b/core/src/test/java/org/apache/gravitino/storage/relational/po/TestDomainPO.java
new file mode 100644
index 0000000000..b110212735
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/po/TestDomainPO.java
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.po;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.time.Instant;
+import java.util.List;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.DomainEntity;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestDomainPO {
+
+ private static final Namespace NAMESPACE = NamespaceUtil.ofDomain("metalake");
+
+ private static final AuditInfo AUDIT_INFO =
+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();
+
+ @Test
+ public void testInitializeAndConvertDomainPO() {
+ DomainEntity domain = newDomain(10L, "Finance/Trading", "comment", ImmutableMap.of("k", "v"));
+
+ DomainPO domainPO = DomainPO.initializeDomainPO(domain, 1L);
+ Assertions.assertEquals(10L, domainPO.domainId());
+ Assertions.assertEquals("Finance/Trading", domainPO.domainName());
+ Assertions.assertEquals(1L, domainPO.metalakeId());
+ Assertions.assertEquals("comment", domainPO.comment());
+ Assertions.assertEquals("DRAFT", domainPO.status());
+ Assertions.assertEquals(1L, domainPO.currentVersion());
+ Assertions.assertEquals(1L, domainPO.lastVersion());
+ Assertions.assertEquals(0L, domainPO.deletedAt());
+
+ Assertions.assertEquals(domain, DomainPO.fromDomainPO(domainPO, NAMESPACE));
+ }
+
+ @Test
+ public void testConvertDomainWithoutCommentAndProperties() {
+ DomainEntity domain = newDomain(10L, "Finance", null, null);
+
+ DomainEntity converted =
+ DomainPO.fromDomainPO(DomainPO.initializeDomainPO(domain, 1L), NAMESPACE);
+ Assertions.assertNull(converted.comment());
+ Assertions.assertNull(converted.properties());
+ Assertions.assertEquals(domain, converted);
+ }
+
+ @Test
+ public void testConvertedDomainCarriesNoDerivedFields() {
+ DomainEntity domain =
+ newDomain(10L, "Trading", null, null).toBuilder()
+ .withParent("Finance")
+ .withBackingTagId(100L)
+ .withBackingTagName("Finance/Trading")
+ .withBackingTagValue("trading")
+ .build();
+
+ DomainEntity converted =
+ DomainPO.fromDomainPO(DomainPO.initializeDomainPO(domain, 1L), NAMESPACE);
+ Assertions.assertFalse(converted.parent().isPresent());
+ // The binding is stored by tag ID; the tag name comes from a join with the live tag.
+ Assertions.assertFalse(converted.backingTag().isPresent());
+ Assertions.assertEquals(100L, converted.backingTagId());
+ Assertions.assertEquals("trading", converted.backingTagValue());
+ Assertions.assertEquals(
+ domain.toBuilder().withParent(null).withBackingTagName(null).build(), converted);
+ }
+
+ @Test
+ public void testUpdateDomainPO() {
+ DomainPO oldDomainPO =
+ DomainPO.initializeDomainPO(newDomain(10L, "Finance", "comment", null), 1L);
+
+ DomainEntity updated =
+ newDomain(10L, "Finance/Tax", "new comment", ImmutableMap.of("k", "v")).toBuilder()
+ .withStatus(Domain.Status.PUBLISHED)
+ .build();
+ DomainPO newDomainPO = DomainPO.updateDomainPO(oldDomainPO, updated);
+
+ Assertions.assertEquals(10L, newDomainPO.domainId());
+ Assertions.assertEquals(1L, newDomainPO.metalakeId());
+ Assertions.assertEquals("Finance/Tax", newDomainPO.domainName());
+ Assertions.assertEquals("new comment", newDomainPO.comment());
+ Assertions.assertEquals("PUBLISHED", newDomainPO.status());
+ Assertions.assertEquals(2L, newDomainPO.currentVersion());
+ Assertions.assertEquals(2L, newDomainPO.lastVersion());
+ Assertions.assertEquals(0L, newDomainPO.deletedAt());
+ Assertions.assertEquals(updated, DomainPO.fromDomainPO(newDomainPO, NAMESPACE));
+ }
+
+ @Test
+ public void testFromDomainPOs() {
+ DomainEntity finance = newDomain(10L, "Finance", null, null);
+ DomainEntity markets = newDomain(11L, "Markets", null, null);
+ List<DomainPO> domainPOs =
+ Lists.newArrayList(
+ DomainPO.initializeDomainPO(finance, 1L), DomainPO.initializeDomainPO(markets, 1L));
+
+ Assertions.assertEquals(
+ Lists.newArrayList(finance, markets), DomainPO.fromDomainPOs(domainPOs, NAMESPACE));
+ }
+
+ @Test
+ public void testDomainPOBuilderValidation() {
+ Assertions.assertDoesNotThrow(() -> validBuilder().build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> validBuilder().withDomainId(null).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> validBuilder().withDomainName(" ").build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> validBuilder().withMetalakeId(null).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> validBuilder().withStatus(null).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> validBuilder().withAuditInfo(null).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> validBuilder().withCurrentVersion(null).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> validBuilder().withLastVersion(null).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> validBuilder().withDeletedAt(null).build());
+ Assertions.assertDoesNotThrow(
+ () -> validBuilder().withBackingTagId(100L).withBackingTagValue("trading").build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> validBuilder().withBackingTagValue("trading").build());
+ }
+
+ private DomainPO.DomainPOBuilder validBuilder() {
+ return DomainPO.builder()
+ .withDomainId(10L)
+ .withDomainName("Finance")
+ .withMetalakeId(1L)
+ .withStatus("DRAFT")
+ .withAuditInfo("{}")
+ .withCurrentVersion(1L)
+ .withLastVersion(1L)
+ .withDeletedAt(0L);
+ }
+
+ private DomainEntity newDomain(
+ Long id, String name, String comment, ImmutableMap<String, String> properties) {
+ return DomainEntity.builder()
+ .withId(id)
+ .withName(name)
+ .withNamespace(NAMESPACE)
+ .withComment(comment)
+ .withProperties(properties)
+ .withStatus(Domain.Status.DRAFT)
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestDomainMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestDomainMetaService.java
new file mode 100644
index 0000000000..b3c83391ec
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestDomainMetaService.java
@@ -0,0 +1,980 @@
+/*
+ * 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 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;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityAlreadyExistsException;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.authorization.AuthorizationUtils;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.exceptions.OptimisticLockException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.BaseMetalake;
+import org.apache.gravitino.meta.DomainEntity;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.meta.TagEntity;
+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.DomainMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.TagMetaMapper;
+import org.apache.gravitino.storage.relational.po.DomainPO;
+import org.apache.gravitino.storage.relational.po.MetalakePO;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.tag.TagValue;
+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.TestTemplate;
+
+public class TestDomainMetaService extends TestJDBCBackend {
+
+ private static final String METALAKE_NAME = "metalake_for_domain_meta_service_test";
+
+ private final Map<String, String> props = ImmutableMap.of("k1", "v1");
+
+ @TestTemplate
+ public void testInsertGetAndListDomains() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ domainMetaService.getDomainByIdentifier(
+ NameIdentifierUtil.ofDomain(METALAKE_NAME, "missing")));
+ Assertions.assertTrue(
+ domainMetaService.listDomainsByNamespace(NamespaceUtil.ofDomain(METALAKE_NAME)).isEmpty());
+
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", "finance comment");
+ // A domain name may contain "/".
+ DomainEntity trading = newDomain(METALAKE_NAME, "Finance/Trading", null);
+ domainMetaService.insertDomain(finance, false);
+ domainMetaService.insertDomain(trading, false);
+
+ DomainEntity loaded = domainMetaService.getDomainByIdentifier(finance.nameIdentifier());
+ Assertions.assertEquals(finance, loaded);
+ Assertions.assertEquals(Domain.Status.DRAFT, loaded.status());
+ Assertions.assertEquals(props, loaded.properties());
+ Assertions.assertFalse(loaded.parent().isPresent());
+ Assertions.assertFalse(loaded.backingTag().isPresent());
+ Assertions.assertEquals(
+ trading, domainMetaService.getDomainByIdentifier(trading.nameIdentifier()));
+ Assertions.assertEquals(
+ finance, backend.get(finance.nameIdentifier(), Entity.EntityType.DOMAIN));
+ Assertions.assertTrue(backend.exists(trading.nameIdentifier(), Entity.EntityType.DOMAIN));
+
+ List<DomainEntity> domains =
+ backend.list(NamespaceUtil.ofDomain(METALAKE_NAME), Entity.EntityType.DOMAIN, true);
+ Assertions.assertEquals(2, domains.size());
+ Assertions.assertTrue(domains.contains(finance));
+ Assertions.assertTrue(domains.contains(trading));
+
+ List<DomainEntity> batch =
+ domainMetaService.batchGetDomainByIdentifier(
+ Lists.newArrayList(
+ finance.nameIdentifier(), NameIdentifierUtil.ofDomain(METALAKE_NAME, "missing")));
+ Assertions.assertEquals(Lists.newArrayList(finance), batch);
+ Assertions.assertTrue(
+ domainMetaService.batchGetDomainByIdentifier(Lists.newArrayList()).isEmpty());
+
+ Assertions.assertThrows(
+ EntityAlreadyExistsException.class,
+ () ->
+ domainMetaService.insertDomain(
+ newDomain(METALAKE_NAME, "Finance", "another finance"), false));
+ }
+
+ @TestTemplate
+ public void testDomainNamesAreScopedByMetalake() throws IOException {
+ String anotherMetalakeName = METALAKE_NAME + "_another";
+ createAndInsertMakeLake(METALAKE_NAME);
+ createAndInsertMakeLake(anotherMetalakeName);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", "comment");
+ DomainEntity anotherFinance = newDomain(anotherMetalakeName, "Finance", "another comment");
+ domainMetaService.insertDomain(finance, false);
+ domainMetaService.insertDomain(anotherFinance, false);
+
+ Assertions.assertEquals(
+ finance, domainMetaService.getDomainByIdentifier(finance.nameIdentifier()));
+ Assertions.assertEquals(
+ anotherFinance, domainMetaService.getDomainByIdentifier(anotherFinance.nameIdentifier()));
+ Assertions.assertEquals(
+ 1, domainMetaService.listDomainsByNamespace(NamespaceUtil.ofDomain(METALAKE_NAME)).size());
+ }
+
+ @TestTemplate
+ public void testInsertDomainWithOverwrite() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", "comment");
+ domainMetaService.insertDomain(finance, false);
+
+ DomainEntity replacement =
+ finance.toBuilder().withComment("replaced").withStatus(Domain.Status.PUBLISHED).build();
+ domainMetaService.insertDomain(replacement, true);
+ Assertions.assertEquals(
+ replacement, domainMetaService.getDomainByIdentifier(finance.nameIdentifier()));
+ Assertions.assertEquals(2L, selectDomainPO(finance.id()).currentVersion());
+
+ // An overwrite cannot reuse the ID of a deleted domain.
+ Assertions.assertTrue(domainMetaService.deleteDomain(finance.nameIdentifier()));
+ Assertions.assertThrows(
+ EntityAlreadyExistsException.class,
+ () -> domainMetaService.insertDomain(replacement, true));
+
+ // An overwrite with no matching name or ID inserts a new domain.
+ DomainEntity markets = newDomain(METALAKE_NAME, "Markets", null);
+ domainMetaService.insertDomain(markets, true);
+ Assertions.assertEquals(
+ markets, domainMetaService.getDomainByIdentifier(markets.nameIdentifier()));
+ Assertions.assertEquals(1L, selectDomainPO(markets.id()).currentVersion());
+ }
+
+ @TestTemplate
+ public void testOverwriteMatchesDomainById() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ String anotherMetalakeName = METALAKE_NAME + "_another";
+ createAndInsertMakeLake(anotherMetalakeName);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", "comment");
+ domainMetaService.insertDomain(finance, false);
+ domainMetaService.updateDomain(
+ finance.nameIdentifier(),
+ entity -> ((DomainEntity) entity).toBuilder().withName("Finance/Tax").build());
+
+ // The name is free after the rename, so the overwrite finds the domain by its ID and replaces
+ // the renamed row instead of adding a second domain.
+ DomainEntity replacement = finance.toBuilder().withComment("replaced").build();
+ domainMetaService.insertDomain(replacement, true);
+ Assertions.assertEquals(
+ replacement, domainMetaService.getDomainByIdentifier(finance.nameIdentifier()));
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ domainMetaService.getDomainByIdentifier(
+ NameIdentifierUtil.ofDomain(METALAKE_NAME, "Finance/Tax")));
+ Assertions.assertEquals(
+ 1, domainMetaService.listDomainsByNamespace(NamespaceUtil.ofDomain(METALAKE_NAME)).size());
+
+ // The ID cannot be taken over by a domain of another metalake.
+ DomainEntity elsewhere =
+ finance.toBuilder().withNamespace(NamespaceUtil.ofDomain(anotherMetalakeName)).build();
+ Assertions.assertThrows(
+ EntityAlreadyExistsException.class, () -> domainMetaService.insertDomain(elsewhere, true));
+ Assertions.assertTrue(
+ domainMetaService
+ .listDomainsByNamespace(NamespaceUtil.ofDomain(anotherMetalakeName))
+ .isEmpty());
+ }
+
+ @TestTemplate
+ public void testBackendReadsAndWritesDomains() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
+ DomainEntity markets = newDomain(METALAKE_NAME, "Markets", null);
+ backend.insert(finance, false);
+ backend.insert(markets, false);
+
+ List<DomainEntity> batch =
+ backend.batchGet(
+ Lists.newArrayList(
+ finance.nameIdentifier(),
+ markets.nameIdentifier(),
+ NameIdentifierUtil.ofDomain(METALAKE_NAME, "missing")),
+ Entity.EntityType.DOMAIN);
+ Assertions.assertEquals(2, batch.size());
+ Assertions.assertTrue(batch.contains(finance));
+ Assertions.assertTrue(batch.contains(markets));
+
+ DomainEntity published =
+ backend.<DomainEntity>update(
+ finance.nameIdentifier(),
+ Entity.EntityType.DOMAIN,
+ entity -> entity.toBuilder().withStatus(Domain.Status.PUBLISHED).build());
+ Assertions.assertEquals(Domain.Status.PUBLISHED, published.status());
+ Assertions.assertEquals(
+ published, backend.get(finance.nameIdentifier(), Entity.EntityType.DOMAIN));
+
+ Assertions.assertTrue(
+ backend.delete(finance.nameIdentifier(), Entity.EntityType.DOMAIN, false));
+ Assertions.assertFalse(
+ backend.delete(finance.nameIdentifier(), Entity.EntityType.DOMAIN, false));
+ Assertions.assertFalse(backend.exists(finance.nameIdentifier(), Entity.EntityType.DOMAIN));
+ Assertions.assertTrue(backend.exists(markets.nameIdentifier(), Entity.EntityType.DOMAIN));
+ }
+
+ @TestTemplate
+ public void testDomainIsLockableAsLiveEndpoint() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
+ domainMetaService.insertDomain(finance, false);
+ NamespacedEntityId observed =
+ EntityIdService.getEntityIds(finance.nameIdentifier(), Entity.EntityType.DOMAIN);
+
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ LiveEndpointService.lockLiveEndpoint(
+ finance.nameIdentifier(), Entity.EntityType.DOMAIN, observed));
+
+ // A domain recreated with the same name is a different endpoint.
+ Assertions.assertTrue(domainMetaService.deleteDomain(finance.nameIdentifier()));
+ domainMetaService.insertDomain(newDomain(METALAKE_NAME, "Finance", null), false);
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ LiveEndpointService.lockLiveEndpoint(
+ finance.nameIdentifier(), Entity.EntityType.DOMAIN, observed)));
+ }
+
+ @TestTemplate
+ public void testInsertDomainIntoMissingMetalake() {
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ DomainEntity domain = newDomain("metalake_that_does_not_exist", "Finance", null);
+
+ Assertions.assertThrows(
+ NoSuchEntityException.class, () -> domainMetaService.insertDomain(domain, false));
+ Assertions.assertThrows(
+ NoSuchEntityException.class, () -> domainMetaService.insertDomain(domain, true));
+ }
+
+ @TestTemplate
+ public void testUpdateDomain() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", "comment");
+ DomainEntity markets = newDomain(METALAKE_NAME, "Markets", null);
+ domainMetaService.insertDomain(finance, false);
+ domainMetaService.insertDomain(markets, false);
+
+ AuditInfo updatedAudit =
+ AuditInfo.builder()
+ .withCreator(AUDIT_INFO.creator())
+ .withCreateTime(AUDIT_INFO.createTime())
+ .withLastModifier("modifier")
+ .withLastModifiedTime(Instant.now())
+ .build();
+ DomainEntity updated =
+ domainMetaService.updateDomain(
+ finance.nameIdentifier(),
+ entity ->
+ ((DomainEntity) entity)
+ .toBuilder()
+ .withName("Finance/Tax")
+ .withComment(null)
+ .withProperties(ImmutableMap.of("k2", "v2"))
+ .withStatus(Domain.Status.PUBLISHED)
+ .withAuditInfo(updatedAudit)
+ .build());
+
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> domainMetaService.getDomainByIdentifier(finance.nameIdentifier()));
+ DomainEntity loaded =
+ domainMetaService.getDomainByIdentifier(
+ NameIdentifierUtil.ofDomain(METALAKE_NAME, "Finance/Tax"));
+ Assertions.assertEquals(updated, loaded);
+ Assertions.assertEquals(finance.id(), loaded.id());
+ Assertions.assertNull(loaded.comment());
+ Assertions.assertEquals(ImmutableMap.of("k2", "v2"), loaded.properties());
+ Assertions.assertEquals(Domain.Status.PUBLISHED, loaded.status());
+ Assertions.assertEquals("modifier", loaded.auditInfo().lastModifier());
+ Assertions.assertEquals(2L, selectDomainPO(finance.id()).currentVersion());
+
+ // Renaming to a name in use fails.
+ Assertions.assertThrows(
+ EntityAlreadyExistsException.class,
+ () ->
+ domainMetaService.updateDomain(
+ loaded.nameIdentifier(),
+ entity -> ((DomainEntity) entity).toBuilder().withName("Markets").build()));
+
+ // The updater must keep the domain ID.
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ domainMetaService.updateDomain(
+ markets.nameIdentifier(),
+ entity ->
+ ((DomainEntity) entity)
+ .toBuilder().withId(RandomIdGenerator.INSTANCE.nextId()).build()));
+
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ domainMetaService.updateDomain(
+ NameIdentifierUtil.ofDomain(METALAKE_NAME, "missing"), entity -> entity));
+ }
+
+ @TestTemplate
+ public void testAlterWaitsForConcurrentAlterAndKeepsItsChange() throws Exception {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", "initial");
+ domainMetaService.insertDomain(finance, false);
+
+ CountDownLatch alterWritten = new CountDownLatch(1);
+ CountDownLatch allowAlterCommit = new CountDownLatch(1);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<Throwable> competingAlter =
+ alterCommentInOpenTransaction(
+ executor, finance.id(), "competing", alterWritten, allowAlterCommit);
+ Assertions.assertTrue(alterWritten.await(30, TimeUnit.SECONDS));
+
+ // This alter reads the domain before the competing alter commits, then waits for its lock.
+ DomainEntity[] givenToUpdater = new DomainEntity[1];
+ Future<DomainEntity> alter =
+ executor.submit(
+ () ->
+ domainMetaService.updateDomain(
+ finance.nameIdentifier(),
+ entity -> {
+ givenToUpdater[0] = (DomainEntity) entity;
+ return givenToUpdater[0].toBuilder()
+ .withProperties(ImmutableMap.of("k2", "v2"))
+ .build();
+ }));
+ Assertions.assertThrows(TimeoutException.class, () -> alter.get(500, TimeUnit.MILLISECONDS));
+
+ allowAlterCommit.countDown();
+ Assertions.assertNull(competingAlter.get(30, TimeUnit.SECONDS));
+ DomainEntity altered = alter.get(30, TimeUnit.SECONDS);
+ // The updater ran on the locked row, so both changes are kept.
+ Assertions.assertEquals("competing", givenToUpdater[0].comment());
+ Assertions.assertEquals("competing", altered.comment());
+ Assertions.assertEquals(ImmutableMap.of("k2", "v2"), altered.properties());
+ Assertions.assertEquals(
+ altered, domainMetaService.getDomainByIdentifier(finance.nameIdentifier()));
+ } finally {
+ allowAlterCommit.countDown();
+ executor.shutdownNow();
+ }
+ }
+
+ @TestTemplate
+ public void testDeleteWaitsForConcurrentAlterAndDeletes() throws Exception {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", "initial");
+ domainMetaService.insertDomain(finance, false);
+
+ CountDownLatch alterWritten = new CountDownLatch(1);
+ CountDownLatch allowAlterCommit = new CountDownLatch(1);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<Throwable> competingAlter =
+ alterCommentInOpenTransaction(
+ executor, finance.id(), "competing", alterWritten, allowAlterCommit);
+ Assertions.assertTrue(alterWritten.await(30, TimeUnit.SECONDS));
+
+ // This delete reads the domain before the alter commits, then waits for its lock.
+ Future<Boolean> delete =
+ executor.submit(() -> domainMetaService.deleteDomain(finance.nameIdentifier()));
+ Assertions.assertThrows(TimeoutException.class, () -> delete.get(500, TimeUnit.MILLISECONDS));
+
+ allowAlterCommit.countDown();
+ Assertions.assertNull(competingAlter.get(30, TimeUnit.SECONDS));
+ Assertions.assertTrue(delete.get(30, TimeUnit.SECONDS));
+ Assertions.assertFalse(backend.exists(finance.nameIdentifier(), Entity.EntityType.DOMAIN));
+ } finally {
+ allowAlterCommit.countDown();
+ executor.shutdownNow();
+ }
+ }
+
+ @TestTemplate
+ public void testDeleteDomainCleansDependentRelations() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ TagEntity tag = newTag("Finance");
+ backend.insert(tag, false);
+ DomainEntity finance =
+ newDomain(METALAKE_NAME, "Finance", null).toBuilder().withBackingTagId(tag.id()).build();
+ domainMetaService.insertDomain(finance, false);
+
+ UserEntity user =
+ createUserEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ AuthorizationUtils.ofUserNamespace(METALAKE_NAME),
+ "domain_owner",
+ AUDIT_INFO);
+ backend.insert(user, false);
+ OwnerMetaService.getInstance()
+ .setOwner(
+ finance.nameIdentifier(), Entity.EntityType.DOMAIN, user.nameIdentifier(), user.type());
+
+ insertPrivilegeOnDomain(finance.id());
+
+ String domainAsMetadataObject =
+ String.format("metadata_object_id = %d AND metadata_object_type = 'DOMAIN'", finance.id());
+ String domainAsSecurableObject =
+ String.format("metadata_object_id = %d AND type = 'DOMAIN'", finance.id());
+ Assertions.assertEquals(1, countActiveRows("owner_meta", domainAsMetadataObject));
+ Assertions.assertEquals(
+ 1, countActiveRows("role_meta_securable_object", domainAsSecurableObject));
+
+ // A delete that observed the domain before a rename no longer names the row: it reports the
+ // domain as missing and cleans nothing.
+ DomainPO preRenamePO = selectDomainPO(finance.id());
+ DomainEntity treasury =
+ domainMetaService.updateDomain(
+ finance.nameIdentifier(),
+ entity -> ((DomainEntity) entity).toBuilder().withName("Treasury").build());
+ Assertions.assertFalse(domainMetaService.deleteDomain(finance.nameIdentifier(), preRenamePO));
+ Assertions.assertEquals(1, countActiveRows("owner_meta", domainAsMetadataObject));
+ Assertions.assertEquals(
+ 1, countActiveRows("role_meta_securable_object", domainAsSecurableObject));
+
+ // A delete that observed an older version of the same domain locks the row and deletes it.
+ DomainPO stalePO = selectDomainPO(treasury.id());
+ domainMetaService.updateDomain(
+ treasury.nameIdentifier(),
+ entity -> ((DomainEntity) entity).toBuilder().withComment("updated").build());
+ Assertions.assertTrue(domainMetaService.deleteDomain(treasury.nameIdentifier(), stalePO));
+ Assertions.assertFalse(domainMetaService.deleteDomain(treasury.nameIdentifier()));
+ Assertions.assertFalse(backend.exists(treasury.nameIdentifier(), Entity.EntityType.DOMAIN));
+ Assertions.assertEquals(0, countActiveRows("owner_meta", domainAsMetadataObject));
+ Assertions.assertEquals(
+ 0, countActiveRows("role_meta_securable_object", domainAsSecurableObject));
+ // The backing tag is kept.
+ Assertions.assertTrue(backend.exists(tag.nameIdentifier(), Entity.EntityType.TAG));
+
+ // The deleted domain row is a stale observation now.
+ Assertions.assertFalse(domainMetaService.deleteDomain(treasury.nameIdentifier(), stalePO));
+ }
+
+ @TestTemplate
+ public void testBackingTagIsStoredOnDomainRow() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ TagEntity dept = newTag("dept");
+ TagEntity finance = newTag("Finance");
+ backend.insert(dept, false);
+ backend.insert(finance, false);
+
+ DomainEntity trading =
+ newDomain(METALAKE_NAME, "Trading", null).toBuilder()
+ .withBackingTagId(dept.id())
+ .withBackingTagValue("trading")
+ .build();
+ DomainEntity financeDomain =
+ newDomain(METALAKE_NAME, "Finance", null).toBuilder()
+ .withBackingTagId(finance.id())
+ .build();
+ domainMetaService.insertDomain(trading, false);
+ domainMetaService.insertDomain(financeDomain, false);
+
+ DomainEntity loaded = domainMetaService.getDomainByIdentifier(trading.nameIdentifier());
+ Assertions.assertEquals(TagValue.of("dept", "trading"), loaded.backingTag().orElse(null));
+ Assertions.assertEquals(dept.id(), loaded.backingTagId());
+ Assertions.assertEquals(
+ TagValue.noValue("Finance"),
+ domainMetaService
+ .getDomainByIdentifier(financeDomain.nameIdentifier())
+ .backingTag()
+ .orElse(null));
+ Assertions.assertTrue(
+ domainMetaService.listDomainsByNamespace(NamespaceUtil.ofDomain(METALAKE_NAME)).stream()
+ .allMatch(domain -> domain.backingTag().isPresent()));
+
+ // The binding is by tag ID, so a renamed tag keeps backing the domain under its new name.
+ TagMetaService.getInstance()
+ .updateTag(
+ dept.nameIdentifier(),
+ entity ->
+ TagEntity.builder()
+ .withId(dept.id())
+ .withName("department")
+ .withNamespace(dept.namespace())
+ .withAuditInfo(AUDIT_INFO)
+ .build());
+ Assertions.assertEquals(
+ TagValue.of("department", "trading"),
+ domainMetaService
+ .getDomainByIdentifier(trading.nameIdentifier())
+ .backingTag()
+ .orElse(null));
+
+ // A deleted tag leaves its ID on the domain, which then has no backing tag, and a new tag with
+ // the same name does not take its place.
+ Assertions.assertTrue(
+ TagMetaService.getInstance()
+ .deleteTag(NameIdentifierUtil.ofTag(METALAKE_NAME, "department")));
+ backend.insert(newTag("department"), false);
+ DomainEntity orphaned = domainMetaService.getDomainByIdentifier(trading.nameIdentifier());
+ Assertions.assertFalse(orphaned.backingTag().isPresent());
+ Assertions.assertEquals(dept.id(), orphaned.backingTagId());
+ Assertions.assertEquals("trading", orphaned.backingTagValue());
+
+ // An update writes the binding: replace it, then remove it.
+ DomainEntity rebound =
+ domainMetaService.updateDomain(
+ trading.nameIdentifier(),
+ entity ->
+ ((DomainEntity) entity)
+ .toBuilder().withBackingTagId(finance.id()).withBackingTagValue(null).build());
+ Assertions.assertEquals(finance.id(), rebound.backingTagId());
+ Assertions.assertEquals(TagValue.noValue("Finance"), rebound.backingTag().orElse(null));
+ Assertions.assertEquals(
+ TagValue.noValue("Finance"),
+ domainMetaService
+ .getDomainByIdentifier(trading.nameIdentifier())
+ .backingTag()
+ .orElse(null));
+
+ domainMetaService.updateDomain(
+ trading.nameIdentifier(),
+ entity ->
+ ((DomainEntity) entity)
+ .toBuilder().withBackingTagId(null).withBackingTagValue(null).build());
+ DomainEntity unbound = domainMetaService.getDomainByIdentifier(trading.nameIdentifier());
+ Assertions.assertFalse(unbound.backingTag().isPresent());
+ Assertions.assertNull(unbound.backingTagId());
+
+ // Rebinding away from a live tag returns the new tag's name, not the one the updater's entity
+ // still carries.
+ TagEntity region = newTag("region");
+ backend.insert(region, false);
+ DomainEntity switched =
+ domainMetaService.updateDomain(
+ financeDomain.nameIdentifier(),
+ entity ->
+ ((DomainEntity) entity)
+ .toBuilder().withBackingTagId(region.id()).withBackingTagValue("apac").build());
+ Assertions.assertEquals(TagValue.of("region", "apac"), switched.backingTag().orElse(null));
+ Assertions.assertEquals(
+ switched, domainMetaService.getDomainByIdentifier(financeDomain.nameIdentifier()));
+ }
+
+ @TestTemplate
+ public void testDeleteDomainWaitsForConcurrentMetalakeDelete() throws Exception {
+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
+ domainMetaService.insertDomain(finance, false);
+ MetalakePO observedMetalakePO =
+ SessionUtils.getWithoutCommit(
+ MetalakeMetaMapper.class, mapper -> mapper.selectMetalakeMetaByName(metalake.name()));
+
+ // The metalake drop holds its exclusive row lock, so the domain delete must wait for it
+ // instead of racing it on the domain and privilege rows.
+ CountDownLatch dropWritten = new CountDownLatch(1);
+ CountDownLatch allowDropCommit = new CountDownLatch(1);
+ CountDownLatch deleteStarted = new CountDownLatch(1);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ Future<Throwable> dropResult =
+ executor.submit(
+ () -> {
+ try {
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ Assertions.assertEquals(
+ Integer.valueOf(1),
+ SessionUtils.getWithoutCommit(
+ MetalakeMetaMapper.class,
+ mapper ->
+ mapper.softDeleteMetalakeMetaByMetalakeId(
+ observedMetalakePO.getMetalakeId(),
+ observedMetalakePO.getCurrentVersion()))),
+ () -> {
+ dropWritten.countDown();
+ await(allowDropCommit);
+ });
+ return null;
+ } catch (Throwable throwable) {
+ return throwable;
+ }
+ });
+
+ try {
+ Assertions.assertTrue(dropWritten.await(30, TimeUnit.SECONDS));
+ Future<Boolean> deleteResult =
+ executor.submit(
+ () -> {
+ deleteStarted.countDown();
+ return domainMetaService.deleteDomain(finance.nameIdentifier());
+ });
+ Assertions.assertTrue(deleteStarted.await(30, TimeUnit.SECONDS));
+ Assertions.assertThrows(
+ TimeoutException.class, () -> deleteResult.get(500, TimeUnit.MILLISECONDS));
+
+ allowDropCommit.countDown();
+ Assertions.assertNull(dropResult.get(30, TimeUnit.SECONDS));
+ // The metalake is gone once the delete gets the lock, so the domain is reported as missing.
+ Assertions.assertFalse(deleteResult.get(30, TimeUnit.SECONDS));
+ } finally {
+ allowDropCommit.countDown();
+ executor.shutdownNow();
+ }
+ }
+
+ @TestTemplate
+ public void testAlterHoldsMetalakeFenceAgainstCascadeDrop() throws Exception {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ TagEntity tag = newTag("Finance");
+ backend.insert(tag, false);
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
+ domainMetaService.insertDomain(finance, false);
+
+ CountDownLatch domainLocked = new CountDownLatch(1);
+ CountDownLatch allowTagLock = new CountDownLatch(1);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ // Like a backing tag change, the updater locks the tag row while the domain row is locked.
+ Future<DomainEntity> alter =
+ executor.submit(
+ () ->
+ domainMetaService.updateDomain(
+ finance.nameIdentifier(),
+ entity -> {
+ domainLocked.countDown();
+ await(allowTagLock);
+ SessionUtils.getWithoutCommit(
+ TagMetaMapper.class,
+ mapper -> mapper.selectTagByTagIdForUpdate(tag.id()));
+ return ((DomainEntity) entity)
+ .toBuilder().withBackingTagId(tag.id()).build();
+ }));
+ Assertions.assertTrue(domainLocked.await(30, TimeUnit.SECONDS));
+
+ // A cascade drop locks tags before domains. It must wait at the metalake fence instead of
+ // taking the tag row the alter is about to lock.
+ Future<Boolean> drop =
+ executor.submit(
+ () ->
+ MetalakeMetaService.getInstance()
+ .deleteMetalake(NameIdentifierUtil.ofMetalake(METALAKE_NAME), true));
+ Assertions.assertThrows(TimeoutException.class, () -> drop.get(500, TimeUnit.MILLISECONDS));
+
+ allowTagLock.countDown();
+ Assertions.assertEquals(tag.id(), alter.get(30, TimeUnit.SECONDS).backingTagId());
+ Assertions.assertTrue(drop.get(30, TimeUnit.SECONDS));
+ } finally {
+ allowTagLock.countDown();
+ executor.shutdownNow();
+ }
+ Assertions.assertFalse(backend.exists(finance.nameIdentifier(), Entity.EntityType.DOMAIN));
+ }
+
+ @TestTemplate
+ public void testOverwriteRejectsIdOfDeletedDomain() throws IOException {
+ createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
+ domainMetaService.insertDomain(finance, false);
+ Assertions.assertTrue(domainMetaService.deleteDomain(finance.nameIdentifier()));
+
+ // The deleted row still holds the ID until garbage collection, so the ID cannot be reused.
+ EntityAlreadyExistsException exception =
+ Assertions.assertThrows(
+ EntityAlreadyExistsException.class,
+ () -> domainMetaService.insertDomain(finance, true));
+ Assertions.assertTrue(
+ exception.getMessage().contains(String.valueOf(finance.id())), exception.getMessage());
+ Assertions.assertFalse(backend.exists(finance.nameIdentifier(), Entity.EntityType.DOMAIN));
+ }
+
+ @TestTemplate
+ public void testOverwriteRacingInsertOfSameName() throws Exception {
+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ DomainEntity first = newDomain(METALAKE_NAME, "Finance", "first");
+ DomainEntity second = newDomain(METALAKE_NAME, "Finance", "second");
+
+ CountDownLatch firstWritten = new CountDownLatch(1);
+ CountDownLatch allowFirstCommit = new CountDownLatch(1);
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ Throwable overwriteFailure;
+ try {
+ Future<Throwable> firstInsert =
+ executor.submit(
+ () -> {
+ try {
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ SessionUtils.doWithoutCommit(
+ DomainMetaMapper.class,
+ mapper ->
+ mapper.insertDomainMeta(
+ DomainPO.initializeDomainPO(first, metalake.id()))),
+ () -> {
+ firstWritten.countDown();
+ await(allowFirstCommit);
+ });
+ return null;
+ } catch (Throwable throwable) {
+ return throwable;
+ }
+ });
+ Assertions.assertTrue(firstWritten.await(30, TimeUnit.SECONDS));
+
+ Future<Throwable> overwrite =
+ executor.submit(
+ () -> {
+ try {
+ domainMetaService.insertDomain(second, true);
+ return null;
+ } catch (Throwable throwable) {
+ return throwable;
+ }
+ });
+ Assertions.assertThrows(
+ TimeoutException.class, () -> overwrite.get(500, TimeUnit.MILLISECONDS));
+
+ allowFirstCommit.countDown();
+ Assertions.assertNull(firstInsert.get(30, TimeUnit.SECONDS));
+ overwriteFailure = overwrite.get(30, TimeUnit.SECONDS);
+ } finally {
+ allowFirstCommit.countDown();
+ executor.shutdownNow();
+ }
+
+ // Where the locking read waits for the uncommitted row, the overwrite replaces it. Where the
+ // read misses it, the insert hits the unique key, and the overwrite is reported as a
+ // concurrent modification rather than as an existing domain.
+ DomainEntity stored = domainMetaService.getDomainByIdentifier(first.nameIdentifier());
+ if (overwriteFailure == null) {
+ Assertions.assertEquals("second", stored.comment());
+ } else {
+ Assertions.assertTrue(
+ overwriteFailure instanceof OptimisticLockException, String.valueOf(overwriteFailure));
+ Assertions.assertEquals(first, stored);
+ }
+ Assertions.assertEquals(
+ 1, domainMetaService.listDomainsByNamespace(NamespaceUtil.ofDomain(METALAKE_NAME)).size());
+ }
+
+ @TestTemplate
+ public void testDomainLifeCycleWithMetalakeDeleteAndGarbageCollection() throws IOException {
+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);
+ String anotherMetalakeName = METALAKE_NAME + "_another";
+ createAndInsertMakeLake(anotherMetalakeName);
+
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
+ DomainEntity anotherFinance = newDomain(anotherMetalakeName, "Finance", null);
+ backend.insert(finance, false);
+ backend.insert(anotherFinance, false);
+
+ Assertions.assertTrue(
+ MetalakeMetaService.getInstance().deleteMetalake(metalake.nameIdentifier(), false));
+ Assertions.assertFalse(backend.exists(finance.nameIdentifier(), Entity.EntityType.DOMAIN));
+ Assertions.assertTrue(
+ backend.exists(anotherFinance.nameIdentifier(), Entity.EntityType.DOMAIN));
+ Assertions.assertTrue(legacyRecordExistsInDB(finance.id(), Entity.EntityType.DOMAIN));
+
+ Assertions.assertEquals(0, backend.deleteOldVersionData(Entity.EntityType.DOMAIN, 1L));
+ Assertions.assertTrue(
+ backend.hardDeleteLegacyData(Entity.EntityType.DOMAIN, Instant.now().toEpochMilli() + 1000)
+ >= 1);
+ Assertions.assertFalse(legacyRecordExistsInDB(finance.id(), Entity.EntityType.DOMAIN));
+ Assertions.assertTrue(
+ backend.exists(anotherFinance.nameIdentifier(), Entity.EntityType.DOMAIN));
+
+ // A cascading metalake delete removes its domains as well.
+ BaseMetalake cascadeMetalake = createAndInsertMakeLake(METALAKE_NAME + "_cascade");
+ DomainEntity markets = newDomain(cascadeMetalake.name(), "Markets", null);
+ backend.insert(markets, false);
+ UserEntity owner =
+ createUserEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ AuthorizationUtils.ofUserNamespace(cascadeMetalake.name()),
+ "markets_owner",
+ AUDIT_INFO);
+ backend.insert(owner, false);
+ OwnerMetaService.getInstance()
+ .setOwner(
+ markets.nameIdentifier(),
+ Entity.EntityType.DOMAIN,
+ owner.nameIdentifier(),
+ owner.type());
+ String marketsAsMetadataObject =
+ String.format("metadata_object_id = %d AND metadata_object_type = 'DOMAIN'", markets.id());
+ Assertions.assertEquals(1, countActiveRows("owner_meta", marketsAsMetadataObject));
+ Assertions.assertTrue(
+ MetalakeMetaService.getInstance().deleteMetalake(cascadeMetalake.nameIdentifier(), true));
+ Assertions.assertFalse(backend.exists(markets.nameIdentifier(), Entity.EntityType.DOMAIN));
+ Assertions.assertEquals(0, countActiveRows("owner_meta", marketsAsMetadataObject));
+ }
+
+ @TestTemplate
+ public void testDomainIdAndFullNameLookup() throws IOException {
+ BaseMetalake metalake = createAndInsertMakeLake(METALAKE_NAME);
+ DomainMetaService domainMetaService = DomainMetaService.getInstance();
+ DomainEntity finance = newDomain(METALAKE_NAME, "Finance", null);
+ domainMetaService.insertDomain(finance, false);
+
+ Assertions.assertEquals(
+ finance.id(), domainMetaService.getDomainIdByMetalakeIdAndName(metalake.id(), "Finance"));
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> domainMetaService.getDomainIdByMetalakeIdAndName(metalake.id(), "missing"));
+ Assertions.assertEquals(
+ finance.id(),
+ EntityIdService.getEntityId(finance.nameIdentifier(), Entity.EntityType.DOMAIN));
+
+ Map<Long, String> fullNames =
+ MetadataObjectService.TYPE_TO_FULLNAME_FUNCTION_MAP
+ .get(MetadataObject.Type.DOMAIN)
+ .apply(Lists.newArrayList(finance.id(), RandomIdGenerator.INSTANCE.nextId()));
+ Assertions.assertEquals(ImmutableMap.of(finance.id(), "Finance"), fullNames);
+ Assertions.assertTrue(
+ MetadataObjectService.TYPE_TO_FULLNAME_FUNCTION_MAP
+ .get(MetadataObject.Type.DOMAIN)
+ .apply(Lists.newArrayList())
+ .isEmpty());
+ Assertions.assertEquals(
+ MetadataObjects.of(null, "Finance", MetadataObject.Type.DOMAIN),
+ NameIdentifierUtil.toMetadataObject(finance.nameIdentifier(), Entity.EntityType.DOMAIN));
+ }
+
+ /**
+ * Alters the comment of a domain in a transaction that stays open, holding the row lock, until
+ * {@code allowCommit} is released.
+ */
+ private Future<Throwable> alterCommentInOpenTransaction(
+ ExecutorService executor,
+ long domainId,
+ String comment,
+ CountDownLatch written,
+ CountDownLatch allowCommit) {
+ DomainPO observedPO = selectDomainPO(domainId);
+ DomainEntity observed =
+ DomainPO.fromDomainPO(observedPO, NamespaceUtil.ofDomain(METALAKE_NAME));
+ DomainPO alteredPO =
+ DomainPO.updateDomainPO(observedPO, observed.toBuilder().withComment(comment).build());
+ return executor.submit(
+ () -> {
+ try {
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ Assertions.assertEquals(
+ Integer.valueOf(1),
+ SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class,
+ mapper -> mapper.updateDomainMeta(alteredPO, observedPO))),
+ () -> {
+ written.countDown();
+ await(allowCommit);
+ });
+ return null;
+ } catch (Throwable throwable) {
+ return throwable;
+ }
+ });
+ }
+
+ private void await(CountDownLatch latch) {
+ try {
+ Assertions.assertTrue(latch.await(30, TimeUnit.SECONDS));
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException(e);
+ }
+ }
+
+ private DomainEntity newDomain(String metalake, String name, String comment) {
+ return DomainEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(name)
+ .withNamespace(NamespaceUtil.ofDomain(metalake))
+ .withComment(comment)
+ .withProperties(props)
+ .withStatus(Domain.Status.DRAFT)
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ }
+
+ private TagEntity newTag(String name) {
+ return TagEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(name)
+ .withNamespace(NamespaceUtil.ofTag(METALAKE_NAME))
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ }
+
+ private void insertPrivilegeOnDomain(long domainId) {
+ try (SqlSession sqlSession =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = sqlSession.getConnection();
+ Statement statement = connection.createStatement()) {
+ statement.executeUpdate(
+ "INSERT INTO role_meta_securable_object (role_id, metadata_object_id, type,"
+ + " privilege_names, privilege_conditions, current_version, last_version,"
+ + " deleted_at) VALUES ("
+ + RandomIdGenerator.INSTANCE.nextId()
+ + ", "
+ + domainId
+ + ", 'DOMAIN', 'USE_DOMAIN', 'ALLOW', 1, 1, 0)");
+ } catch (SQLException se) {
+ throw new RuntimeException("SQL execution failed", se);
+ }
+ }
+
+ private DomainPO selectDomainPO(long domainId) {
+ return SessionUtils.getWithoutCommit(
+ DomainMetaMapper.class, mapper -> mapper.selectDomainMetaById(domainId));
+ }
+
+ private int countActiveRows(String table, String whereClause) {
+ try (SqlSession sqlSession =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = sqlSession.getConnection();
+ Statement statement = connection.createStatement();
+ ResultSet rs =
+ statement.executeQuery(
+ String.format(
+ "SELECT count(*) FROM %s WHERE %s AND deleted_at = 0", table, whereClause))) {
+ if (rs.next()) {
+ return rs.getInt(1);
+ }
+ 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/TestOrphanedMetadataObjectRelationService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOrphanedMetadataObjectRelationService.java
index 807cadf2a0..82e3ff5360 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOrphanedMetadataObjectRelationService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOrphanedMetadataObjectRelationService.java
@@ -25,15 +25,18 @@ import java.sql.SQLException;
import java.sql.Statement;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.Namespace;
+import org.apache.gravitino.domain.Domain;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
import org.apache.gravitino.meta.ColumnEntity;
+import org.apache.gravitino.meta.DomainEntity;
import org.apache.gravitino.meta.SchemaEntity;
import org.apache.gravitino.meta.TableEntity;
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.NamespaceUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.TestTemplate;
@@ -179,6 +182,30 @@ public class TestOrphanedMetadataObjectRelationService extends TestJDBCBackend {
}
}
+ @TestTemplate
+ public void testSoftDeleteOrphanedDomainRelations() throws Exception {
+ String metalake = "metalake_for_orphan_domain_relation_test";
+ createAndInsertMakeLake(metalake);
+ DomainEntity liveDomain =
+ DomainEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName("live_domain")
+ .withNamespace(NamespaceUtil.ofDomain(metalake))
+ .withStatus(Domain.Status.DRAFT)
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ backend.insert(liveDomain, false);
+
+ insertRelations("DOMAIN", liveDomain.id(), ORPHAN_ID);
+
+ Assertions.assertEquals(
+ 4,
+ OrphanedMetadataObjectRelationService.getInstance()
+ .softDeleteOrphanedRelations(MetadataObject.Type.DOMAIN, 10));
+ Assertions.assertEquals(4, countActiveRelations(liveDomain.id()));
+ Assertions.assertEquals(0, countActiveRelations(ORPHAN_ID));
+ }
+
private void insertRelations(String type, long liveId, long orphanId) throws SQLException {
try (SqlSession session =
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
diff --git a/core/src/test/java/org/apache/gravitino/utils/TestMetadataObjectUtil.java b/core/src/test/java/org/apache/gravitino/utils/TestMetadataObjectUtil.java
index 02abd359a8..abec589098 100644
--- a/core/src/test/java/org/apache/gravitino/utils/TestMetadataObjectUtil.java
+++ b/core/src/test/java/org/apache/gravitino/utils/TestMetadataObjectUtil.java
@@ -125,15 +125,11 @@ public class TestMetadataObjectUtil {
public void testMetadataObjectEntityTypes() {
Set<Entity.EntityType> entityTypes = MetadataObjectUtil.metadataObjectEntityTypes();
for (MetadataObject.Type type : MetadataObject.Type.values()) {
- if (type == MetadataObject.Type.DOMAIN) {
- // DOMAIN is not backed by an entity yet.
- Assertions.assertThrows(
- IllegalArgumentException.class, () -> MetadataObjectUtil.toEntityType(type));
- continue;
- }
Assertions.assertTrue(entityTypes.contains(MetadataObjectUtil.toEntityType(type)));
}
- Assertions.assertEquals(MetadataObject.Type.values().length - 1, entityTypes.size());
+ Assertions.assertEquals(MetadataObject.Type.values().length, entityTypes.size());
+ Assertions.assertEquals(
+ Entity.EntityType.DOMAIN, MetadataObjectUtil.toEntityType(MetadataObject.Type.DOMAIN));
Assertions.assertThrows(
UnsupportedOperationException.class, () -> entityTypes.add(Entity.EntityType.USER));
}
@@ -204,6 +200,11 @@ public class TestMetadataObjectUtil {
MetadataObjectUtil.toEntityIdent(
"metalake", MetadataObjects.of("catalog.schema", "view", MetadataObject.Type.VIEW)));
+ Assertions.assertEquals(
+ NameIdentifierUtil.ofDomain("metalake", "Finance/Trading"),
+ MetadataObjectUtil.toEntityIdent(
+ "metalake", MetadataObjects.of(null, "Finance/Trading", MetadataObject.Type.DOMAIN)));
+
Assertions.assertEquals(
NameIdentifier.of("metalake", "catalog", "schema", "function"),
MetadataObjectUtil.toEntityIdent(
diff --git a/core/src/test/java/org/apache/gravitino/utils/TestNameIdentifierUtil.java b/core/src/test/java/org/apache/gravitino/utils/TestNameIdentifierUtil.java
index 78ce09e685..b9d3489928 100644
--- a/core/src/test/java/org/apache/gravitino/utils/TestNameIdentifierUtil.java
+++ b/core/src/test/java/org/apache/gravitino/utils/TestNameIdentifierUtil.java
@@ -23,6 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.util.Map;
import org.apache.gravitino.Entity;
@@ -165,6 +166,27 @@ public class TestNameIdentifierUtil {
NameIdentifierUtil.ofTag("metalake1", "tag1"), Entity.EntityType.TAG);
assertEquals(expectedTagObject, tagObject);
+ // test domain, whose name may contain "/"
+ NameIdentifier domain = NameIdentifierUtil.ofDomain("metalake1", "Finance/Trading");
+ assertEquals(NamespaceUtil.ofDomain("metalake1"), domain.namespace());
+ assertEquals(
+ MetadataObjects.parse("Finance/Trading", MetadataObject.Type.DOMAIN),
+ NameIdentifierUtil.toMetadataObject(domain, Entity.EntityType.DOMAIN));
+ assertEquals(
+ domain,
+ NameIdentifierUtil.buildNameIdentifier(
+ Entity.EntityType.DOMAIN,
+ "Finance/Trading",
+ ImmutableMap.of(Entity.EntityType.METALAKE, "metalake1")));
+ assertEquals(
+ NameIdentifier.of("metalake1"),
+ NameIdentifierUtil.parentNameIdentifier(domain, Entity.EntityType.DOMAIN));
+ assertThrows(
+ IllegalNamespaceException.class,
+ () ->
+ NameIdentifierUtil.toMetadataObject(
+ NameIdentifier.of("metalake1", "Finance"), Entity.EntityType.DOMAIN));
+
// test model version is not convertible to MetadataObject
NameIdentifier modelVersion =
NameIdentifier.of("metalake1", "catalog1", "schema1", "model1", "0");
diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sql
index d443c0824d..ae3c20f1e3 100644
--- a/scripts/h2/schema-2.0.0-h2.sql
+++ b/scripts/h2/schema-2.0.0-h2.sql
@@ -795,3 +795,21 @@ CREATE TABLE IF NOT EXISTS `semantic_model_source_rel` (
CREATE INDEX IF NOT EXISTS `idx_smsr_model` ON `semantic_model_source_rel` (`semantic_model_id`, `deleted_at`);
CREATE INDEX IF NOT EXISTS `idx_smsr_source` ON `semantic_model_source_rel` (`metalake_id`, `source_type`, `source_id`, `deleted_at`);
CREATE INDEX IF NOT EXISTS `idx_smsr_deleted_at` ON `semantic_model_source_rel` (`deleted_at`);
+
+CREATE TABLE IF NOT EXISTS `domain_meta` (
+ `domain_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'domain id',
+ `domain_name` VARCHAR(128) NOT NULL COMMENT 'domain name',
+ `metalake_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'metalake id',
+ `domain_comment` VARCHAR(256) DEFAULT '' COMMENT 'domain comment',
+ `domain_status` VARCHAR(16) NOT NULL DEFAULT 'DRAFT' COMMENT 'domain status, DRAFT or PUBLISHED',
+ `backing_tag_id` BIGINT(20) UNSIGNED DEFAULT NULL COMMENT 'id of the backing tag, NULL if the domain has none',
+ `backing_tag_value` VARCHAR(256) DEFAULT NULL COMMENT 'value of the backing tag, NULL binds the tag without a value',
+ `properties` CLOB DEFAULT NULL COMMENT 'domain properties',
+ `audit_info` CLOB NOT NULL COMMENT 'domain audit info',
+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'domain current version',
+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'domain last version',
+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'domain deleted at',
+ PRIMARY KEY (`domain_id`),
+ UNIQUE KEY `uk_mi_dn_del` (`metalake_id`, `domain_name`, `deleted_at`),
+ KEY `domain_meta_idx_backing_tag` (`metalake_id`, `backing_tag_id`, `backing_tag_value`, `deleted_at`)
+) ENGINE=InnoDB;
diff --git a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
index ddd8470561..3a87c9a7ad 100644
--- a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
+++ b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql
@@ -250,3 +250,21 @@ CREATE INDEX IF NOT EXISTS `idx_smsr_deleted_at` ON `semantic_model_source_rel`
-- Align the location and uri name widths with the MySQL and PostgreSQL schemas.
ALTER TABLE `fileset_version_info` ALTER COLUMN `storage_location_name` VARCHAR(256) NOT NULL DEFAULT 'default';
ALTER TABLE `model_version_info` ALTER COLUMN `model_version_uri_name` VARCHAR(256) NOT NULL;
+
+CREATE TABLE IF NOT EXISTS `domain_meta` (
+ `domain_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'domain id',
+ `domain_name` VARCHAR(128) NOT NULL COMMENT 'domain name',
+ `metalake_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'metalake id',
+ `domain_comment` VARCHAR(256) DEFAULT '' COMMENT 'domain comment',
+ `domain_status` VARCHAR(16) NOT NULL DEFAULT 'DRAFT' COMMENT 'domain status, DRAFT or PUBLISHED',
+ `backing_tag_id` BIGINT(20) UNSIGNED DEFAULT NULL COMMENT 'id of the backing tag, NULL if the domain has none',
+ `backing_tag_value` VARCHAR(256) DEFAULT NULL COMMENT 'value of the backing tag, NULL binds the tag without a value',
+ `properties` CLOB DEFAULT NULL COMMENT 'domain properties',
+ `audit_info` CLOB NOT NULL COMMENT 'domain audit info',
+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'domain current version',
+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'domain last version',
+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'domain deleted at',
+ PRIMARY KEY (`domain_id`),
+ UNIQUE KEY `uk_mi_dn_del` (`metalake_id`, `domain_name`, `deleted_at`),
+ KEY `domain_meta_idx_backing_tag` (`metalake_id`, `backing_tag_id`, `backing_tag_value`, `deleted_at`)
+) ENGINE=InnoDB;
diff --git a/scripts/mysql/schema-2.0.0-mysql.sql b/scripts/mysql/schema-2.0.0-mysql.sql
index 56ec88cd70..52501e7058 100644
--- a/scripts/mysql/schema-2.0.0-mysql.sql
+++ b/scripts/mysql/schema-2.0.0-mysql.sql
@@ -783,3 +783,21 @@ CREATE TABLE IF NOT EXISTS `semantic_model_source_rel` (
KEY `idx_smsr_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
COMMENT 'current semantic model dataset source associations';
+
+CREATE TABLE IF NOT EXISTS `domain_meta` (
+ `domain_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'domain id',
+ `domain_name` VARCHAR(128) NOT NULL COMMENT 'domain name',
+ `metalake_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'metalake id',
+ `domain_comment` VARCHAR(256) DEFAULT '' COMMENT 'domain comment',
+ `domain_status` VARCHAR(16) NOT NULL DEFAULT 'DRAFT' COMMENT 'domain status, DRAFT or PUBLISHED',
+ `backing_tag_id` BIGINT(20) UNSIGNED DEFAULT NULL COMMENT 'id of the backing tag, NULL if the domain has none',
+ `backing_tag_value` VARCHAR(256) DEFAULT NULL COMMENT 'value of the backing tag, NULL binds the tag without a value',
+ `properties` MEDIUMTEXT DEFAULT NULL COMMENT 'domain properties',
+ `audit_info` MEDIUMTEXT NOT NULL COMMENT 'domain audit info',
+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'domain current version',
+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'domain last version',
+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'domain deleted at',
+ PRIMARY KEY (`domain_id`),
+ UNIQUE KEY `uk_mi_dn_del` (`metalake_id`, `domain_name`, `deleted_at`),
+ KEY `domain_meta_idx_backing_tag` (`metalake_id`, `backing_tag_id`, `backing_tag_value`, `deleted_at`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'domain metadata';
diff --git a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
index bf43eae536..e7810e7661 100644
--- a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
+++ b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
@@ -712,3 +712,21 @@ CREATE TABLE IF NOT EXISTS `semantic_model_source_rel` (
KEY `idx_smsr_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
COMMENT 'current semantic model dataset source associations';
+
+CREATE TABLE IF NOT EXISTS `domain_meta` (
+ `domain_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'domain id',
+ `domain_name` VARCHAR(128) NOT NULL COMMENT 'domain name',
+ `metalake_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'metalake id',
+ `domain_comment` VARCHAR(256) DEFAULT '' COMMENT 'domain comment',
+ `domain_status` VARCHAR(16) NOT NULL DEFAULT 'DRAFT' COMMENT 'domain status, DRAFT or PUBLISHED',
+ `backing_tag_id` BIGINT(20) UNSIGNED DEFAULT NULL COMMENT 'id of the backing tag, NULL if the domain has none',
+ `backing_tag_value` VARCHAR(256) DEFAULT NULL COMMENT 'value of the backing tag, NULL binds the tag without a value',
+ `properties` MEDIUMTEXT DEFAULT NULL COMMENT 'domain properties',
+ `audit_info` MEDIUMTEXT NOT NULL COMMENT 'domain audit info',
+ `current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'domain current version',
+ `last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'domain last version',
+ `deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'domain deleted at',
+ PRIMARY KEY (`domain_id`),
+ UNIQUE KEY `uk_mi_dn_del` (`metalake_id`, `domain_name`, `deleted_at`),
+ KEY `domain_meta_idx_backing_tag` (`metalake_id`, `backing_tag_id`, `backing_tag_value`, `deleted_at`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'domain metadata';
diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql b/scripts/postgresql/schema-2.0.0-postgresql.sql
index 1612123497..d573ca0971 100644
--- a/scripts/postgresql/schema-2.0.0-postgresql.sql
+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql
@@ -1360,3 +1360,34 @@ COMMENT ON COLUMN semantic_model_source_rel.dataset_name IS 'exact dataset name
COMMENT ON COLUMN semantic_model_source_rel.source_type IS 'TABLE or VIEW';
COMMENT ON COLUMN semantic_model_source_rel.source_id IS 'resolved source object id';
COMMENT ON COLUMN semantic_model_source_rel.deleted_at IS 'association retired at';
+
+CREATE TABLE IF NOT EXISTS domain_meta (
+ domain_id BIGINT NOT NULL,
+ domain_name VARCHAR(128) NOT NULL,
+ metalake_id BIGINT NOT NULL,
+ domain_comment VARCHAR(256) DEFAULT '',
+ domain_status VARCHAR(16) NOT NULL DEFAULT 'DRAFT',
+ backing_tag_id BIGINT DEFAULT NULL,
+ backing_tag_value VARCHAR(256) DEFAULT NULL,
+ properties TEXT DEFAULT NULL,
+ audit_info TEXT NOT NULL,
+ current_version INT NOT NULL DEFAULT 1,
+ last_version INT NOT NULL DEFAULT 1,
+ deleted_at BIGINT NOT NULL DEFAULT 0,
+ PRIMARY KEY (domain_id),
+ UNIQUE (metalake_id, domain_name, deleted_at)
+);
+CREATE INDEX IF NOT EXISTS domain_meta_idx_backing_tag ON domain_meta (metalake_id, backing_tag_id, backing_tag_value, deleted_at);
+COMMENT ON TABLE domain_meta IS 'domain metadata';
+COMMENT ON COLUMN domain_meta.domain_id IS 'domain id';
+COMMENT ON COLUMN domain_meta.domain_name IS 'domain name';
+COMMENT ON COLUMN domain_meta.metalake_id IS 'metalake id';
+COMMENT ON COLUMN domain_meta.domain_comment IS 'domain comment';
+COMMENT ON COLUMN domain_meta.domain_status IS 'domain status, DRAFT or PUBLISHED';
+COMMENT ON COLUMN domain_meta.backing_tag_id IS 'id of the backing tag, NULL if the domain has none';
+COMMENT ON COLUMN domain_meta.backing_tag_value IS 'value of the backing tag, NULL binds the tag without a value';
+COMMENT ON COLUMN domain_meta.properties IS 'domain properties';
+COMMENT ON COLUMN domain_meta.audit_info IS 'domain audit info';
+COMMENT ON COLUMN domain_meta.current_version IS 'domain current version';
+COMMENT ON COLUMN domain_meta.last_version IS 'domain last version';
+COMMENT ON COLUMN domain_meta.deleted_at IS 'domain deleted at';
diff --git a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
index 3424170694..a7d2419c7c 100644
--- a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
+++ b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql
@@ -365,3 +365,34 @@ COMMENT ON COLUMN semantic_model_source_rel.dataset_name IS 'exact dataset name
COMMENT ON COLUMN semantic_model_source_rel.source_type IS 'TABLE or VIEW';
COMMENT ON COLUMN semantic_model_source_rel.source_id IS 'resolved source object id';
COMMENT ON COLUMN semantic_model_source_rel.deleted_at IS 'association retired at';
+
+CREATE TABLE IF NOT EXISTS domain_meta (
+ domain_id BIGINT NOT NULL,
+ domain_name VARCHAR(128) NOT NULL,
+ metalake_id BIGINT NOT NULL,
+ domain_comment VARCHAR(256) DEFAULT '',
+ domain_status VARCHAR(16) NOT NULL DEFAULT 'DRAFT',
+ backing_tag_id BIGINT DEFAULT NULL,
+ backing_tag_value VARCHAR(256) DEFAULT NULL,
+ properties TEXT DEFAULT NULL,
+ audit_info TEXT NOT NULL,
+ current_version INT NOT NULL DEFAULT 1,
+ last_version INT NOT NULL DEFAULT 1,
+ deleted_at BIGINT NOT NULL DEFAULT 0,
+ PRIMARY KEY (domain_id),
+ UNIQUE (metalake_id, domain_name, deleted_at)
+);
+CREATE INDEX IF NOT EXISTS domain_meta_idx_backing_tag ON domain_meta (metalake_id, backing_tag_id, backing_tag_value, deleted_at);
+COMMENT ON TABLE domain_meta IS 'domain metadata';
+COMMENT ON COLUMN domain_meta.domain_id IS 'domain id';
+COMMENT ON COLUMN domain_meta.domain_name IS 'domain name';
+COMMENT ON COLUMN domain_meta.metalake_id IS 'metalake id';
+COMMENT ON COLUMN domain_meta.domain_comment IS 'domain comment';
+COMMENT ON COLUMN domain_meta.domain_status IS 'domain status, DRAFT or PUBLISHED';
+COMMENT ON COLUMN domain_meta.backing_tag_id IS 'id of the backing tag, NULL if the domain has none';
+COMMENT ON COLUMN domain_meta.backing_tag_value IS 'value of the backing tag, NULL binds the tag without a value';
+COMMENT ON COLUMN domain_meta.properties IS 'domain properties';
+COMMENT ON COLUMN domain_meta.audit_info IS 'domain audit info';
+COMMENT ON COLUMN domain_meta.current_version IS 'domain current version';
+COMMENT ON COLUMN domain_meta.last_version IS 'domain last version';
+COMMENT ON COLUMN domain_meta.deleted_at IS 'domain deleted at';