This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch glossary-term-dev
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/glossary-term-dev by this push:
new 6e1afe00ff [#14986] feat(core): Add glossary term entity and storage
(#14992)
6e1afe00ff is described below
commit 6e1afe00ffacc7549ba9a90fd6d45c3f2d060dde
Author: Qi Yu <[email protected]>
AuthorDate: Wed Nov 18 14:25:09 2026 +0800
[#14986] feat(core): Add glossary term entity and storage (#14992)
### What changes were proposed in this pull request?
Implement design task T2: persist glossary definitions and synonyms with
normalized name keys, optional unique source references, revisions,
transactional updates, soft deletion, metalake cleanup and garbage
collection. Wire the entity into the relational backend and keep
glossary reads uncached.
Add H2, MySQL and PostgreSQL schemas and 1.3.0-to-2.0.0 upgrade scripts.
All glossary tables and columns have database-visible comments,
including key examples. Only live definitions reserve names/source
references: H2/MySQL use a generated discriminator; PostgreSQL uses
partial unique indexes. MySQL's binary source key preserves
trailing-space distinctions on 5.7 and 8.0.
Read definitions, synonyms and the live parent name in one non-locking
statement snapshot. ID resolution also checks the live parent name in
its SELECT. Writes retain parent fencing and row locks; overwrite
rejects mismatched IDs before mutation. Argument validation uses
Preconditions.checkArgument, including null required fields, collection
inputs and link elements.
### Why are the changes needed?
Provide the storage foundation for the Glossary API on
glossary-term-dev.
Fixes #14986
### Does this PR introduce _any_ user-facing change?
No new REST endpoints. Relation/hierarchy storage (T3), manager
validation and semantic no-op handling (T4), authorization, bindings and
API projections remain separate tasks.
Shared synonyms are intentional (T2.9). This storage service does not
enforce name-versus-synonym conflicts, even for sequential writes.
Before exposing manager/API writes, T3/T4 must acquire the dedicated
per-metalake hierarchy mutex, read fresh state, check both directions
and retain the lock through commit for every create, rename, overwrite
and synonym change. This deferred requirement is documented in code; the
review thread remains open.
Batch-get reads each identifier separately. Full-metalake listing joins
definitions and synonyms, repeating root columns for up to 100 synonyms
per term but decoding each definition once. H2 serializes writes within
a metalake through its parent lock; reads take no row locks.
### How was this patch tested?
- Final head 308e6fd18d: 49 targeted cases passed: 5 entity and 15
relational-store/cache unit tests, plus 16 glossary storage and 13
SQL-script cases on H2. Core Spotless and git diff --check passed. No
full core suite was run locally.
- Negative regressions verified that the old implementation throws NPE
for null required fields and accepts null link elements; the corrected
validation passes. Earlier negative regressions cover blocking reads,
overwrite ID mismatches, wrong namespaces and four metalake-rename read
races.
- Fresh/upgrade glossary SQL blocks match per backend. Prior H2 metadata
inspection verified comments on both tables and all 18 columns;
hexadecimal examples were checked independently.
- MySQL/PostgreSQL CI artifacts for d0caac9fe1 showed 12 glossary and 13
SQL-script cases passing per backend. This is earlier-head evidence
only: final-head backend CI is still required, including the later
parent-name JOIN and SQL comments. Local Docker is unavailable.
---
.../src/main/java/org/apache/gravitino/Entity.java | 3 +-
.../apache/gravitino/meta/GlossaryTermEntity.java | 269 +++++++++++
.../apache/gravitino/meta/GlossaryTermNames.java | 61 +++
.../gravitino/storage/relational/JDBCBackend.java | 18 +
.../storage/relational/RelationalEntityStore.java | 15 +
.../RelationalEntityStoreIdResolver.java | 7 +-
.../relational/mapper/GlossaryTermMetaMapper.java | 95 ++++
.../provider/DefaultMapperPackageProvider.java | 2 +
.../provider/base/GlossaryTermSQLProvider.java | 124 +++++
.../storage/relational/po/GlossaryTermPO.java | 41 ++
.../relational/po/GlossaryTermSnapshotPO.java | 31 ++
.../service/GlossaryTermMetaService.java | 389 ++++++++++++++++
.../relational/service/MetalakeMetaService.java | 2 +
.../gravitino/meta/TestGlossaryTermEntity.java | 132 ++++++
.../apache/gravitino/storage/TestSQLScripts.java | 59 +++
.../relational/TestRelationalEntityStore.java | 26 ++
.../relational/service/GlossaryInvariants.java | 61 +++
.../service/TestGlossaryTermMetaService.java | 499 +++++++++++++++++++++
design-docs/glossary-design.md | 16 +-
scripts/h2/schema-2.0.0-h2.sql | 31 ++
scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql | 31 ++
scripts/mysql/schema-2.0.0-mysql.sql | 31 ++
scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql | 31 ++
scripts/postgresql/schema-2.0.0-postgresql.sql | 49 ++
.../upgrade-1.3.0-to-2.0.0-postgresql.sql | 49 ++
25 files changed, 2066 insertions(+), 6 deletions(-)
diff --git a/core/src/main/java/org/apache/gravitino/Entity.java
b/core/src/main/java/org/apache/gravitino/Entity.java
index 797ea7392b..0aa43595e7 100644
--- a/core/src/main/java/org/apache/gravitino/Entity.java
+++ b/core/src/main/java/org/apache/gravitino/Entity.java
@@ -88,7 +88,8 @@ public interface Entity extends Serializable {
JOB,
AUDIT,
FUNCTION,
- DOMAIN;
+ DOMAIN,
+ GLOSSARY_TERM;
}
/**
diff --git
a/core/src/main/java/org/apache/gravitino/meta/GlossaryTermEntity.java
b/core/src/main/java/org/apache/gravitino/meta/GlossaryTermEntity.java
new file mode 100644
index 0000000000..5170d2569f
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/meta/GlossaryTermEntity.java
@@ -0,0 +1,269 @@
+/*
+ * 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 java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import javax.annotation.Nullable;
+import org.apache.gravitino.Audit;
+import org.apache.gravitino.Auditable;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.Field;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.glossary.GlossaryTerm.Status;
+import org.apache.gravitino.glossary.TermLink;
+
+/**
+ * Persisted glossary definition. Relations and authorized API projections are
loaded separately.
+ */
+public final class GlossaryTermEntity implements Entity, HasIdentifier,
Auditable {
+ /** The id field. */
+ public static final Field ID = Field.required("id", Long.class, "The
glossary id.");
+ /** The name field. */
+ public static final Field NAME = Field.required("name", String.class, "The
glossary name.");
+ /** The definition field. */
+ public static final Field DEFINITION =
+ Field.optional("definition", String.class, "The glossary definition.");
+ /** The synonyms field. */
+ public static final Field SYNONYMS =
+ Field.required("synonyms", String[].class, "The glossary synonyms.");
+ /** The status field. */
+ public static final Field STATUS = Field.required("status", Status.class,
"The glossary status.");
+ /** The links field. */
+ public static final Field LINKS =
+ Field.required("links", TermLink[].class, "The glossary links.");
+ /** The sourceRef field. */
+ public static final Field SOURCE_REF =
+ Field.optional("sourceRef", String.class, "The glossary sourceRef.");
+ /** The properties field. */
+ public static final Field PROPERTIES =
+ Field.required("properties", Map.class, "The glossary properties.");
+ /** The version field. */
+ public static final Field VERSION =
+ Field.required("version", Long.class, "The glossary version.");
+ /** The auditInfo field. */
+ public static final Field AUDIT_INFO =
+ Field.required("auditInfo", Audit.class, "The glossary auditInfo.");
+
+ private Long id;
+ private String name;
+ private Namespace namespace;
+ @Nullable private String definition;
+ private String[] synonyms;
+ private Status status;
+ private TermLink[] links;
+ @Nullable private String sourceRef;
+ private Map<String, String> properties;
+ private long version;
+ private Audit auditInfo;
+
+ private GlossaryTermEntity() {}
+ /** Returns the id. */
+ public Long id() {
+ return id;
+ }
+ /** Returns the name. */
+ public String name() {
+ return name;
+ }
+ /** Returns the namespace. */
+ public Namespace namespace() {
+ return namespace;
+ }
+ /** Returns the definition. */
+ @Nullable
+ public String definition() {
+ return definition;
+ }
+ /** Returns the synonyms. */
+ public String[] synonyms() {
+ return synonyms.clone();
+ }
+ /** Returns the status. */
+ public Status status() {
+ return status;
+ }
+ /** Returns the links. */
+ public TermLink[] links() {
+ return links.clone();
+ }
+ /** Returns the sourceRef. */
+ @Nullable
+ public String sourceRef() {
+ return sourceRef;
+ }
+ /** Returns the properties. */
+ public Map<String, String> properties() {
+ return properties;
+ }
+ /** Returns the version. */
+ public long version() {
+ return version;
+ }
+ /** Returns the auditInfo. */
+ public Audit auditInfo() {
+ return auditInfo;
+ }
+
+ @Override
+ public EntityType type() {
+ return EntityType.GLOSSARY_TERM;
+ }
+
+ @Override
+ public Map<Field, Object> fields() {
+ Map<Field, Object> values = new LinkedHashMap<>();
+ values.put(ID, id);
+ values.put(NAME, name);
+ values.put(DEFINITION, definition);
+ values.put(SYNONYMS, synonyms.clone());
+ values.put(STATUS, status);
+ values.put(LINKS, links.clone());
+ values.put(SOURCE_REF, sourceRef);
+ values.put(PROPERTIES, properties);
+ values.put(VERSION, version);
+ values.put(AUDIT_INFO, auditInfo);
+ return Collections.unmodifiableMap(values);
+ }
+ /** Returns a definition builder. */
+ public static Builder builder() {
+ return new Builder();
+ }
+ /** Builds a persisted definition without relation projections. */
+ public static final class Builder {
+ private final GlossaryTermEntity value = new GlossaryTermEntity();
+
+ private Builder() {
+ value.synonyms = new String[0];
+ value.links = new TermLink[0];
+ value.status = Status.APPROVED;
+ value.properties = Collections.emptyMap();
+ value.version = 1;
+ }
+ /** Sets the id. */
+ public Builder withId(Long v) {
+ value.id = v;
+ return this;
+ }
+ /** Sets the name. */
+ public Builder withName(String v) {
+ value.name = v;
+ return this;
+ }
+ /** Sets the namespace. */
+ public Builder withNamespace(Namespace v) {
+ value.namespace = v;
+ return this;
+ }
+ /** Sets the definition. */
+ public Builder withDefinition(@Nullable String v) {
+ value.definition = v;
+ return this;
+ }
+ /** Sets the synonyms. */
+ public Builder withSynonyms(String[] v) {
+ Preconditions.checkArgument(v != null, "synonyms cannot be null");
+ value.synonyms = v.clone();
+ return this;
+ }
+ /** Sets the status. */
+ public Builder withStatus(Status v) {
+ value.status = v;
+ return this;
+ }
+ /**
+ * Sets the links.
+ *
+ * @throws IllegalArgumentException if the array or any link is null
+ */
+ public Builder withLinks(TermLink[] v) {
+ Preconditions.checkArgument(v != null, "links cannot be null");
+ TermLink[] links = v.clone();
+ for (int i = 0; i < links.length; i++) {
+ Preconditions.checkArgument(links[i] != null, "links[%s] cannot be
null", i);
+ }
+ value.links = links;
+ return this;
+ }
+ /** Sets the sourceRef. */
+ public Builder withSourceRef(@Nullable String v) {
+ value.sourceRef = v;
+ return this;
+ }
+ /** Sets the properties. */
+ public Builder withProperties(Map<String, String> v) {
+ Preconditions.checkArgument(v != null, "properties cannot be null");
+ value.properties = Collections.unmodifiableMap(new LinkedHashMap<>(v));
+ return this;
+ }
+ /** Sets the version. */
+ public Builder withVersion(long v) {
+ value.version = v;
+ return this;
+ }
+ /** Sets the auditInfo. */
+ public Builder withAuditInfo(Audit v) {
+ value.auditInfo = v;
+ return this;
+ }
+ /** Returns the validated definition. */
+ public GlossaryTermEntity build() {
+ Preconditions.checkArgument(value.id != null, "id cannot be null");
+ Preconditions.checkArgument(value.namespace != null, "namespace cannot
be null");
+ Preconditions.checkArgument(value.auditInfo != null, "auditInfo cannot
be null");
+ Preconditions.checkArgument(value.status != null, "status cannot be
null");
+ value.name = GlossaryTermNames.display(value.name);
+ Preconditions.checkArgument(
+ value.namespace.length() == 3
+ &&
value.namespace.level(1).equals(Entity.SYSTEM_CATALOG_RESERVED_NAME)
+ && value.namespace.level(2).equals("glossary_term"),
+ "Expected glossary term namespace");
+ GlossaryTermNames.validate(value.name);
+ Preconditions.checkArgument(value.version >= 1, "Revision must be
positive");
+ Preconditions.checkArgument(value.synonyms.length <= 100, "At most 100
synonyms are allowed");
+ for (int i = 0; i < value.synonyms.length; i++) {
+ value.synonyms[i] = GlossaryTermNames.display(value.synonyms[i]);
+ GlossaryTermNames.validate(value.synonyms[i]);
+ }
+ if (value.sourceRef != null) GlossaryTermNames.validate(value.sourceRef);
+ Preconditions.checkArgument(
+ value.definition == null
+ || value.definition.getBytes(StandardCharsets.UTF_8).length <=
16384,
+ "Definition exceeds 16384 UTF-8 bytes");
+ GlossaryTermEntity copy = new GlossaryTermEntity();
+ copy.id = value.id;
+ copy.name = value.name;
+ copy.namespace = value.namespace;
+ copy.definition = value.definition;
+ copy.synonyms = value.synonyms.clone();
+ copy.status = value.status;
+ copy.links = value.links.clone();
+ copy.sourceRef = value.sourceRef;
+ copy.properties = value.properties;
+ copy.version = value.version;
+ copy.auditInfo = value.auditInfo;
+ return copy;
+ }
+ }
+}
diff --git
a/core/src/main/java/org/apache/gravitino/meta/GlossaryTermNames.java
b/core/src/main/java/org/apache/gravitino/meta/GlossaryTermNames.java
new file mode 100644
index 0000000000..78a2f965c4
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/meta/GlossaryTermNames.java
@@ -0,0 +1,61 @@
+/*
+ * 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 java.util.Locale;
+import java.util.regex.Pattern;
+
+/** Shared normalization for persisted glossary names and synonyms. */
+public final class GlossaryTermNames {
+ private static final Pattern SPACE = Pattern.compile("\\s+",
Pattern.UNICODE_CHARACTER_CLASS);
+
+ private GlossaryTermNames() {}
+ /** Removes surrounding Unicode whitespace while preserving display
spelling. */
+ public static String display(String value) {
+ Preconditions.checkArgument(value != null, "name cannot be null");
+ int start = 0;
+ int end = value.length();
+ while (start < end && isWhitespace(value.codePointAt(start))) {
+ start += Character.charCount(value.codePointAt(start));
+ }
+ while (start < end && isWhitespace(value.codePointBefore(end))) {
+ end -= Character.charCount(value.codePointBefore(end));
+ }
+ return value.substring(start, end);
+ }
+ /** Returns the locale-independent lookup key. */
+ public static String key(String value) {
+ return SPACE.matcher(display(value)).replaceAll("
").toLowerCase(Locale.ROOT);
+ }
+ /** Checks the persisted 128-code-point bound. */
+ public static void validate(String value) {
+ Preconditions.checkArgument(
+ !key(value).isEmpty() && value.codePointCount(0, value.length()) <=
128,
+ "Glossary name or source reference must contain 1 to 128 code points");
+ }
+
+ private static boolean isWhitespace(int codePoint) {
+ // Match Unicode White_Space, including NEL and non-breaking spaces, as
(?U)\\s does.
+ return codePoint >= 0x09 && codePoint <= 0x0D
+ || codePoint == 0x85
+ || Character.isSpaceChar(codePoint);
+ }
+}
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 dcdb2c4621..f30925ecf3 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
@@ -61,6 +61,7 @@ import org.apache.gravitino.meta.DomainEntity;
import org.apache.gravitino.meta.FilesetEntity;
import org.apache.gravitino.meta.FunctionEntity;
import org.apache.gravitino.meta.GenericEntity;
+import org.apache.gravitino.meta.GlossaryTermEntity;
import org.apache.gravitino.meta.GroupEntity;
import org.apache.gravitino.meta.JobEntity;
import org.apache.gravitino.meta.JobTemplateEntity;
@@ -85,6 +86,7 @@ import
org.apache.gravitino.storage.relational.service.DomainMetaService;
import org.apache.gravitino.storage.relational.service.DomainRelService;
import org.apache.gravitino.storage.relational.service.FilesetMetaService;
import org.apache.gravitino.storage.relational.service.FunctionMetaService;
+import org.apache.gravitino.storage.relational.service.GlossaryTermMetaService;
import org.apache.gravitino.storage.relational.service.GroupMetaService;
import org.apache.gravitino.storage.relational.service.JobMetaService;
import org.apache.gravitino.storage.relational.service.JobTemplateMetaService;
@@ -174,6 +176,8 @@ public class JDBCBackend implements RelationalBackend,
SupportsOrphanedRelationC
return (List<E>)
FilesetMetaService.getInstance().listFilesetsByNamespace(namespace);
case TOPIC:
return (List<E>)
TopicMetaService.getInstance().listTopicsByNamespace(namespace);
+ case GLOSSARY_TERM:
+ return (List<E>) GlossaryTermMetaService.getInstance().list(namespace);
case TAG:
return (List<E>)
TagMetaService.getInstance().listTagsByNamespace(namespace);
case USER:
@@ -297,6 +301,8 @@ public class JDBCBackend implements RelationalBackend,
SupportsOrphanedRelationC
return (E) GroupMetaService.getInstance().getGroupByIdentifier(ident);
case ROLE:
return (E) RoleMetaService.getInstance().getRoleByIdentifier(ident);
+ case GLOSSARY_TERM:
+ return (E) GlossaryTermMetaService.getInstance().get(ident);
case TAG:
return (E) TagMetaService.getInstance().getTagByIdentifier(ident);
case MODEL:
@@ -352,6 +358,8 @@ public class JDBCBackend implements RelationalBackend,
SupportsOrphanedRelationC
return (List<E>)
TopicMetaService.getInstance().batchGetTopicByIdentifier(identifiers);
case MODEL:
return (List<E>)
ModelMetaService.getInstance().batchGetModelByIdentifier(identifiers);
+ case GLOSSARY_TERM:
+ return (List<E>)
GlossaryTermMetaService.getInstance().batchGet(identifiers);
case TAG:
return (List<E>)
TagMetaService.getInstance().batchGetTagByIdentifier(identifiers);
case POLICY:
@@ -512,6 +520,9 @@ public class JDBCBackend implements RelationalBackend,
SupportsOrphanedRelationC
return RoleMetaService.getInstance()
.deleteRoleMetasByLegacyTimeline(
legacyTimeline, GARBAGE_COLLECTOR_SINGLE_DELETION_LIMIT);
+ case GLOSSARY_TERM:
+ return GlossaryTermMetaService.getInstance()
+ .collect(legacyTimeline, GARBAGE_COLLECTOR_SINGLE_DELETION_LIMIT);
case TAG:
return TagMetaService.getInstance()
.deleteTagMetasByLegacyTimeline(
@@ -596,6 +607,7 @@ public class JDBCBackend implements RelationalBackend,
SupportsOrphanedRelationC
case JOB:
case VIEW:
case DOMAIN:
+ case GLOSSARY_TERM:
// These entity types have not implemented multi-versions, so we can
skip.
return 0;
@@ -1160,6 +1172,8 @@ public class JDBCBackend implements RelationalBackend,
SupportsOrphanedRelationC
RoleMetaService.getInstance().insertRole((RoleEntity) e, overwritten);
} else if (e instanceof GroupEntity) {
GroupMetaService.getInstance().insertGroup((GroupEntity) e, overwritten);
+ } else if (e instanceof GlossaryTermEntity) {
+ GlossaryTermMetaService.getInstance().insert((GlossaryTermEntity) e,
overwritten);
} else if (e instanceof TagEntity) {
TagMetaService.getInstance().insertTag((TagEntity) e, overwritten);
} else if (e instanceof ModelEntity) {
@@ -1218,6 +1232,8 @@ public class JDBCBackend implements RelationalBackend,
SupportsOrphanedRelationC
return (E) GroupMetaService.getInstance().updateGroup(ident, updater);
case ROLE:
return (E) RoleMetaService.getInstance().updateRole(ident, updater);
+ case GLOSSARY_TERM:
+ return (E) GlossaryTermMetaService.getInstance().update(ident,
updater);
case TAG:
return (E) TagMetaService.getInstance().updateTag(ident, updater);
case MODEL:
@@ -1265,6 +1281,8 @@ public class JDBCBackend implements RelationalBackend,
SupportsOrphanedRelationC
return GroupMetaService.getInstance().deleteGroup(ident);
case ROLE:
return RoleMetaService.getInstance().deleteRole(ident);
+ case GLOSSARY_TERM:
+ return GlossaryTermMetaService.getInstance().delete(ident);
case TAG:
return TagMetaService.getInstance().deleteTag(ident);
case MODEL:
diff --git
a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
index 8c73c653cd..fa91f6b307 100644
---
a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
+++
b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalEntityStore.java
@@ -271,6 +271,9 @@ public class RelationalEntityStore
@Override
public boolean exists(NameIdentifier ident, Entity.EntityType entityType)
throws IOException {
+ if (entityType == Entity.EntityType.GLOSSARY_TERM) {
+ return backend.exists(ident, entityType);
+ }
boolean existsInCache = cache.contains(ident, entityType);
return existsInCache || backend.exists(ident, entityType);
}
@@ -312,6 +315,9 @@ public class RelationalEntityStore
public <E extends Entity & HasIdentifier> E get(
NameIdentifier ident, Entity.EntityType entityType, Class<E> e)
throws NoSuchEntityException, IOException {
+ if (entityType == Entity.EntityType.GLOSSARY_TERM) {
+ return backend.get(ident, entityType);
+ }
return cache.withCacheLock(
EntityCacheKey.of(ident, entityType),
() -> {
@@ -331,6 +337,9 @@ public class RelationalEntityStore
@Override
public <E extends Entity & HasIdentifier> List<E> batchGet(
List<NameIdentifier> idents, Entity.EntityType entityType, Class<E>
clazz) {
+ if (entityType == Entity.EntityType.GLOSSARY_TERM) {
+ return backend.batchGet(idents, entityType);
+ }
List<E> allEntities = new ArrayList<>();
List<NameIdentifier> noCacheIdents =
idents.stream()
@@ -836,6 +845,9 @@ public class RelationalEntityStore
}
private <E extends Entity & HasIdentifier> void cacheIfEpochUnchanged(E
entity, long epoch) {
+ if (entity.type() == Entity.EntityType.GLOSSARY_TERM) {
+ return;
+ }
if (cache instanceof BaseEntityCache &&
!BaseEntityCache.isCacheable(entity.type())) {
// Uncached entities still invoke the cache's related-invalidation hook.
There is no stale
// value to publish, and taking this entity's key lock can nest locks
inside that hook.
@@ -849,6 +861,9 @@ public class RelationalEntityStore
// The caller holds the entry's cache lock; do not acquire it again here.
private <E extends Entity & HasIdentifier> void publishIfEpochUnchanged(E
entity, long epoch) {
+ if (entity.type() == Entity.EntityType.GLOSSARY_TERM) {
+ return;
+ }
if (cache instanceof BaseEntityCache &&
!BaseEntityCache.isCacheable(entity.type())) {
cache.put(entity);
return;
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 2bb8a96553..8c067c5c03 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
@@ -31,6 +31,7 @@ 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.GlossaryTermMetaService;
import org.apache.gravitino.storage.relational.service.GroupMetaService;
import org.apache.gravitino.storage.relational.service.JobTemplateMetaService;
import org.apache.gravitino.storage.relational.service.MetalakeMetaService;
@@ -58,7 +59,8 @@ public class RelationalEntityStoreIdResolver implements
EntityIdResolver {
Entity.EntityType.POLICY,
Entity.EntityType.JOB,
Entity.EntityType.JOB_TEMPLATE,
- Entity.EntityType.DOMAIN);
+ Entity.EntityType.DOMAIN,
+ Entity.EntityType.GLOSSARY_TERM);
private static final Set<Entity.EntityType>
ENTITY_TYPES_REQUIRING_CATALOG_IDS =
ImmutableSet.of(Entity.EntityType.CATALOG);
@@ -118,6 +120,9 @@ public class RelationalEntityStoreIdResolver implements
EntityIdResolver {
private NamespacedEntityId getEntityIdsRequiringMetalakeId(
NameIdentifier nameIdentifier, Entity.EntityType type) {
+ if (type == Entity.EntityType.GLOSSARY_TERM) {
+ return GlossaryTermMetaService.getInstance().getIds(nameIdentifier);
+ }
long metalakeId =
MetalakeMetaService.getInstance()
.getMetalakeIdByName(NameIdentifierUtil.getMetalake(nameIdentifier));
diff --git
a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/GlossaryTermMetaMapper.java
b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/GlossaryTermMetaMapper.java
new file mode 100644
index 0000000000..a1bda07fd9
--- /dev/null
+++
b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/GlossaryTermMetaMapper.java
@@ -0,0 +1,95 @@
+/*
+ * 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 javax.annotation.Nullable;
+import
org.apache.gravitino.storage.relational.mapper.provider.base.GlossaryTermSQLProvider;
+import org.apache.gravitino.storage.relational.po.GlossaryTermPO;
+import org.apache.gravitino.storage.relational.po.GlossaryTermSnapshotPO;
+import org.apache.ibatis.annotations.DeleteProvider;
+import org.apache.ibatis.annotations.InsertProvider;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.SelectProvider;
+import org.apache.ibatis.annotations.UpdateProvider;
+
+/** Glossary definition and synonym persistence in the caller transaction. */
+public interface GlossaryTermMetaMapper {
+ /** Locks the live definition, or returns null; the caller must fence its
metalake first. */
+ @Nullable
+ @SelectProvider(type = GlossaryTermSQLProvider.class, method =
"getForUpdate")
+ GlossaryTermPO getForUpdate(@Param("metalakeId") long metalakeId,
@Param("key") String key);
+
+ /** Returns only term/metalake IDs, or null if the term or requested parent
name is absent. */
+ @Nullable
+ @SelectProvider(type = GlossaryTermSQLProvider.class, method = "getIds")
+ GlossaryTermPO getIds(
+ @Param("metalakeId") long metalakeId,
+ @Param("metalakeName") String metalakeName,
+ @Param("key") String key);
+
+ /** Executes insert within the current transaction. */
+ @InsertProvider(type = GlossaryTermSQLProvider.class, method = "insert")
+ void insert(@Param("p") GlossaryTermPO p);
+ /** Executes update within the current transaction. */
+ @UpdateProvider(type = GlossaryTermSQLProvider.class, method = "update")
+ int update(@Param("p") GlossaryTermPO p, @Param("version") long version);
+ /** Executes synonyms within the current transaction. */
+ @SelectProvider(type = GlossaryTermSQLProvider.class, method = "synonyms")
+ List<String> synonyms(@Param("id") long id);
+ /** Executes addSynonym within the current transaction. */
+ @InsertProvider(type = GlossaryTermSQLProvider.class, method = "addSynonym")
+ void addSynonym(
+ @Param("id") long id,
+ @Param("metalakeId") long metalakeId,
+ @Param("synonym") String synonym,
+ @Param("key") String key);
+ /** Executes clearSynonyms within the current transaction. */
+ @DeleteProvider(type = GlossaryTermSQLProvider.class, method =
"clearSynonyms")
+ void clearSynonyms(@Param("id") long id);
+ /** Executes delete within the current transaction. */
+ @UpdateProvider(type = GlossaryTermSQLProvider.class, method = "delete")
+ int delete(
+ @Param("id") long id, @Param("version") long version,
@Param("deletedAt") long deletedAt);
+ /** Executes deleteSynonyms within the current transaction. */
+ @UpdateProvider(type = GlossaryTermSQLProvider.class, method =
"deleteSynonyms")
+ void deleteSynonyms(@Param("id") long id, @Param("deletedAt") long
deletedAt);
+ /** Executes dropMetalake within the current transaction. */
+ @UpdateProvider(type = GlossaryTermSQLProvider.class, method =
"dropMetalake")
+ void dropMetalake(@Param("id") long id, @Param("deletedAt") long deletedAt);
+ /** Executes dropMetalakeSynonyms within the current transaction. */
+ @UpdateProvider(type = GlossaryTermSQLProvider.class, method =
"dropMetalakeSynonyms")
+ void dropMetalakeSynonyms(@Param("id") long id, @Param("deletedAt") long
deletedAt);
+ /** Executes expired within the current transaction. */
+ @SelectProvider(type = GlossaryTermSQLProvider.class, method = "expired")
+ List<Long> expired(@Param("cutoff") long cutoff, @Param("limit") int limit);
+ /** Executes purgeSynonyms within the current transaction. */
+ @DeleteProvider(type = GlossaryTermSQLProvider.class, method =
"purgeSynonyms")
+ void purgeSynonyms(@Param("id") long id);
+ /** Executes purge within the current transaction. */
+ @DeleteProvider(type = GlossaryTermSQLProvider.class, method = "purge")
+ int purge(@Param("id") long id);
+ /** Reads definitions, synonyms and the live parent name in one snapshot
without row locks. */
+ @SelectProvider(type = GlossaryTermSQLProvider.class, method = "snapshot")
+ List<GlossaryTermSnapshotPO> snapshot(
+ @Param("metalakeId") long metalakeId,
+ @Param("metalakeName") String metalakeName,
+ @Param("key") @Nullable String key);
+}
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 cd7914c040..0cd1ee0e2b 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
@@ -28,6 +28,7 @@ import
org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
import org.apache.gravitino.storage.relational.mapper.FilesetVersionMapper;
import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
import
org.apache.gravitino.storage.relational.mapper.FunctionVersionMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.GlossaryTermMetaMapper;
import org.apache.gravitino.storage.relational.mapper.GroupMetaMapper;
import org.apache.gravitino.storage.relational.mapper.GroupRoleRelMapper;
import org.apache.gravitino.storage.relational.mapper.JobMetaMapper;
@@ -101,6 +102,7 @@ public class DefaultMapperPackageProvider implements
MapperPackageProvider {
TableMetaMapper.class,
TagMetadataObjectRelMapper.class,
TagMetaMapper.class,
+ GlossaryTermMetaMapper.class,
TopicMetaMapper.class,
UserMetaMapper.class,
UserRoleRelMapper.class,
diff --git
a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/GlossaryTermSQLProvider.java
b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/GlossaryTermSQLProvider.java
new file mode 100644
index 0000000000..7440e1cc54
--- /dev/null
+++
b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/GlossaryTermSQLProvider.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.storage.relational.mapper.provider.base;
+
+import java.util.Map;
+
+/** Portable SQL for glossary definitions and synonyms on H2, MySQL and
PostgreSQL. */
+public final class GlossaryTermSQLProvider {
+ private static final String LIVE_METALAKE_JOIN =
+ " JOIN metalake_meta m ON m.metalake_id=t.metalake_id "
+ + "AND m.metalake_name=#{metalakeName} AND m.deleted_at=0 ";
+
+ /** Locks a definition after the caller has fenced its metalake. */
+ public static String getForUpdate() {
+ return "SELECT term_id AS termId, name AS name, name_key AS nameKey,
metalake_id AS "
+ + "metalakeId, definition AS definition, status AS status, links AS
links, source_ref AS "
+ + "sourceRef, properties AS properties, audit_info AS auditInfo,
current_version AS "
+ + "currentVersion, deleted_at AS deletedAt FROM glossary_term_meta
WHERE metalake_id = "
+ + "#{metalakeId} AND name_key = #{key} AND deleted_at=0 FOR UPDATE";
+ }
+ /** Resolves IDs only while the parent still has the requested live name. */
+ public static String getIds() {
+ return "SELECT t.term_id AS termId, t.metalake_id AS metalakeId FROM
glossary_term_meta t"
+ + LIVE_METALAKE_JOIN
+ + "WHERE t.metalake_id=#{metalakeId} AND t.name_key=#{key} AND
t.deleted_at=0";
+ }
+
+ /** Returns SQL for insert. */
+ public static String insert() {
+ return "INSERT INTO glossary_term_meta (term_id, name, name_key,
metalake_id, definition, "
+ + "status, links, source_ref, properties, audit_info, current_version,
deleted_at) "
+ + "VALUES (#{p.termId}, #{p.name}, #{p.nameKey}, #{p.metalakeId},
#{p.definition}, "
+ + "#{p.status}, #{p.links}, #{p.sourceRef}, #{p.properties},
#{p.auditInfo}, "
+ + "#{p.currentVersion}, #{p.deletedAt})";
+ }
+ /** Returns SQL for update. */
+ public static String update() {
+ return "UPDATE glossary_term_meta SET name=#{p.name},
name_key=#{p.nameKey}, "
+ + "definition=#{p.definition}, status=#{p.status}, links=#{p.links}, "
+ + "source_ref=#{p.sourceRef}, properties=#{p.properties},
audit_info=#{p.auditInfo}, "
+ + "current_version=#{p.currentVersion} WHERE term_id=#{p.termId} AND "
+ + "metalake_id=#{p.metalakeId} AND current_version=#{version} AND
deleted_at=0";
+ }
+ /** Returns SQL for synonyms. */
+ public static String synonyms() {
+ return "SELECT synonym FROM glossary_term_synonym WHERE term_id=#{id} AND
deleted_at=0 ORDER "
+ + "BY synonym_key";
+ }
+ /** Returns SQL for addSynonym. */
+ public static String addSynonym() {
+ return "INSERT INTO glossary_term_synonym (term_id, metalake_id, synonym,
synonym_key, "
+ + "deleted_at) VALUES (#{id},#{metalakeId},#{synonym},#{key},0)";
+ }
+ /** Returns SQL for clearSynonyms. */
+ public static String clearSynonyms() {
+ return "DELETE FROM glossary_term_synonym WHERE term_id=#{id} AND
deleted_at=0";
+ }
+ /** Returns SQL for delete. */
+ public static String delete() {
+ return "UPDATE glossary_term_meta SET deleted_at=#{deletedAt} WHERE
term_id=#{id} AND "
+ + "current_version=#{version} AND deleted_at=0";
+ }
+ /** Returns SQL for deleteSynonyms. */
+ public static String deleteSynonyms() {
+ return "UPDATE glossary_term_synonym SET deleted_at=#{deletedAt} WHERE
term_id=#{id} AND "
+ + "deleted_at=0";
+ }
+ /** Returns SQL for dropMetalake. */
+ public static String dropMetalake() {
+ return "UPDATE glossary_term_meta SET deleted_at=#{deletedAt} WHERE
metalake_id=#{id} AND "
+ + "deleted_at=0";
+ }
+ /** Returns SQL for dropMetalakeSynonyms. */
+ public static String dropMetalakeSynonyms() {
+ return "UPDATE glossary_term_synonym SET deleted_at=#{deletedAt} WHERE
metalake_id=#{id} AND "
+ + "deleted_at=0";
+ }
+ /** Returns SQL for expired. */
+ public static String expired() {
+ return "SELECT term_id FROM glossary_term_meta WHERE deleted_at>0 AND
deleted_at<#{cutoff} "
+ + "ORDER BY term_id LIMIT #{limit}";
+ }
+ /** Returns SQL for purgeSynonyms. */
+ public static String purgeSynonyms() {
+ return "DELETE FROM glossary_term_synonym WHERE term_id=#{id} AND
deleted_at>0";
+ }
+ /** Returns SQL for purge. */
+ public static String purge() {
+ return "DELETE FROM glossary_term_meta WHERE term_id=#{id} AND
deleted_at>0";
+ }
+ /** Reads definitions and synonyms together, including definitions without
synonyms. */
+ public static String snapshot(Map<String, Object> params) {
+ // Validate the parent name in this snapshot too: it can be renamed after
ID resolution.
+ // A single statement avoids mixed revisions at READ_COMMITTED without
locking readers.
+ return "SELECT t.term_id AS termId, t.name AS name, t.name_key AS nameKey,
"
+ + "t.metalake_id AS metalakeId, t.definition AS definition, t.status
AS status, "
+ + "t.links AS links, t.source_ref AS sourceRef, t.properties AS
properties, "
+ + "t.audit_info AS auditInfo, t.current_version AS currentVersion, "
+ + "t.deleted_at AS deletedAt, s.synonym AS synonym FROM
glossary_term_meta t"
+ + LIVE_METALAKE_JOIN
+ + "LEFT JOIN glossary_term_synonym s ON s.term_id=t.term_id "
+ + "AND s.metalake_id=t.metalake_id AND s.deleted_at=0 "
+ + "WHERE t.metalake_id=#{metalakeId} AND t.deleted_at=0"
+ + (params.get("key") == null ? "" : " AND t.name_key=#{key}")
+ + " ORDER BY t.term_id,s.synonym_key";
+ }
+}
diff --git
a/core/src/main/java/org/apache/gravitino/storage/relational/po/GlossaryTermPO.java
b/core/src/main/java/org/apache/gravitino/storage/relational/po/GlossaryTermPO.java
new file mode 100644
index 0000000000..dc70b33010
--- /dev/null
+++
b/core/src/main/java/org/apache/gravitino/storage/relational/po/GlossaryTermPO.java
@@ -0,0 +1,41 @@
+/*
+ * 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 lombok.Getter;
+import lombok.Setter;
+
+/** Persistent glossary definition row. */
+@Getter
+@Setter
+public class GlossaryTermPO {
+ private Long termId;
+ private String name;
+ private String nameKey;
+ private Long metalakeId;
+ private String definition;
+ private String status;
+ private String links;
+ private String sourceRef;
+ private String properties;
+ private String auditInfo;
+ private Long currentVersion;
+ private Long deletedAt;
+}
diff --git
a/core/src/main/java/org/apache/gravitino/storage/relational/po/GlossaryTermSnapshotPO.java
b/core/src/main/java/org/apache/gravitino/storage/relational/po/GlossaryTermSnapshotPO.java
new file mode 100644
index 0000000000..1f3d9f1549
--- /dev/null
+++
b/core/src/main/java/org/apache/gravitino/storage/relational/po/GlossaryTermSnapshotPO.java
@@ -0,0 +1,31 @@
+/*
+ * 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 javax.annotation.Nullable;
+import lombok.Getter;
+import lombok.Setter;
+
+/** One row of a definition/synonym snapshot; synonym is null for terms
without synonyms. */
+@Getter
+@Setter
+public class GlossaryTermSnapshotPO extends GlossaryTermPO {
+ @Nullable private String synonym;
+}
diff --git
a/core/src/main/java/org/apache/gravitino/storage/relational/service/GlossaryTermMetaService.java
b/core/src/main/java/org/apache/gravitino/storage/relational/service/GlossaryTermMetaService.java
new file mode 100644
index 0000000000..0b933e4b9a
--- /dev/null
+++
b/core/src/main/java/org/apache/gravitino/storage/relational/service/GlossaryTermMetaService.java
@@ -0,0 +1,389 @@
+/*
+ * 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.fasterxml.jackson.core.type.TypeReference;
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import javax.annotation.Nullable;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.glossary.GlossaryTerm.Status;
+import org.apache.gravitino.glossary.TermLink;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GlossaryTermEntity;
+import org.apache.gravitino.meta.GlossaryTermNames;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.storage.relational.mapper.GlossaryTermMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
+import org.apache.gravitino.storage.relational.po.GlossaryTermPO;
+import org.apache.gravitino.storage.relational.po.GlossaryTermSnapshotPO;
+import org.apache.gravitino.storage.relational.po.MetalakePO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+
+/**
+ * Transactional persistence of glossary definitions and their synonyms.
+ *
+ * <p>Operations join an existing SessionUtils transaction or commit their
own. Missing definitions
+ * throw NoSuchEntityException, except delete (false) and batchGet (omitted).
Duplicate names,
+ * source references and reserved IDs are translated to
EntityAlreadyExistsException. Other database
+ * failures propagate through the existing store exception converter.
+ *
+ * <p>Namespace-based operations reject namespaces other than {@code
+ * <metalake>.system.glossary_term} with IllegalArgumentException before
accessing storage.
+ *
+ * <p>Insert starts at revision 1; update and overwrite increment the stored
revision once. Callers
+ * must detect semantic no-ops before invoking a write. Relation validation,
authorization and the
+ * name-versus-synonym checks belong to the glossary manager, not this
persistence service. Shared
+ * synonyms across terms are allowed. Name/synonym conflicts are not rejected
here, even for
+ * sequential writes; the parent lock and database unique keys do not enforce
that cross-table rule.
+ * Before exposing manager/API writes, the manager must take the per-metalake
hierarchy lock, read
+ * fresh state, and check conflicts in both directions. It must keep that lock
through commit in the
+ * same transaction for create, rename, overwrite and synonym changes. Reads
use a single statement
+ * snapshot for definitions, synonyms and the live parent name without taking
row locks.
+ */
+public final class GlossaryTermMetaService {
+ private static final GlossaryTermMetaService INSTANCE = new
GlossaryTermMetaService();
+
+ private GlossaryTermMetaService() {}
+ /** Returns the shared service. */
+ public static GlossaryTermMetaService getInstance() {
+ return INSTANCE;
+ }
+
+ /**
+ * Inserts a definition, or overwrites the same identity and increments its
revision.
+ *
+ * @throws IllegalArgumentException if overwrite finds the name with a
different entity ID; load
+ * the existing entity and use its ID before overwriting
+ */
+ public void insert(GlossaryTermEntity entity, boolean overwritten) throws
IOException {
+ try {
+ transaction(
+ entity.namespace(),
+ (mapper, metalakeId) -> {
+ GlossaryTermPO old =
+ mapper.getForUpdate(metalakeId,
GlossaryTermNames.key(entity.name()));
+ GlossaryTermPO row = toPO(entity, metalakeId);
+ if (overwritten && old != null) {
+ Preconditions.checkArgument(
+ Objects.equals(old.getTermId(), entity.id()),
+ "Cannot overwrite glossary term %s with ID %s; load and
retain existing ID %s",
+ entity.nameIdentifier(),
+ entity.id(),
+ old.getTermId());
+ row.setCurrentVersion(Math.addExact(old.getCurrentVersion(), 1));
+ requireUpdated(mapper.update(row, old.getCurrentVersion()),
entity.nameIdentifier());
+ mapper.clearSynonyms(row.getTermId());
+ } else {
+ row.setCurrentVersion(1L);
+ mapper.insert(row);
+ }
+ writeSynonyms(mapper, row, entity.synonyms());
+ return null;
+ });
+ } catch (RuntimeException e) {
+ ExceptionUtils.checkSQLException(
+ e, Entity.EntityType.GLOSSARY_TERM,
entity.nameIdentifier().toString());
+ throw e;
+ }
+ }
+
+ /** Loads a definition and its synonyms from one statement snapshot without
row locks. */
+ public GlossaryTermEntity get(NameIdentifier ident) {
+ List<GlossaryTermEntity> terms = read(ident.namespace(),
GlossaryTermNames.key(ident.name()));
+ if (terms.isEmpty()) {
+ throw new NoSuchEntityException("Glossary term %s does not exist",
ident);
+ }
+ return terms.get(0);
+ }
+
+ /** Resolves term and metalake identities without row locks. */
+ public NamespacedEntityId getIds(NameIdentifier ident) {
+ validateNamespace(ident.namespace());
+ return SessionUtils.getWithoutCommit(
+ GlossaryTermMetaMapper.class,
+ mapper -> {
+ long metalakeId = metalake(ident.namespace()).getMetalakeId();
+ GlossaryTermPO row =
+ mapper.getIds(
+ metalakeId, ident.namespace().level(0),
GlossaryTermNames.key(ident.name()));
+ if (row == null) {
+ throw new NoSuchEntityException("Glossary term %s does not exist",
ident);
+ }
+ return new NamespacedEntityId(row.getTermId(), row.getMetalakeId());
+ });
+ }
+
+ /** Lists definitions and synonyms from one statement snapshot without row
locks. */
+ public List<GlossaryTermEntity> list(Namespace ns) {
+ return read(ns, null);
+ }
+
+ /**
+ * Loads requested terms, omitting missing names.
+ *
+ * <p>Like the existing user/role fallback, this accepts identifiers from
different metalakes and
+ * performs a snapshot read per identifier. Use list for a complete
metalake: it reads definitions
+ * and synonyms together without issuing a query per returned term.
+ */
+ public List<GlossaryTermEntity> batchGet(List<NameIdentifier> identifiers) {
+ List<GlossaryTermEntity> result = new ArrayList<>();
+ for (NameIdentifier ident : identifiers) {
+ try {
+ result.add(get(ident));
+ } catch (NoSuchEntityException ignored) {
+ /* Missing entries are omitted. */
+ }
+ }
+ return result;
+ }
+
+ /** Updates one definition atomically with its synonyms, preserving its
identity and namespace. */
+ public <E extends Entity & HasIdentifier> GlossaryTermEntity update(
+ NameIdentifier ident, Function<E, E> updater) throws IOException {
+ try {
+ return transaction(
+ ident.namespace(),
+ (mapper, metalakeId) -> {
+ GlossaryTermPO old = require(mapper, ident, metalakeId);
+ GlossaryTermEntity updated =
+ (GlossaryTermEntity) updater.apply((E) fromPO(old, mapper,
ident.namespace()));
+ Preconditions.checkArgument(
+ Objects.equals(old.getTermId(), updated.id())
+ && ident.namespace().equals(updated.namespace()),
+ "A glossary update must retain identity and namespace");
+ GlossaryTermPO row = toPO(updated, old.getMetalakeId());
+ row.setCurrentVersion(Math.addExact(old.getCurrentVersion(), 1));
+ requireUpdated(mapper.update(row, old.getCurrentVersion()), ident);
+ mapper.clearSynonyms(row.getTermId());
+ writeSynonyms(mapper, row, updated.synonyms());
+ return fromPO(row, mapper, ident.namespace());
+ });
+ } catch (RuntimeException e) {
+ ExceptionUtils.checkSQLException(e, Entity.EntityType.GLOSSARY_TERM,
ident.toString());
+ throw e;
+ }
+ }
+
+ /** Soft-deletes a definition and all its synonyms; a missing definition
returns false. */
+ public boolean delete(NameIdentifier ident) {
+ try {
+ return transaction(
+ ident.namespace(),
+ (mapper, metalakeId) -> {
+ GlossaryTermPO row = require(mapper, ident, metalakeId);
+ long deletedAt = Math.max(1, System.currentTimeMillis());
+ requireUpdated(
+ mapper.delete(row.getTermId(), row.getCurrentVersion(),
deletedAt), ident);
+ mapper.deleteSynonyms(row.getTermId(), deletedAt);
+ return true;
+ });
+ } catch (NoSuchEntityException e) {
+ return false;
+ }
+ }
+
+ /** Soft-deletes definitions and synonyms inside the metalake deletion
transaction. */
+ public void dropMetalake(long metalakeId) {
+ long deletedAt = Math.max(1, System.currentTimeMillis());
+ SessionUtils.doWithoutCommit(
+ GlossaryTermMetaMapper.class,
+ mapper -> {
+ mapper.dropMetalake(metalakeId, deletedAt);
+ mapper.dropMetalakeSynonyms(metalakeId, deletedAt);
+ });
+ }
+
+ /** Purges at most limit expired definitions and their deleted synonyms
atomically. */
+ public int collect(long cutoff, int limit) {
+ return SessionUtils.doWithCommitAndFetchResult(
+ GlossaryTermMetaMapper.class,
+ mapper -> {
+ int count = 0;
+ for (Long id : mapper.expired(cutoff, limit)) {
+ mapper.purgeSynonyms(id);
+ count += mapper.purge(id);
+ }
+ return count;
+ });
+ }
+
+ private void validateNamespace(Namespace ns) {
+ Preconditions.checkArgument(
+ ns != null
+ && ns.length() == 3
+ && Entity.SYSTEM_CATALOG_RESERVED_NAME.equals(ns.level(1))
+ && "glossary_term".equals(ns.level(2)),
+ "Expected glossary term namespace: %s",
+ ns);
+ }
+
+ private <T> T transaction(Namespace ns, BiFunction<GlossaryTermMetaMapper,
Long, T> work) {
+ validateNamespace(ns);
+ return SessionUtils.doWithCommitAndFetchResult(
+ GlossaryTermMetaMapper.class,
+ mapper -> {
+ MetalakePO observed = metalake(ns);
+ // Fence metalake deletion; definition row locks keep the root and
synonyms consistent.
+ // MySQL/PostgreSQL share the parent lock across terms. H2 uses an
exclusive parent
+ // lock instead, serializing operations within a metalake. This is
not the glossary
+ // hierarchy mutex: a caller's name/synonym precheck before this
lock can become stale,
+ // even on H2. The manager must perform that check under the
dedicated hierarchy mutex
+ // in this same transaction; making only this parent lock exclusive
is insufficient.
+ MetalakePO locked =
+ SessionUtils.getWithoutCommit(
+ MetalakeMetaMapper.class,
+ m ->
m.selectMetalakeMetaByIdForShare(observed.getMetalakeId()));
+ if (locked == null || !Objects.equals(locked.getMetalakeName(),
ns.level(0)))
+ throw new NoSuchEntityException("Metalake %s no longer exists",
ns.level(0));
+ SessionUtils.clearSessionCache();
+ return work.apply(mapper, locked.getMetalakeId());
+ });
+ }
+
+ private List<GlossaryTermEntity> read(Namespace ns, @Nullable String key) {
+ validateNamespace(ns);
+ return SessionUtils.getWithoutCommit(
+ GlossaryTermMetaMapper.class,
+ mapper -> {
+ List<GlossaryTermSnapshotPO> rows =
+ mapper.snapshot(metalake(ns).getMetalakeId(), ns.level(0), key);
+ Map<Long, GlossaryTermPO> definitions = new LinkedHashMap<>();
+ Map<Long, List<String>> synonyms = new LinkedHashMap<>();
+ for (GlossaryTermSnapshotPO row : rows) {
+ definitions.putIfAbsent(row.getTermId(), row);
+ List<String> values =
+ synonyms.computeIfAbsent(row.getTermId(), ignored -> new
ArrayList<>());
+ if (row.getSynonym() != null) {
+ values.add(row.getSynonym());
+ }
+ }
+ List<GlossaryTermEntity> result = new ArrayList<>();
+ definitions.forEach((id, row) -> result.add(fromPO(row,
synonyms.get(id), ns)));
+ return result;
+ });
+ }
+
+ private MetalakePO metalake(Namespace ns) {
+ return
MetalakeMetaService.getInstance().requireMetalakeByName(ns.level(0));
+ }
+
+ private GlossaryTermPO require(
+ GlossaryTermMetaMapper mapper, NameIdentifier ident, long metalakeId) {
+ GlossaryTermPO row = mapper.getForUpdate(metalakeId,
GlossaryTermNames.key(ident.name()));
+ if (row == null) throw new NoSuchEntityException("Glossary term %s does
not exist", ident);
+ return row;
+ }
+
+ private void requireUpdated(int count, NameIdentifier ident) {
+ if (count != 1)
+ throw
ExceptionUtils.concurrentModification(Entity.EntityType.GLOSSARY_TERM, ident);
+ }
+
+ private void writeSynonyms(GlossaryTermMetaMapper mapper, GlossaryTermPO
row, String[] synonyms) {
+ Map<String, String> unique = new LinkedHashMap<>();
+ for (String synonym : synonyms)
unique.putIfAbsent(GlossaryTermNames.key(synonym), synonym);
+ unique.forEach(
+ (key, value) -> mapper.addSynonym(row.getTermId(),
row.getMetalakeId(), value, key));
+ }
+
+ private GlossaryTermPO toPO(GlossaryTermEntity entity, long metalakeId) {
+ GlossaryTermPO row = new GlossaryTermPO();
+ row.setTermId(entity.id());
+ row.setMetalakeId(metalakeId);
+ row.setName(entity.name());
+ row.setNameKey(GlossaryTermNames.key(entity.name()));
+ row.setDefinition(entity.definition());
+ row.setStatus(entity.status().name());
+ row.setSourceRef(entity.sourceRef());
+ row.setCurrentVersion(entity.version());
+ row.setDeletedAt(0L);
+ row.setLinks(
+ json(
+ Arrays.stream(entity.links())
+ .map(
+ link -> {
+ Map<String, String> fields = new LinkedHashMap<>();
+ fields.put("label", link.label());
+ fields.put("url", link.url());
+ return fields;
+ })
+ .toList()));
+ row.setProperties(json(entity.properties()));
+ row.setAuditInfo(json(entity.auditInfo()));
+ return row;
+ }
+
+ private GlossaryTermEntity fromPO(
+ GlossaryTermPO row, GlossaryTermMetaMapper mapper, Namespace ns) {
+ return fromPO(row, mapper.synonyms(row.getTermId()), ns);
+ }
+
+ private GlossaryTermEntity fromPO(GlossaryTermPO row, List<String> synonyms,
Namespace ns) {
+ try {
+ List<Map<String, String>> links =
+ JsonUtils.anyFieldMapper()
+ .readValue(row.getLinks(), new TypeReference<List<Map<String,
String>>>() {});
+ return GlossaryTermEntity.builder()
+ .withId(row.getTermId())
+ .withNamespace(ns)
+ .withName(row.getName())
+ .withDefinition(row.getDefinition())
+ .withStatus(Status.valueOf(row.getStatus()))
+ .withSourceRef(row.getSourceRef())
+ .withVersion(row.getCurrentVersion())
+ .withSynonyms(synonyms.toArray(new String[0]))
+ .withLinks(
+ links.stream()
+ .map(link -> TermLink.of(link.get("label"), link.get("url")))
+ .toArray(TermLink[]::new))
+ .withProperties(
+ JsonUtils.anyFieldMapper()
+ .readValue(row.getProperties(), new
TypeReference<Map<String, String>>() {}))
+
.withAuditInfo(JsonUtils.anyFieldMapper().readValue(row.getAuditInfo(),
AuditInfo.class))
+ .build();
+ } catch (IOException e) {
+ throw new UncheckedIOException("Cannot decode glossary term " +
row.getTermId(), e);
+ }
+ }
+
+ private String json(Object value) {
+ try {
+ return JsonUtils.anyFieldMapper().writeValueAsString(value);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+}
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 3de63af5fb..bd96bcba37 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
@@ -301,6 +301,7 @@ public class MetalakeMetaService {
SessionUtils.doWithoutCommit(
TagMetaMapper.class,
mapper ->
mapper.softDeleteTagMetasByMetalakeId(metalakeId)),
+ () ->
GlossaryTermMetaService.getInstance().dropMetalake(metalakeId),
() ->
SessionUtils.doWithoutCommit(
PolicyTagRelMapper.class, mapper ->
mapper.softDeleteByMetalakeId(metalakeId)),
@@ -425,6 +426,7 @@ public class MetalakeMetaService {
SessionUtils.doWithoutCommit(
TagMetaMapper.class,
mapper ->
mapper.softDeleteTagMetasByMetalakeId(metalakeId)),
+ () ->
GlossaryTermMetaService.getInstance().dropMetalake(metalakeId),
() ->
SessionUtils.doWithoutCommit(
PolicyTagRelMapper.class, mapper ->
mapper.softDeleteByMetalakeId(metalakeId)),
diff --git
a/core/src/test/java/org/apache/gravitino/meta/TestGlossaryTermEntity.java
b/core/src/test/java/org/apache/gravitino/meta/TestGlossaryTermEntity.java
new file mode 100644
index 0000000000..e51a568f8b
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/meta/TestGlossaryTermEntity.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.meta;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Map;
+import java.util.regex.Pattern;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.glossary.TermLink;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.function.Executable;
+
+/** Tests storage definition bounds and snapshot isolation. */
+public class TestGlossaryTermEntity {
+ private GlossaryTermEntity.Builder builder() {
+ return GlossaryTermEntity.builder()
+ .withId(1L)
+ .withName("term")
+ .withNamespace(Namespace.of("lake",
Entity.SYSTEM_CATALOG_RESERVED_NAME, "glossary_term"))
+ .withAuditInfo(
+
AuditInfo.builder().withCreator("creator").withCreateTime(Instant.EPOCH).build());
+ }
+
+ @Test
+ public void testNullArguments() {
+ assertNullArgument("id", () -> builder().withId(null).build());
+ assertNullArgument("namespace", () ->
builder().withNamespace(null).build());
+ assertNullArgument("auditInfo", () ->
builder().withAuditInfo(null).build());
+ assertNullArgument("status", () -> builder().withStatus(null).build());
+ assertNullArgument("name", () -> builder().withName(null).build());
+ assertNullArgument("synonyms", () -> builder().withSynonyms(null));
+ assertNullArgument("links", () -> builder().withLinks(null));
+ assertNullArgument("links[0]", () -> builder().withLinks(new TermLink[]
{null}));
+ assertNullArgument("properties", () -> builder().withProperties(null));
+ assertNullArgument("name", () -> builder().withSynonyms(new String[]
{null}).build());
+ assertNullArgument("name", () -> GlossaryTermNames.display(null));
+ assertNullArgument("name", () -> GlossaryTermNames.key(null));
+ assertNullArgument("name", () -> GlossaryTermNames.validate(null));
+ Assertions.assertDoesNotThrow(() ->
builder().withDefinition(null).withSourceRef(null).build());
+ }
+
+ @Test
+ public void testBounds() {
+ Assertions.assertDoesNotThrow(
+ () ->
builder().withName("π".repeat(128)).withDefinition("a".repeat(16384)).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () ->
builder().withName("π".repeat(129)).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () ->
builder().withDefinition("η".repeat(5462)).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () ->
builder().withSourceRef("x".repeat(129)).build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> builder().withSynonyms(new
String[101]).build());
+ Assertions.assertThrows(IllegalArgumentException.class, () ->
builder().withName(" ").build());
+ Assertions.assertThrows(IllegalArgumentException.class, () ->
builder().withVersion(0).build());
+ Assertions.assertEquals("active customer", GlossaryTermNames.key("γ
Active\t Customerγ"));
+ }
+
+ @Test
+ public void testLinearDisplayNormalization() {
+ String internal = "a" + " ".repeat(1_000_000) + "b";
+ Assertions.assertTimeoutPreemptively(
+ Duration.ofSeconds(5),
+ () -> {
+ Assertions.assertEquals(internal,
GlossaryTermNames.display(internal));
+ Assertions.assertEquals("a b", GlossaryTermNames.key(internal));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () ->
builder().withName(internal).build());
+ });
+ }
+
+ @Test
+ public void testUnicodeWhitespaceBoundaries() {
+ Pattern whitespace = Pattern.compile("\\s",
Pattern.UNICODE_CHARACTER_CLASS);
+ for (int codePoint = 0; codePoint <= Character.MAX_CODE_POINT;
codePoint++) {
+ String boundary = new String(Character.toChars(codePoint));
+ String value = boundary + "πa" + boundary;
+ boolean matches = whitespace.matcher(boundary).matches();
+ Assertions.assertEquals(
+ matches ? "πa" : value, GlossaryTermNames.display(value), "Code
point " + codePoint);
+ if (matches) Assertions.assertEquals("",
GlossaryTermNames.display(boundary.repeat(3)));
+ }
+ Assertions.assertEquals("", GlossaryTermNames.display(""));
+ Assertions.assertThrows(IllegalArgumentException.class, () ->
GlossaryTermNames.display(null));
+ }
+
+ @Test
+ public void testSnapshotIsolation() {
+ String[] synonyms = {"client"};
+ GlossaryTermEntity.Builder b =
+ builder()
+ .withSynonyms(synonyms)
+ .withLinks(new TermLink[] {TermLink.of(null,
"https://example.org")})
+ .withProperties(Map.of("k", "v"));
+ GlossaryTermEntity first = b.build();
+ synonyms[0] = "changed";
+ first.synonyms()[0] = "changed";
+ b.withName("other").build();
+ Assertions.assertEquals("term", first.name());
+ Assertions.assertEquals("client", first.synonyms()[0]);
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> first.properties().put("a",
"b"));
+ Assertions.assertEquals(Entity.EntityType.GLOSSARY_TERM, first.type());
+ Assertions.assertEquals(1L, first.fields().get(GlossaryTermEntity.ID));
+ }
+
+ private void assertNullArgument(String field, Executable operation) {
+ IllegalArgumentException error =
+ Assertions.assertThrows(IllegalArgumentException.class, operation);
+ Assertions.assertEquals(field + " cannot be null", error.getMessage());
+ }
+}
diff --git
a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
index 01c6a4e719..9ed378eea8 100644
--- a/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
+++ b/core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java
@@ -224,6 +224,8 @@ public class TestSQLScripts extends TestJDBCBackend {
executeScript(scriptFile);
}
if ("2.0.0".equals(versionScripts.getKey())) {
+ assertGlossarySchema();
+ assertGlossaryLiveUniqueness();
assertCleanupIndexes("schema " + versionScripts.getKey());
assertNameColumnWidths("schema " + versionScripts.getKey());
}
@@ -258,6 +260,8 @@ public class TestSQLScripts extends TestJDBCBackend {
executeScript(sourceSchema);
executeScript(upgradeScript);
if ("2.0.0".equals(upgradeMatcher.group(2))) {
+ assertGlossarySchema();
+ assertGlossaryLiveUniqueness();
assertCleanupIndexes(upgradeScript.getName());
assertNameColumnWidths(upgradeScript.getName());
}
@@ -1115,4 +1119,59 @@ public class TestSQLScripts extends TestJDBCBackend {
connection.createStatement().execute("DROP TABLE " + table);
}
}
+
+ private void assertGlossaryLiveUniqueness() throws SQLException {
+ try (SqlSession session =
+
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = session.getConnection();
+ Statement statement = connection.createStatement()) {
+ String insert =
+ "INSERT INTO glossary_term_meta (term_id, metalake_id, name,
name_key, "
+ + "status, links, source_ref, properties, audit_info) VALUES
(%d, 100, '%s', '%s', "
+ + "'DRAFT', '[]', '%s', '{}', '{}')";
+ for (int generation = 1; generation <= 3; generation++) {
+ String name = generation == 3 ? "other" : "churn";
+ statement.executeUpdate(String.format(insert, generation, name, name,
"source"));
+ Assertions.assertThrows(
+ SQLException.class,
+ () -> statement.executeUpdate(String.format(insert, 10, name,
name, "different")));
+ Assertions.assertThrows(
+ SQLException.class,
+ () -> statement.executeUpdate(String.format(insert, 11, "unused",
"unused", "source")));
+ statement.executeUpdate(
+ "UPDATE glossary_term_meta SET deleted_at=123456 WHERE
deleted_at=0");
+ }
+ try (ResultSet rows =
+ statement.executeQuery(
+ "SELECT COUNT(*) FROM glossary_term_meta WHERE
deleted_at=123456")) {
+ Assertions.assertTrue(rows.next());
+ Assertions.assertEquals(3, rows.getInt(1));
+ }
+ }
+ }
+
+ private void assertGlossarySchema() throws SQLException {
+ try (SqlSession session =
+
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+ Connection connection = session.getConnection();
+ Statement statement = connection.createStatement()) {
+ try (ResultSet rows =
+ statement.executeQuery(
+ "SELECT term_id, metalake_id, name, name_key, definition,
status, links, source_ref, properties, audit_info, current_version, deleted_at
FROM glossary_term_meta WHERE 1=0")) {
+ Assertions.assertEquals(12, rows.getMetaData().getColumnCount());
+ }
+ try (ResultSet rows =
+ statement.executeQuery(
+ "SELECT term_id, metalake_id, synonym, synonym_key, deleted_at
FROM glossary_term_synonym WHERE 1=0")) {
+ Assertions.assertEquals(5, rows.getMetaData().getColumnCount());
+ }
+ try (ResultSet tables =
+ connection.getMetaData().getTables(null, null, "%", new String[]
{"TABLE"})) {
+ while (tables.next())
+ Assertions.assertNotEquals(
+ "glossary_term_version_info",
+ tables.getString("TABLE_NAME").toLowerCase(Locale.ROOT));
+ }
+ }
+ }
}
diff --git
a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
index 0286c13622..981a34bb3d 100644
---
a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
+++
b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStore.java
@@ -46,6 +46,7 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.DomainEntity;
+import org.apache.gravitino.meta.GlossaryTermEntity;
import org.apache.gravitino.meta.ModelEntity;
import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.meta.TopicEntity;
@@ -76,6 +77,31 @@ public class TestRelationalEntityStore {
FieldUtils.writeField(store, "cache", Mockito.spy(new NoOpsCache(config)),
true);
}
+ @Test
+ void testGlossaryDefinitionsBypassCache() throws Exception {
+ EntityCache cache = Mockito.mock(EntityCache.class);
+ FieldUtils.writeField(store, "cache", cache, true);
+ Entity.EntityType type = Entity.EntityType.GLOSSARY_TERM;
+ NameIdentifier ident =
+ NameIdentifier.of("lake", Entity.SYSTEM_CATALOG_RESERVED_NAME,
"glossary_term", "term");
+ GlossaryTermEntity entity =
+ GlossaryTermEntity.builder()
+ .withId(1L)
+ .withName("term")
+ .withNamespace(ident.namespace())
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+ Mockito.when(backend.get(ident, type)).thenReturn(entity);
+ Mockito.when(backend.exists(ident, type)).thenReturn(true);
+ Mockito.when(backend.batchGet(List.of(ident),
type)).thenReturn(List.of(entity));
+ store.put(entity, false);
+ Assertions.assertSame(entity, store.get(ident, type,
GlossaryTermEntity.class));
+ Assertions.assertTrue(store.exists(ident, type));
+ Assertions.assertEquals(
+ List.of(entity), store.batchGet(List.of(ident), type,
GlossaryTermEntity.class));
+ Mockito.verifyNoInteractions(cache);
+ }
+
@Test
void testUncachedInsertStillInvokesRelatedInvalidationAfterEpochChanges()
throws Exception {
BaseEntityCache cache = Mockito.mock(BaseEntityCache.class);
diff --git
a/core/src/test/java/org/apache/gravitino/storage/relational/service/GlossaryInvariants.java
b/core/src/test/java/org/apache/gravitino/storage/relational/service/GlossaryInvariants.java
new file mode 100644
index 0000000000..d957d2edc6
--- /dev/null
+++
b/core/src/test/java/org/apache/gravitino/storage/relational/service/GlossaryInvariants.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.storage.relational.service;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.util.HashSet;
+import java.util.Set;
+import org.apache.gravitino.meta.GlossaryTermNames;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.Assertions;
+
+/** Checks the T2 storage invariants directly, independently of entity
decoding. */
+public final class GlossaryInvariants {
+ private GlossaryInvariants() {}
+ /** Checks normalized unique names and live synonym endpoints. */
+ public static void assertDefinitions() throws Exception {
+ try (SqlSession session =
+
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+ Connection connection = session.getConnection();
+ Statement statement = connection.createStatement()) {
+ Set<String> names = new HashSet<>();
+ try (ResultSet rows =
+ statement.executeQuery(
+ "SELECT metalake_id, name, name_key FROM glossary_term_meta
WHERE deleted_at=0")) {
+ while (rows.next()) {
+ Assertions.assertEquals(GlossaryTermNames.key(rows.getString(2)),
rows.getString(3));
+ Assertions.assertTrue(names.add(rows.getLong(1) + ":" +
rows.getString(3)));
+ }
+ }
+ try (ResultSet rows =
+ statement.executeQuery(
+ "SELECT s.synonym, s.synonym_key, t.term_id FROM
glossary_term_synonym s LEFT JOIN glossary_term_meta t ON s.term_id=t.term_id
AND s.metalake_id=t.metalake_id AND t.deleted_at=0 WHERE s.deleted_at=0")) {
+ while (rows.next()) {
+ Assertions.assertEquals(GlossaryTermNames.key(rows.getString(1)),
rows.getString(2));
+ Assertions.assertNotNull(
+ rows.getObject(3), "Live synonym must reference a live term in
its metalake");
+ }
+ }
+ }
+ }
+}
diff --git
a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGlossaryTermMetaService.java
b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGlossaryTermMetaService.java
new file mode 100644
index 0000000000..05ce446d7f
--- /dev/null
+++
b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestGlossaryTermMetaService.java
@@ -0,0 +1,499 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.gravitino.storage.relational.service;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityAlreadyExistsException;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.glossary.GlossaryTerm.Status;
+import org.apache.gravitino.glossary.TermLink;
+import org.apache.gravitino.meta.GlossaryTermEntity;
+import org.apache.gravitino.meta.GlossaryTermNames;
+import org.apache.gravitino.storage.relational.RelationalEntityStoreIdResolver;
+import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.mapper.GlossaryTermMetaMapper;
+import org.apache.gravitino.storage.relational.po.MetalakePO;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.function.Executable;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+/** Backend contract tests for persisted glossary definitions. */
+public class TestGlossaryTermMetaService extends TestJDBCBackend {
+ private static final Entity.EntityType TYPE =
Entity.EntityType.GLOSSARY_TERM;
+ private static final Namespace NS =
+ Namespace.of("glossary", Entity.SYSTEM_CATALOG_RESERVED_NAME,
"glossary_term");
+ private final GlossaryTermMetaService service =
GlossaryTermMetaService.getInstance();
+
+ @AfterEach
+ public void checkInvariants() throws Exception {
+ GlossaryInvariants.assertDefinitions();
+ }
+
+ private void setupMetalake() throws Exception {
+ backend.insert(createBaseMakeLake(100L, "glossary", AUDIT_INFO), false);
+ }
+
+ private GlossaryTermEntity.Builder term(long id, String name) {
+ return GlossaryTermEntity.builder()
+ .withId(id)
+ .withNamespace(NS)
+ .withName(name)
+ .withAuditInfo(AUDIT_INFO);
+ }
+
+ private NameIdentifier ident(String name) {
+ return NameIdentifier.of(NS, name);
+ }
+
+ @TestTemplate
+ public void testRoundTripAndUpdate() throws Exception {
+ setupMetalake();
+ GlossaryTermEntity value =
+ term(101, " Active Customer ")
+ .withDefinition("Business definition")
+ .withSynonyms(new String[] {"client", "buyer"})
+ .withStatus(Status.DRAFT)
+ .withLinks(new TermLink[] {TermLink.of("docs",
"https://example.org/term")})
+ .withSourceRef("import:101")
+ .withProperties(Map.of("team", "sales"))
+ .build();
+ backend.insert(value, false);
+ GlossaryTermEntity read = backend.get(ident("ACTIVE CUSTOMER"), TYPE);
+ Assertions.assertEquals("Active Customer", read.name());
+ Assertions.assertEquals(value.definition(), read.definition());
+ Assertions.assertEquals(Status.DRAFT, read.status());
+ Assertions.assertEquals(value.properties(), read.properties());
+ Assertions.assertArrayEquals(value.links(), read.links());
+ Assertions.assertEquals(value.sourceRef(), read.sourceRef());
+ Assertions.assertEquals(AUDIT_INFO, read.auditInfo());
+ Assertions.assertEquals(2, read.synonyms().length);
+ Assertions.assertEquals(1, read.version());
+ Assertions.assertArrayEquals(
+ new long[] {100, 101},
+ new RelationalEntityStoreIdResolver()
+ .getEntityIds(ident("ACTIVE CUSTOMER"), TYPE)
+ .fullIds());
+ GlossaryTermEntity updated =
+ service.update(
+ ident("Active Customer"),
+ old -> term(101, "Account").withSynonyms(new String[]
{"customer"}).build());
+ Assertions.assertEquals(2, updated.version());
+ Assertions.assertFalse(backend.exists(ident("Active Customer"), TYPE));
+ Assertions.assertArrayEquals(
+ new String[] {"customer"}, service.get(ident("Account")).synonyms());
+ Assertions.assertEquals(1, backend.list(NS, TYPE, true).size());
+ Assertions.assertEquals(
+ 1, service.batchGet(Arrays.asList(ident("Account"),
ident("absent"))).size());
+ }
+
+ @TestTemplate
+ public void testNormalizedNamesAndUnicode() throws Exception {
+ setupMetalake();
+ backend.insert(term(101, "Churn").build(), false);
+ for (String name : new String[] {" churn ", "CHURN"})
+ Assertions.assertThrows(
+ EntityAlreadyExistsException.class, () -> backend.insert(term(102,
name).build(), false));
+ backend.insert(term(103, "Active Customer").build(), false);
+ for (String name : new String[] {"active customer", "Active\tCustomer"})
+ Assertions.assertThrows(
+ EntityAlreadyExistsException.class, () -> backend.insert(term(104,
name).build(), false));
+ Locale previous = Locale.getDefault();
+ try {
+ Locale.setDefault(Locale.forLanguageTag("tr-TR"));
+ Assertions.assertEquals("title", GlossaryTermNames.key("TITLE"));
+ } finally {
+ Locale.setDefault(previous);
+ }
+ String[] names = {"Cafe", "CafΓ©", "a/b.δΈζπ", "π".repeat(128)};
+ long id = 105;
+ for (String name : names) {
+ backend.insert(term(id++, name).build(), false);
+ Assertions.assertEquals(name, service.get(ident(name)).name());
+ }
+ }
+
+ @TestTemplate
+ public void testNullableAndExactSourceReferences() throws Exception {
+ setupMetalake();
+ backend.insert(term(101, "One").build(), false);
+ backend.insert(term(102, "Two").build(), false);
+ backend.insert(term(103, "Three").withSourceRef("import:One").build(),
false);
+ backend.insert(term(104, "Four").withSourceRef("import:one").build(),
false);
+ Assertions.assertThrows(
+ EntityAlreadyExistsException.class,
+ () -> backend.insert(term(105,
"Five").withSourceRef("import:One").build(), false));
+ Assertions.assertFalse(backend.exists(ident("Five"), TYPE));
+ }
+
+ @TestTemplate
+ public void testExactSourceReferenceAndUnicodeBound() throws Exception {
+ setupMetalake();
+ backend.insert(term(101, "One").withSourceRef("import:a").build(), false);
+ backend.insert(term(102, "Two").withSourceRef("import:a ").build(), false);
+ backend.insert(term(103, "Three").withSourceRef("π".repeat(128)).build(),
false);
+ Assertions.assertEquals("import:a ",
service.get(ident("Two")).sourceRef());
+ Assertions.assertEquals("π".repeat(128),
service.get(ident("Three")).sourceRef());
+ }
+
+ @TestTemplate
+ public void testOuterTransactionRollsBackDefinitionAndSynonyms() throws
Exception {
+ setupMetalake();
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () ->
+ SessionUtils.doMultipleWithCommit(
+ () -> {
+ try {
+ service.insert(
+ term(101, "One").withSynonyms(new String[]
{"first"}).build(), false);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ throw new IllegalStateException("abort outer transaction");
+ }));
+ Assertions.assertFalse(backend.exists(ident("One"), TYPE));
+ Assertions.assertEquals(0, service.list(NS).size());
+ backend.insert(term(101, "One").build(), false);
+ Assertions.assertEquals(0, service.get(ident("One")).synonyms().length);
+ }
+
+ @TestTemplate
+ public void testSynonymsAndRollback() throws Exception {
+ setupMetalake();
+ backend.insert(term(101, "One").withSynonyms(new String[]
{"shared"}).build(), false);
+ backend.insert(term(102, "Two").withSynonyms(new String[]
{"shared"}).build(), false);
+ Assertions.assertThrows(
+ EntityAlreadyExistsException.class,
+ () ->
+ service.update(
+ ident("One"),
+ old -> term(101, "Two").withSynonyms(new String[]
{"replacement"}).build()));
+ Assertions.assertArrayEquals(new String[] {"shared"},
service.get(ident("One")).synonyms());
+ Assertions.assertEquals(1, service.get(ident("One")).version());
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> service.update(ident("One"), old -> term(999, "One").build()));
+ }
+
+ @TestTemplate
+ public void testDeleteRecreateAndGc() throws Exception {
+ setupMetalake();
+ backend.insert(term(101, "Churn").withSynonyms(new String[]
{"loss"}).build(), false);
+ Assertions.assertTrue(backend.delete(ident("Churn"), TYPE, false));
+ Assertions.assertFalse(backend.delete(ident("Churn"), TYPE, false));
+ backend.insert(term(102, "Churn").build(), false);
+ Assertions.assertEquals(102, service.get(ident("Churn")).id());
+ Assertions.assertEquals(0, service.collect(1, 10));
+ Assertions.assertEquals(1, service.collect(Long.MAX_VALUE, 10));
+ Assertions.assertEquals(102, service.get(ident("Churn")).id());
+ }
+
+ @TestTemplate
+ public void testWrongNamespaceCannotAccessTerm() throws Exception {
+ IllegalArgumentException nullNamespace =
+ Assertions.assertThrows(IllegalArgumentException.class, () ->
service.list(null));
+ Assertions.assertEquals("Expected glossary term namespace: null",
nullNamespace.getMessage());
+ setupMetalake();
+ backend.insert(term(101, "Churn").withSynonyms(new String[]
{"loss"}).build(), false);
+ for (Namespace wrong :
+ new Namespace[] {
+ Namespace.empty(),
+ Namespace.of("glossary"),
+ Namespace.of("glossary", "system"),
+ Namespace.of("glossary", "catalog", "schema"),
+ Namespace.of("glossary", "system", "schema"),
+ Namespace.of("glossary", "catalog", "glossary_term"),
+ Namespace.of("glossary", "system", "glossary_term", "extra")
+ }) {
+ NameIdentifier invalid = NameIdentifier.of(wrong, "Churn");
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> backend.delete(invalid, TYPE,
false));
+ Assertions.assertThrows(IllegalArgumentException.class, () ->
backend.get(invalid, TYPE));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> backend.list(wrong, TYPE,
true));
+ Assertions.assertThrows(IllegalArgumentException.class, () ->
service.getIds(invalid));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> new RelationalEntityStoreIdResolver().getEntityIds(invalid,
TYPE));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> new RelationalEntityStoreIdResolver().getEntityId(invalid,
TYPE));
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () ->
service.batchGet(Arrays.asList(invalid)));
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ service.update(
+ invalid,
+ old -> {
+ Assertions.fail(
+ "Invalid namespace must be rejected before calling the
updater");
+ return old;
+ }));
+ GlossaryTermEntity read = service.get(ident("Churn"));
+ Assertions.assertEquals(101, read.id());
+ Assertions.assertEquals(1, read.version());
+ Assertions.assertArrayEquals(new String[] {"loss"}, read.synonyms());
+ }
+ }
+
+ @TestTemplate
+ public void testSameTimestampDeletionAndCollection() throws Exception {
+ setupMetalake();
+ long deletedAt = 123456L;
+ // Cover name reuse and independent source-reference reuse, including
metalake cleanup.
+ for (int generation = 0; generation < 3; generation++) {
+ long id = 101L + generation;
+ String name = generation == 2 ? "Other name" : "Churn";
+ backend.insert(
+ term(id, name).withSourceRef("import:churn").withSynonyms(new
String[] {"loss"}).build(),
+ false);
+ final boolean dropMetalake = generation == 2;
+ SessionUtils.doWithCommit(
+ GlossaryTermMetaMapper.class,
+ mapper -> {
+ if (dropMetalake) {
+ mapper.dropMetalake(100L, deletedAt);
+ mapper.dropMetalakeSynonyms(100L, deletedAt);
+ } else {
+ Assertions.assertEquals(1, mapper.delete(id, 1, deletedAt));
+ mapper.deleteSynonyms(id, deletedAt);
+ }
+ });
+ Assertions.assertFalse(backend.exists(ident(name), TYPE));
+ }
+ backend.insert(
+ term(104, "Churn")
+ .withSourceRef("import:churn")
+ .withSynonyms(new String[] {"live synonym"})
+ .build(),
+ false);
+ Assertions.assertEquals(0, service.collect(deletedAt, 10));
+ Assertions.assertEquals(2, service.collect(deletedAt + 1, 2));
+ Assertions.assertEquals(1, service.collect(deletedAt + 1, 2));
+ Assertions.assertEquals(0, service.collect(Long.MAX_VALUE, 10));
+ Assertions.assertEquals(104, service.get(ident("Churn")).id());
+ Assertions.assertArrayEquals(
+ new String[] {"live synonym"}, service.get(ident("Churn")).synonyms());
+ }
+
+ @TestTemplate
+ public void testMetalakeCleanupIsolation() throws Exception {
+ setupMetalake();
+ backend.insert(term(101, "One").withSynonyms(new String[]
{"first"}).build(), false);
+ backend.insert(createBaseMakeLake(200L, "other", AUDIT_INFO), false);
+ Namespace other = Namespace.of("other",
Entity.SYSTEM_CATALOG_RESERVED_NAME, "glossary_term");
+ backend.insert(term(201, "Other").withNamespace(other).build(), false);
+ backend.delete(NameIdentifier.of("glossary"), Entity.EntityType.METALAKE,
true);
+ Assertions.assertEquals(1, service.list(other).size());
+ Assertions.assertEquals(1, service.collect(Long.MAX_VALUE, 10));
+ }
+
+ @TestTemplate
+ public void testOverwritePreservesIdentity() throws Exception {
+ setupMetalake();
+ backend.insert(term(101, "One").withSynonyms(new String[]
{"first"}).build(), false);
+ IllegalArgumentException error =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ backend.insert(
+ term(102, "ONE").withSynonyms(new String[]
{"second"}).build(), true));
+
Assertions.assertTrue(error.getMessage().contains(ident("ONE").toString()));
+ Assertions.assertTrue(error.getMessage().contains("102"));
+ Assertions.assertTrue(error.getMessage().contains("101"));
+ Assertions.assertTrue(error.getMessage().contains("load and retain
existing ID"));
+ GlossaryTermEntity unchanged = service.get(ident("one"));
+ Assertions.assertEquals(101, unchanged.id());
+ Assertions.assertEquals(1, unchanged.version());
+ Assertions.assertArrayEquals(new String[] {"first"}, unchanged.synonyms());
+ backend.insert(term(101, "ONE").withSynonyms(new String[]
{"second"}).build(), true);
+ GlossaryTermEntity read = service.get(ident("one"));
+ Assertions.assertEquals(101, read.id());
+ Assertions.assertEquals(2, read.version());
+ Assertions.assertArrayEquals(new String[] {"second"}, read.synonyms());
+ }
+
+ @TestTemplate
+ public void testReadsDoNotWaitForUncommittedWriter() throws Exception {
+ setupMetalake();
+ backend.insert(
+ term(101, "One")
+ .withDefinition("before")
+ .withSynonyms(new String[] {"first", "shared"})
+ .build(),
+ false);
+ backend.insert(term(102, "Two").withSynonyms(new String[]
{"shared"}).build(), false);
+ backend.insert(term(103, "Empty").build(), false);
+ ExecutorService reader = Executors.newSingleThreadExecutor();
+ try {
+ // The update has executed but its parent/term locks remain held by this
outer transaction.
+ // An independent reader must finish before commit and observe the
complete old definition.
+ SessionUtils.beginTransaction();
+ try {
+ service.update(
+ ident("One"),
+ old ->
+ term(101, "One")
+ .withDefinition("after")
+ .withSynonyms(new String[] {"replacement"})
+ .build());
+ Future<?> read =
+ reader.submit(
+ () -> {
+ try {
+ GlossaryTermEntity value = backend.get(ident("One"), TYPE);
+ Assertions.assertEquals("before", value.definition());
+ Assertions.assertEquals(1, value.version());
+ Assertions.assertArrayEquals(
+ new String[] {"first", "shared"}, value.synonyms());
+ List<GlossaryTermEntity> all = backend.list(NS, TYPE,
true);
+ Assertions.assertEquals(3, all.size());
+ Map<String, GlossaryTermEntity> byName =
+ all.stream()
+
.collect(Collectors.toMap(GlossaryTermEntity::name, item -> item));
+ Assertions.assertArrayEquals(value.synonyms(),
byName.get("One").synonyms());
+ Assertions.assertEquals("before",
byName.get("One").definition());
+ Assertions.assertArrayEquals(
+ new String[] {"shared"}, byName.get("Two").synonyms());
+ Assertions.assertEquals(0,
byName.get("Empty").synonyms().length);
+ Assertions.assertArrayEquals(
+ new long[] {100, 101},
+ new RelationalEntityStoreIdResolver()
+ .getEntityIds(ident("One"), TYPE)
+ .fullIds());
+ List<GlossaryTermEntity> batch =
+ backend.batchGet(Arrays.asList(ident("One"),
ident("absent")), TYPE);
+ Assertions.assertEquals(1, batch.size());
+ Assertions.assertEquals("before",
batch.get(0).definition());
+ Assertions.assertArrayEquals(value.synonyms(),
batch.get(0).synonyms());
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ });
+ read.get(10, TimeUnit.SECONDS);
+ SessionUtils.commitTransaction();
+ } finally {
+ if (SessionUtils.isInTransaction()) {
+ SessionUtils.rollbackTransaction();
+ }
+ }
+ GlossaryTermEntity committed = service.get(ident("One"));
+ Assertions.assertEquals("after", committed.definition());
+ Assertions.assertEquals(2, committed.version());
+ Assertions.assertArrayEquals(new String[] {"replacement"},
committed.synonyms());
+ } finally {
+ reader.shutdownNow();
+ Assertions.assertTrue(reader.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ }
+
+ @TestTemplate
+ public void testGetDoesNotFollowRenamedMetalake() throws Exception {
+ assertReadAfterMetalakeRename(
+ () ->
+ Assertions.assertThrows(
+ NoSuchEntityException.class, () -> backend.get(ident("New
term"), TYPE)));
+ }
+
+ @TestTemplate
+ public void testListDoesNotFollowRenamedMetalake() throws Exception {
+ assertReadAfterMetalakeRename(
+ () -> Assertions.assertTrue(backend.list(NS, TYPE, true).isEmpty()));
+ }
+
+ @TestTemplate
+ public void testBatchGetDoesNotFollowRenamedMetalake() throws Exception {
+ assertReadAfterMetalakeRename(
+ () -> Assertions.assertTrue(backend.batchGet(List.of(ident("New
term")), TYPE).isEmpty()));
+ }
+
+ @TestTemplate
+ public void testIdsDoNotFollowRenamedMetalake() throws Exception {
+ assertReadAfterMetalakeRename(
+ () ->
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> new
RelationalEntityStoreIdResolver().getEntityIds(ident("New term"), TYPE)));
+ }
+
+ private void assertReadAfterMetalakeRename(Executable read) throws Exception
{
+ setupMetalake();
+ Namespace renamed =
+ Namespace.of("renamed", Entity.SYSTEM_CATALOG_RESERVED_NAME,
"glossary_term");
+ ExecutorService writer = Executors.newSingleThreadExecutor();
+ MetalakeMetaService metalakes =
Mockito.spy(MetalakeMetaService.getInstance());
+ Mockito.doAnswer(
+ invocation -> {
+ MetalakePO observed = (MetalakePO) invocation.callRealMethod();
+ // Commit on an independent session after name resolution but
before the term SELECT.
+ // This term has never existed under the old namespace, so
returning it cannot
+ // represent
+ // an earlier valid snapshot. The spy changes timing only; all
reads and writes hit
+ // the DB.
+ writer
+ .submit(
+ () -> {
+ backend.update(
+ NameIdentifier.of("glossary"),
+ Entity.EntityType.METALAKE,
+ old -> createBaseMakeLake(100L, "renamed",
AUDIT_INFO));
+ backend.insert(
+ term(101L, "New term")
+ .withNamespace(renamed)
+ .withSynonyms(new String[] {"new synonym"})
+ .build(),
+ false);
+ return null;
+ })
+ .get(10, TimeUnit.SECONDS);
+ return observed;
+ })
+ .when(metalakes)
+ .requireMetalakeByName("glossary");
+ try (MockedStatic<MetalakeMetaService> services =
+ Mockito.mockStatic(MetalakeMetaService.class,
Mockito.CALLS_REAL_METHODS)) {
+ services.when(MetalakeMetaService::getInstance).thenReturn(metalakes);
+ Assertions.assertDoesNotThrow(read);
+ Mockito.verify(metalakes).requireMetalakeByName("glossary");
+ } finally {
+ writer.shutdownNow();
+ Assertions.assertTrue(writer.awaitTermination(10, TimeUnit.SECONDS));
+ }
+ Assertions.assertEquals(101L, service.get(NameIdentifier.of(renamed, "New
term")).id());
+ }
+}
diff --git a/design-docs/glossary-design.md b/design-docs/glossary-design.md
index 830f52e583..bf7127c6e5 100644
--- a/design-docs/glossary-design.md
+++ b/design-docs/glossary-design.md
@@ -145,7 +145,7 @@ TermVersion { termId, version, state, snapshot, audit_info
} // Step 2 only;
| Table | Unique key
| Other index |
| -------------------------- |
------------------------------------------------------------------------------
| ---------------------------------------- |
-| `glossary_term_meta` | `(metalake_id, name_key, deleted_at)`,
`(metalake_id, source_ref, deleted_at)` |
|
+| `glossary_term_meta` | `(metalake_id, name_key)`, `(metalake_id,
source_ref)` for live rows only |
|
| `glossary_term_synonym` | `(term_id, synonym_key, deleted_at)`
| `(metalake_id, synonym_key, deleted_at)` |
| `glossary_term_rel` | `(from_term_id, to_term_id, rel_type,
deleted_at)` | `(to_term_id, rel_type)`
|
| `glossary_term_domain_rel` | `(term_id, domain_id, deleted_at)`
| `(domain_id)` |
@@ -153,6 +153,11 @@ TermVersion { termId, version, state, snapshot,
audit_info } // Step 2 only;
- The tables are added to the H2, MySQL and PostgreSQL schemas and to the
`upgrade-1.3.0-to-2.0.0`
scripts.
+- **Live definition uniqueness**: only rows with `deleted_at = 0` reserve a
name or source
+ reference. PostgreSQL uses partial unique indexes. H2 and MySQL add a
generated `live_row`
+ discriminator (`1` for live rows, `NULL` for deleted rows) to the unique
keys. Keep the actual
+ deletion timestamp for GC; distinct deleted generations may share that
timestamp without
+ colliding. MySQL indexes the binary source-reference key described below.
- **Normalized key**: `key(s)` trims `s`, turns each run of spaces into one
space, and lower-cases
it (`Locale.ROOT`). Names, synonyms and lookups all use `key()`, so they
compare the same way.
- **Names** are unique in a metalake by `name_key = key(name)`. So `Churn` and
`churn` are the same
@@ -178,9 +183,12 @@ TermVersion { termId, version, state, snapshot,
audit_info } // Step 2 only;
synonyms. A definition has at most 16,384 UTF-8 bytes. A non-null
`sourceRef` has at most 128
Unicode code points. Reject over-limit values with 400 before writing; never
truncate them.
Apply the same bounds to create, alter and future imports. Store
`source_ref` as nullable
- `VARCHAR(128)` with exact, case-sensitive comparison. Under utf8mb4 its
maximum key payload
- is 512 bytes; with two BIGINT key columns the composite payload is 528
bytes, avoiding a
- prefix index or a dependency on the 3072-byte MySQL index limit.
+ `VARCHAR(128)` on MySQL/PostgreSQL and `VARCHAR(256)` on H2 to accommodate
UTF-16 storage,
+ while Java enforces the 128-code-point bound. Comparison is exact and
case-sensitive, including
+ trailing spaces. MySQL uses a generated `VARBINARY(512)` source-reference
key because its 5.7
+ string collation pads spaces. With the metalake BIGINT and nullable live-row
INT, the explicit
+ composite key payload is at most 524 bytes, avoiding a prefix index or a
dependency on the
+ 3072-byte MySQL index limit.
- `MetadataObject.Type.GLOSSARY_TERM` is added for owners, tags, events and
audit. Privileges
**cannot be granted on a single term**: the role APIs reject them.
- Terms, relations and bindings are not cached. Owner-based glossary
authorization resolves the
diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sql
index cdc64526bf..179283dc9e 100644
--- a/scripts/h2/schema-2.0.0-h2.sql
+++ b/scripts/h2/schema-2.0.0-h2.sql
@@ -828,3 +828,34 @@ CREATE TABLE IF NOT EXISTS `domain_rel` (
KEY `domain_rel_idx_parent` (`parent_id`, `deleted_at`),
KEY `domain_rel_idx_metalake` (`metalake_id`, `deleted_at`)
) ENGINE=InnoDB;
+
+CREATE TABLE IF NOT EXISTS glossary_term_meta (
+ term_id BIGINT NOT NULL PRIMARY KEY COMMENT 'globally unique glossary term
id',
+ metalake_id BIGINT NOT NULL COMMENT 'owning metalake id',
+ name VARCHAR(256) NOT NULL COMMENT 'glossary term display name, preserving
case and internal whitespace',
+ name_key VARCHAR(384) NOT NULL COMMENT 'lookup and uniqueness key:
trimmed, whitespace-collapsed and lowercased name, e.g. " Active Customer "
-> "active customer"',
+ definition CLOB COMMENT 'optional glossary term definition',
+ status VARCHAR(16) NOT NULL COMMENT 'glossary term status: DRAFT, APPROVED
or DEPRECATED',
+ links CLOB NOT NULL COMMENT 'documentation links as a JSON array of label
and URL pairs',
+ source_ref VARCHAR(256) COMMENT 'optional external source identifier, e.g.
"crm:123", case and trailing spaces are significant',
+ properties CLOB NOT NULL COMMENT 'glossary term properties as a JSON
object',
+ audit_info CLOB NOT NULL COMMENT 'glossary term audit info as a JSON
object',
+ current_version BIGINT NOT NULL DEFAULT 1 COMMENT 'glossary term revision,
starting at 1 and incremented on update or overwrite',
+ deleted_at BIGINT NOT NULL DEFAULT 0 COMMENT 'soft deletion time in epoch
milliseconds, 0 means live',
+ -- NULL exempts deleted generations from uniqueness, even at the same
deletion time.
+ live_row INT GENERATED ALWAYS AS (CASE WHEN deleted_at = 0 THEN 1 ELSE
NULL END) COMMENT 'generated live-row discriminator, only live rows reserve
unique keys, e.g. deleted_at=0 -> 1 and deleted_at=1700000000000 -> NULL',
+ CONSTRAINT uk_glossary_name UNIQUE (metalake_id, name_key, live_row),
+ CONSTRAINT uk_glossary_source UNIQUE (metalake_id, source_ref, live_row)
+);
+COMMENT ON TABLE glossary_term_meta IS 'glossary term definitions';
+
+CREATE TABLE IF NOT EXISTS glossary_term_synonym (
+ term_id BIGINT NOT NULL COMMENT 'globally unique glossary term id',
+ metalake_id BIGINT NOT NULL COMMENT 'owning metalake id',
+ synonym VARCHAR(256) NOT NULL COMMENT 'glossary term synonym display name',
+ synonym_key VARCHAR(384) NOT NULL COMMENT 'synonym lookup key: trimmed,
whitespace-collapsed and lowercased synonym, e.g. " ACTIVE USER " -> "active
user"',
+ deleted_at BIGINT NOT NULL DEFAULT 0 COMMENT 'soft deletion time in epoch
milliseconds, 0 means live',
+ PRIMARY KEY (term_id, synonym_key, deleted_at)
+);
+COMMENT ON TABLE glossary_term_synonym IS 'glossary term synonyms, different
terms may share the same synonym';
+CREATE INDEX IF NOT EXISTS idx_glossary_synonym ON glossary_term_synonym
(metalake_id, synonym_key, deleted_at);
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 bedb91a308..97b262a739 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
@@ -425,3 +425,34 @@ CREATE TABLE IF NOT EXISTS `domain_rel` (
KEY `domain_rel_idx_parent` (`parent_id`, `deleted_at`),
KEY `domain_rel_idx_metalake` (`metalake_id`, `deleted_at`)
) ENGINE=InnoDB;
+
+CREATE TABLE IF NOT EXISTS glossary_term_meta (
+ term_id BIGINT NOT NULL PRIMARY KEY COMMENT 'globally unique glossary term
id',
+ metalake_id BIGINT NOT NULL COMMENT 'owning metalake id',
+ name VARCHAR(256) NOT NULL COMMENT 'glossary term display name, preserving
case and internal whitespace',
+ name_key VARCHAR(384) NOT NULL COMMENT 'lookup and uniqueness key:
trimmed, whitespace-collapsed and lowercased name, e.g. " Active Customer "
-> "active customer"',
+ definition CLOB COMMENT 'optional glossary term definition',
+ status VARCHAR(16) NOT NULL COMMENT 'glossary term status: DRAFT, APPROVED
or DEPRECATED',
+ links CLOB NOT NULL COMMENT 'documentation links as a JSON array of label
and URL pairs',
+ source_ref VARCHAR(256) COMMENT 'optional external source identifier, e.g.
"crm:123", case and trailing spaces are significant',
+ properties CLOB NOT NULL COMMENT 'glossary term properties as a JSON
object',
+ audit_info CLOB NOT NULL COMMENT 'glossary term audit info as a JSON
object',
+ current_version BIGINT NOT NULL DEFAULT 1 COMMENT 'glossary term revision,
starting at 1 and incremented on update or overwrite',
+ deleted_at BIGINT NOT NULL DEFAULT 0 COMMENT 'soft deletion time in epoch
milliseconds, 0 means live',
+ -- NULL exempts deleted generations from uniqueness, even at the same
deletion time.
+ live_row INT GENERATED ALWAYS AS (CASE WHEN deleted_at = 0 THEN 1 ELSE
NULL END) COMMENT 'generated live-row discriminator, only live rows reserve
unique keys, e.g. deleted_at=0 -> 1 and deleted_at=1700000000000 -> NULL',
+ CONSTRAINT uk_glossary_name UNIQUE (metalake_id, name_key, live_row),
+ CONSTRAINT uk_glossary_source UNIQUE (metalake_id, source_ref, live_row)
+);
+COMMENT ON TABLE glossary_term_meta IS 'glossary term definitions';
+
+CREATE TABLE IF NOT EXISTS glossary_term_synonym (
+ term_id BIGINT NOT NULL COMMENT 'globally unique glossary term id',
+ metalake_id BIGINT NOT NULL COMMENT 'owning metalake id',
+ synonym VARCHAR(256) NOT NULL COMMENT 'glossary term synonym display name',
+ synonym_key VARCHAR(384) NOT NULL COMMENT 'synonym lookup key: trimmed,
whitespace-collapsed and lowercased synonym, e.g. " ACTIVE USER " -> "active
user"',
+ deleted_at BIGINT NOT NULL DEFAULT 0 COMMENT 'soft deletion time in epoch
milliseconds, 0 means live',
+ PRIMARY KEY (term_id, synonym_key, deleted_at)
+);
+COMMENT ON TABLE glossary_term_synonym IS 'glossary term synonyms, different
terms may share the same synonym';
+CREATE INDEX IF NOT EXISTS idx_glossary_synonym ON glossary_term_synonym
(metalake_id, synonym_key, deleted_at);
diff --git a/scripts/mysql/schema-2.0.0-mysql.sql
b/scripts/mysql/schema-2.0.0-mysql.sql
index c95284821d..2cfaaed4fd 100644
--- a/scripts/mysql/schema-2.0.0-mysql.sql
+++ b/scripts/mysql/schema-2.0.0-mysql.sql
@@ -816,3 +816,34 @@ CREATE TABLE IF NOT EXISTS `domain_rel` (
KEY `domain_rel_idx_parent` (`parent_id`, `deleted_at`),
KEY `domain_rel_idx_metalake` (`metalake_id`, `deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'domain
parent relation';
+
+CREATE TABLE IF NOT EXISTS glossary_term_meta (
+ term_id BIGINT NOT NULL PRIMARY KEY COMMENT 'globally unique glossary term
id',
+ metalake_id BIGINT NOT NULL COMMENT 'owning metalake id',
+ name VARCHAR(128) COLLATE utf8mb4_bin NOT NULL COMMENT 'glossary term
display name, preserving case and internal whitespace',
+ name_key VARCHAR(384) COLLATE utf8mb4_bin NOT NULL COMMENT 'lookup and
uniqueness key: trimmed, whitespace-collapsed and lowercased name, e.g. "
Active Customer " -> "active customer"',
+ definition MEDIUMTEXT COMMENT 'optional glossary term definition',
+ status VARCHAR(16) NOT NULL COMMENT 'glossary term status: DRAFT, APPROVED
or DEPRECATED',
+ links MEDIUMTEXT NOT NULL COMMENT 'documentation links as a JSON array of
label and URL pairs',
+ source_ref VARCHAR(128) COLLATE utf8mb4_bin COMMENT 'optional external
source identifier, e.g. "crm:123", case and trailing spaces are significant',
+ -- MySQL 5.7 collations pad spaces. The binary key preserves exact source
references.
+ source_ref_key VARBINARY(512) GENERATED ALWAYS AS (CAST(source_ref AS
BINARY)) STORED COMMENT 'generated binary source reference key for exact
uniqueness, e.g. "ref:A" -> 0x7265663A41 but "ref:A " -> 0x7265663A4120',
+ properties MEDIUMTEXT NOT NULL COMMENT 'glossary term properties as a JSON
object',
+ audit_info MEDIUMTEXT NOT NULL COMMENT 'glossary term audit info as a JSON
object',
+ current_version BIGINT NOT NULL DEFAULT 1 COMMENT 'glossary term revision,
starting at 1 and incremented on update or overwrite',
+ deleted_at BIGINT NOT NULL DEFAULT 0 COMMENT 'soft deletion time in epoch
milliseconds, 0 means live',
+ -- NULL exempts deleted generations from uniqueness, even at the same
deletion time.
+ live_row INT GENERATED ALWAYS AS (CASE WHEN deleted_at = 0 THEN 1 ELSE
NULL END) STORED COMMENT 'generated live-row discriminator, only live rows
reserve unique keys, e.g. deleted_at=0 -> 1 and deleted_at=1700000000000 ->
NULL',
+ CONSTRAINT uk_glossary_name UNIQUE (metalake_id, name_key, live_row),
+ CONSTRAINT uk_glossary_source UNIQUE (metalake_id, source_ref_key,
live_row)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'glossary
term definitions';
+
+CREATE TABLE IF NOT EXISTS glossary_term_synonym (
+ term_id BIGINT NOT NULL COMMENT 'globally unique glossary term id',
+ metalake_id BIGINT NOT NULL COMMENT 'owning metalake id',
+ synonym VARCHAR(128) COLLATE utf8mb4_bin NOT NULL COMMENT 'glossary term
synonym display name',
+ synonym_key VARCHAR(384) COLLATE utf8mb4_bin NOT NULL COMMENT 'synonym
lookup key: trimmed, whitespace-collapsed and lowercased synonym, e.g. " ACTIVE
USER " -> "active user"',
+ deleted_at BIGINT NOT NULL DEFAULT 0 COMMENT 'soft deletion time in epoch
milliseconds, 0 means live',
+ PRIMARY KEY (term_id, synonym_key, deleted_at),
+ KEY idx_glossary_synonym (metalake_id, synonym_key, deleted_at)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'glossary
term synonyms, different terms may share the same synonym';
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 39214079cc..9741432c97 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
@@ -923,3 +923,34 @@ CREATE TABLE IF NOT EXISTS `domain_rel` (
KEY `domain_rel_idx_parent` (`parent_id`, `deleted_at`),
KEY `domain_rel_idx_metalake` (`metalake_id`, `deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'domain
parent relation';
+
+CREATE TABLE IF NOT EXISTS glossary_term_meta (
+ term_id BIGINT NOT NULL PRIMARY KEY COMMENT 'globally unique glossary term
id',
+ metalake_id BIGINT NOT NULL COMMENT 'owning metalake id',
+ name VARCHAR(128) COLLATE utf8mb4_bin NOT NULL COMMENT 'glossary term
display name, preserving case and internal whitespace',
+ name_key VARCHAR(384) COLLATE utf8mb4_bin NOT NULL COMMENT 'lookup and
uniqueness key: trimmed, whitespace-collapsed and lowercased name, e.g. "
Active Customer " -> "active customer"',
+ definition MEDIUMTEXT COMMENT 'optional glossary term definition',
+ status VARCHAR(16) NOT NULL COMMENT 'glossary term status: DRAFT, APPROVED
or DEPRECATED',
+ links MEDIUMTEXT NOT NULL COMMENT 'documentation links as a JSON array of
label and URL pairs',
+ source_ref VARCHAR(128) COLLATE utf8mb4_bin COMMENT 'optional external
source identifier, e.g. "crm:123", case and trailing spaces are significant',
+ -- MySQL 5.7 collations pad spaces. The binary key preserves exact source
references.
+ source_ref_key VARBINARY(512) GENERATED ALWAYS AS (CAST(source_ref AS
BINARY)) STORED COMMENT 'generated binary source reference key for exact
uniqueness, e.g. "ref:A" -> 0x7265663A41 but "ref:A " -> 0x7265663A4120',
+ properties MEDIUMTEXT NOT NULL COMMENT 'glossary term properties as a JSON
object',
+ audit_info MEDIUMTEXT NOT NULL COMMENT 'glossary term audit info as a JSON
object',
+ current_version BIGINT NOT NULL DEFAULT 1 COMMENT 'glossary term revision,
starting at 1 and incremented on update or overwrite',
+ deleted_at BIGINT NOT NULL DEFAULT 0 COMMENT 'soft deletion time in epoch
milliseconds, 0 means live',
+ -- NULL exempts deleted generations from uniqueness, even at the same
deletion time.
+ live_row INT GENERATED ALWAYS AS (CASE WHEN deleted_at = 0 THEN 1 ELSE
NULL END) STORED COMMENT 'generated live-row discriminator, only live rows
reserve unique keys, e.g. deleted_at=0 -> 1 and deleted_at=1700000000000 ->
NULL',
+ CONSTRAINT uk_glossary_name UNIQUE (metalake_id, name_key, live_row),
+ CONSTRAINT uk_glossary_source UNIQUE (metalake_id, source_ref_key,
live_row)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'glossary
term definitions';
+
+CREATE TABLE IF NOT EXISTS glossary_term_synonym (
+ term_id BIGINT NOT NULL COMMENT 'globally unique glossary term id',
+ metalake_id BIGINT NOT NULL COMMENT 'owning metalake id',
+ synonym VARCHAR(128) COLLATE utf8mb4_bin NOT NULL COMMENT 'glossary term
synonym display name',
+ synonym_key VARCHAR(384) COLLATE utf8mb4_bin NOT NULL COMMENT 'synonym
lookup key: trimmed, whitespace-collapsed and lowercased synonym, e.g. " ACTIVE
USER " -> "active user"',
+ deleted_at BIGINT NOT NULL DEFAULT 0 COMMENT 'soft deletion time in epoch
milliseconds, 0 means live',
+ PRIMARY KEY (term_id, synonym_key, deleted_at),
+ KEY idx_glossary_synonym (metalake_id, synonym_key, deleted_at)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'glossary
term synonyms, different terms may share the same synonym';
diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql
b/scripts/postgresql/schema-2.0.0-postgresql.sql
index 6c4d8c92a0..77d44ab1e8 100644
--- a/scripts/postgresql/schema-2.0.0-postgresql.sql
+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql
@@ -1415,3 +1415,52 @@ COMMENT ON COLUMN domain_rel.audit_info IS 'domain
relation audit info';
COMMENT ON COLUMN domain_rel.current_version IS 'domain relation current
version';
COMMENT ON COLUMN domain_rel.last_version IS 'domain relation last version';
COMMENT ON COLUMN domain_rel.deleted_at IS 'domain relation deleted at';
+
+CREATE TABLE IF NOT EXISTS glossary_term_meta (
+ term_id BIGINT NOT NULL PRIMARY KEY,
+ metalake_id BIGINT NOT NULL,
+ name VARCHAR(128) COLLATE "C" NOT NULL,
+ name_key VARCHAR(384) COLLATE "C" NOT NULL,
+ definition TEXT,
+ status VARCHAR(16) NOT NULL,
+ links TEXT NOT NULL,
+ source_ref VARCHAR(128) COLLATE "C",
+ properties TEXT NOT NULL,
+ audit_info TEXT NOT NULL,
+ current_version BIGINT NOT NULL DEFAULT 1,
+ deleted_at BIGINT NOT NULL DEFAULT 0
+);
+-- Only live rows reserve names and source references. Deletion times remain
available for GC.
+CREATE UNIQUE INDEX IF NOT EXISTS uk_glossary_name ON glossary_term_meta
(metalake_id, name_key) WHERE deleted_at = 0;
+CREATE UNIQUE INDEX IF NOT EXISTS uk_glossary_source ON glossary_term_meta
(metalake_id, source_ref) WHERE deleted_at = 0;
+
+CREATE TABLE IF NOT EXISTS glossary_term_synonym (
+ term_id BIGINT NOT NULL,
+ metalake_id BIGINT NOT NULL,
+ synonym VARCHAR(128) COLLATE "C" NOT NULL,
+ synonym_key VARCHAR(384) COLLATE "C" NOT NULL,
+ deleted_at BIGINT NOT NULL DEFAULT 0,
+ PRIMARY KEY (term_id, synonym_key, deleted_at)
+);
+CREATE INDEX IF NOT EXISTS idx_glossary_synonym ON glossary_term_synonym
(metalake_id, synonym_key, deleted_at);
+
+COMMENT ON TABLE glossary_term_meta IS 'glossary term definitions';
+COMMENT ON COLUMN glossary_term_meta.term_id IS 'globally unique glossary term
id';
+COMMENT ON COLUMN glossary_term_meta.metalake_id IS 'owning metalake id';
+COMMENT ON COLUMN glossary_term_meta.name IS 'glossary term display name,
preserving case and internal whitespace';
+COMMENT ON COLUMN glossary_term_meta.name_key IS 'lookup and uniqueness key:
trimmed, whitespace-collapsed and lowercased name, e.g. " Active Customer "
-> "active customer"';
+COMMENT ON COLUMN glossary_term_meta.definition IS 'optional glossary term
definition';
+COMMENT ON COLUMN glossary_term_meta.status IS 'glossary term status: DRAFT,
APPROVED or DEPRECATED';
+COMMENT ON COLUMN glossary_term_meta.links IS 'documentation links as a JSON
array of label and URL pairs';
+COMMENT ON COLUMN glossary_term_meta.source_ref IS 'optional external source
identifier, e.g. "crm:123", case and trailing spaces are significant';
+COMMENT ON COLUMN glossary_term_meta.properties IS 'glossary term properties
as a JSON object';
+COMMENT ON COLUMN glossary_term_meta.audit_info IS 'glossary term audit info
as a JSON object';
+COMMENT ON COLUMN glossary_term_meta.current_version IS 'glossary term
revision, starting at 1 and incremented on update or overwrite';
+COMMENT ON COLUMN glossary_term_meta.deleted_at IS 'soft deletion time in
epoch milliseconds, 0 means live';
+
+COMMENT ON TABLE glossary_term_synonym IS 'glossary term synonyms, different
terms may share the same synonym';
+COMMENT ON COLUMN glossary_term_synonym.term_id IS 'globally unique glossary
term id';
+COMMENT ON COLUMN glossary_term_synonym.metalake_id IS 'owning metalake id';
+COMMENT ON COLUMN glossary_term_synonym.synonym IS 'glossary term synonym
display name';
+COMMENT ON COLUMN glossary_term_synonym.synonym_key IS 'synonym lookup key:
trimmed, whitespace-collapsed and lowercased synonym, e.g. " ACTIVE USER " ->
"active user"';
+COMMENT ON COLUMN glossary_term_synonym.deleted_at IS 'soft deletion time in
epoch milliseconds, 0 means live';
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 c4c1fb651d..4675950537 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
@@ -554,3 +554,52 @@ COMMENT ON COLUMN domain_rel.audit_info IS 'domain
relation audit info';
COMMENT ON COLUMN domain_rel.current_version IS 'domain relation current
version';
COMMENT ON COLUMN domain_rel.last_version IS 'domain relation last version';
COMMENT ON COLUMN domain_rel.deleted_at IS 'domain relation deleted at';
+
+CREATE TABLE IF NOT EXISTS glossary_term_meta (
+ term_id BIGINT NOT NULL PRIMARY KEY,
+ metalake_id BIGINT NOT NULL,
+ name VARCHAR(128) COLLATE "C" NOT NULL,
+ name_key VARCHAR(384) COLLATE "C" NOT NULL,
+ definition TEXT,
+ status VARCHAR(16) NOT NULL,
+ links TEXT NOT NULL,
+ source_ref VARCHAR(128) COLLATE "C",
+ properties TEXT NOT NULL,
+ audit_info TEXT NOT NULL,
+ current_version BIGINT NOT NULL DEFAULT 1,
+ deleted_at BIGINT NOT NULL DEFAULT 0
+);
+-- Only live rows reserve names and source references. Deletion times remain
available for GC.
+CREATE UNIQUE INDEX IF NOT EXISTS uk_glossary_name ON glossary_term_meta
(metalake_id, name_key) WHERE deleted_at = 0;
+CREATE UNIQUE INDEX IF NOT EXISTS uk_glossary_source ON glossary_term_meta
(metalake_id, source_ref) WHERE deleted_at = 0;
+
+CREATE TABLE IF NOT EXISTS glossary_term_synonym (
+ term_id BIGINT NOT NULL,
+ metalake_id BIGINT NOT NULL,
+ synonym VARCHAR(128) COLLATE "C" NOT NULL,
+ synonym_key VARCHAR(384) COLLATE "C" NOT NULL,
+ deleted_at BIGINT NOT NULL DEFAULT 0,
+ PRIMARY KEY (term_id, synonym_key, deleted_at)
+);
+CREATE INDEX IF NOT EXISTS idx_glossary_synonym ON glossary_term_synonym
(metalake_id, synonym_key, deleted_at);
+
+COMMENT ON TABLE glossary_term_meta IS 'glossary term definitions';
+COMMENT ON COLUMN glossary_term_meta.term_id IS 'globally unique glossary term
id';
+COMMENT ON COLUMN glossary_term_meta.metalake_id IS 'owning metalake id';
+COMMENT ON COLUMN glossary_term_meta.name IS 'glossary term display name,
preserving case and internal whitespace';
+COMMENT ON COLUMN glossary_term_meta.name_key IS 'lookup and uniqueness key:
trimmed, whitespace-collapsed and lowercased name, e.g. " Active Customer "
-> "active customer"';
+COMMENT ON COLUMN glossary_term_meta.definition IS 'optional glossary term
definition';
+COMMENT ON COLUMN glossary_term_meta.status IS 'glossary term status: DRAFT,
APPROVED or DEPRECATED';
+COMMENT ON COLUMN glossary_term_meta.links IS 'documentation links as a JSON
array of label and URL pairs';
+COMMENT ON COLUMN glossary_term_meta.source_ref IS 'optional external source
identifier, e.g. "crm:123", case and trailing spaces are significant';
+COMMENT ON COLUMN glossary_term_meta.properties IS 'glossary term properties
as a JSON object';
+COMMENT ON COLUMN glossary_term_meta.audit_info IS 'glossary term audit info
as a JSON object';
+COMMENT ON COLUMN glossary_term_meta.current_version IS 'glossary term
revision, starting at 1 and incremented on update or overwrite';
+COMMENT ON COLUMN glossary_term_meta.deleted_at IS 'soft deletion time in
epoch milliseconds, 0 means live';
+
+COMMENT ON TABLE glossary_term_synonym IS 'glossary term synonyms, different
terms may share the same synonym';
+COMMENT ON COLUMN glossary_term_synonym.term_id IS 'globally unique glossary
term id';
+COMMENT ON COLUMN glossary_term_synonym.metalake_id IS 'owning metalake id';
+COMMENT ON COLUMN glossary_term_synonym.synonym IS 'glossary term synonym
display name';
+COMMENT ON COLUMN glossary_term_synonym.synonym_key IS 'synonym lookup key:
trimmed, whitespace-collapsed and lowercased synonym, e.g. " ACTIVE USER " ->
"active user"';
+COMMENT ON COLUMN glossary_term_synonym.deleted_at IS 'soft deletion time in
epoch milliseconds, 0 means live';