Skip to content

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

[#15247] feat: Persist Semantic Model revisions and publish on save (#15251)

mchadesad08c8dc66fc
diff --git a/api/src/main/java/org/apache/gravitino/exceptions/NoSuchSemanticModelRevisionException.java b/api/src/main/java/org/apache/gravitino/exceptions/NoSuchSemanticModelRevisionException.java
new file mode 100644
index 0000000000..f9ccfbd77e
--- /dev/null
+++ b/api/src/main/java/org/apache/gravitino/exceptions/NoSuchSemanticModelRevisionException.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.exceptions;
+
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+
+/** Exception thrown when the requested Semantic Model revision does not exist. */
+public class NoSuchSemanticModelRevisionException extends NotFoundException {
+
+ /**
+ * Constructs an exception with a formatted detail message.
+ *
+ * @param message The detail message format.
+ * @param args The arguments referenced by the format specifiers in the detail message.
+ */
+ @FormatMethod
+ public NoSuchSemanticModelRevisionException(@FormatString String message, Object... args) {
+ super(message, args);
+ }
+
+ /**
+ * Constructs an exception with a cause and a formatted detail message.
+ *
+ * @param cause The cause of the exception.
+ * @param message The detail message format.
+ * @param args The arguments referenced by the format specifiers in the detail message.
+ */
+ @FormatMethod
+ public NoSuchSemanticModelRevisionException(
+ Throwable cause, @FormatString String message, Object... args) {
+ super(cause, message, args);
+ }
+}
diff --git a/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java b/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java
index bd5fc6b856..753f37542a 100644
--- a/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java
+++ b/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java
@@ -22,7 +22,6 @@ import java.util.Collections;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.gravitino.Audit;
-import org.apache.gravitino.Auditable;
import org.apache.gravitino.annotation.Evolving;
import org.apache.gravitino.domain.SupportsDomains;
import org.apache.gravitino.policy.SupportsPolicies;
@@ -33,7 +32,15 @@ import org.apache.gravitino.tag.SupportsTags;
* Ossie-compatible definition with Gravitino properties and audit information.
*/
@Evolving
-public interface SemanticModel extends Auditable {
+public interface SemanticModel extends SemanticModelRevision {
+
+ /** The publication status of a Semantic Model revision. */
+ enum Status {
+ /** Saved and awaiting publication. */
+ DRAFT,
+ /** Published as the active revision at least once. */
+ PUBLISHED
+ }
/**
* The property key for the Apache Ossie document version.
diff --git a/api/src/main/java/org/apache/gravitino/semantic/SemanticModelRevision.java b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelRevision.java
new file mode 100644
index 0000000000..83682161ff
--- /dev/null
+++ b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelRevision.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.semantic;
+
+import java.time.Instant;
+import javax.annotation.Nullable;
+import org.apache.gravitino.Auditable;
+import org.apache.gravitino.annotation.Evolving;
+
+/** Metadata of a retained Semantic Model revision. The audit information describes its writer. */
+@Evolving
+public interface SemanticModelRevision extends Auditable {
+
+ /**
+ * Returns the revision number.
+ *
+ * @return The revision number, starting at one.
+ */
+ int revision();
+
+ /**
+ * Returns the revision's publication status.
+ *
+ * @return The publication status.
+ */
+ SemanticModel.Status status();
+
+ /**
+ * Returns the publishing principal.
+ *
+ * @return The publishing principal, or {@code null} for a draft.
+ */
+ @Nullable
+ String publishedBy();
+
+ /**
+ * Returns the publication time.
+ *
+ * @return The publication time, or {@code null} for a draft.
+ */
+ @Nullable
+ Instant publishedAt();
+}
diff --git a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelDefinition.java b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelDefinition.java
index a3a85d8e11..f58460b538 100644
--- a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelDefinition.java
+++ b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelDefinition.java
@@ -25,6 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import java.time.Instant;
import java.util.Collections;
import org.apache.gravitino.Audit;
import org.apache.gravitino.NameIdentifier;
@@ -154,6 +155,26 @@ public class TestSemanticModelDefinition {
private static SemanticModel semanticModel(SemanticModelDefinition definition) {
return new SemanticModel() {
+ @Override
+ public int revision() {
+ return 1;
+ }
+
+ @Override
+ public Status status() {
+ return Status.PUBLISHED;
+ }
+
+ @Override
+ public String publishedBy() {
+ return "user";
+ }
+
+ @Override
+ public Instant publishedAt() {
+ return Instant.EPOCH;
+ }
+
@Override
public String name() {
return "sales";
diff --git a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
index 7a3c904d04..083948d184 100644
--- a/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
+++ b/catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java
@@ -39,6 +39,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
import static org.apache.gravitino.Configs.VERSION_RETENTION_COUNT;
@@ -309,6 +310,7 @@ public class TestFilesetCatalogOperations {
f.deleteOnExit();
when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);
when(config.get(STORE_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
diff --git a/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/TestKafkaCatalogOperations.java b/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/TestKafkaCatalogOperations.java
index 8512434ffa..ccfcc389ce 100644
--- a/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/TestKafkaCatalogOperations.java
+++ b/catalogs/catalog-kafka/src/test/java/org/apache/gravitino/catalog/kafka/TestKafkaCatalogOperations.java
@@ -40,6 +40,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
import static org.apache.gravitino.Configs.VERSION_RETENTION_COUNT;
@@ -183,6 +184,7 @@ public class TestKafkaCatalogOperations extends KafkaClusterEmbedded {
f.deleteOnExit();
when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);
when(config.get(STORE_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
diff --git a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java
index ba28e488ad..58f5d5a9c2 100644
--- a/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java
+++ b/catalogs/catalog-lakehouse-generic/src/test/java/org/apache/gravitino/catalog/lakehouse/generic/TestGenericCatalogOperations.java
@@ -39,6 +39,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
import static org.apache.gravitino.Configs.VERSION_RETENTION_COUNT;
@@ -137,6 +138,7 @@ public class TestGenericCatalogOperations {
f.deleteOnExit();
when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);
when(config.get(STORE_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
diff --git a/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/TestModelCatalogOperations.java b/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/TestModelCatalogOperations.java
index 7d7c02a7cd..a4f1119a37 100644
--- a/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/TestModelCatalogOperations.java
+++ b/catalogs/catalog-model/src/test/java/org/apache/gravtitino/catalog/model/TestModelCatalogOperations.java
@@ -39,6 +39,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
import static org.apache.gravitino.Configs.VERSION_RETENTION_COUNT;
@@ -138,6 +139,7 @@ public class TestModelCatalogOperations {
Mockito.when(config.get(ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_MILLISECONDS)).thenReturn(1000L);
when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);
when(config.get(STORE_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
when(config.get(ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericSemanticModel.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericSemanticModel.java
index 014ac26cf6..1e76d6ecf0 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericSemanticModel.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericSemanticModel.java
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.client;
+import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
@@ -48,6 +49,10 @@ class GenericSemanticModel
private final SemanticModelDefinition definition;
private final Map<String, String> properties;
private final Audit audit;
+ private final int revision;
+ private final Status status;
+ @Nullable private final String publishedBy;
+ @Nullable private final Instant publishedAt;
private final MetadataObjectDomainOperations objectDomainOperations;
private final MetadataObjectTagOperations objectTagOperations;
@@ -66,6 +71,10 @@ class GenericSemanticModel
? Collections.emptyMap()
: Collections.unmodifiableMap(new LinkedHashMap<>(sourceProperties));
this.audit = semanticModel.auditInfo();
+ this.revision = semanticModel.revision();
+ this.status = semanticModel.status();
+ this.publishedBy = semanticModel.publishedBy();
+ this.publishedAt = semanticModel.publishedAt();
MetadataObject metadataObject =
MetadataObjects.of(
Arrays.asList(semanticModelNamespace.level(1), semanticModelNamespace.level(2), name),
@@ -112,6 +121,28 @@ class GenericSemanticModel
return audit;
}
+ @Override
+ public int revision() {
+ return revision;
+ }
+
+ @Override
+ public Status status() {
+ return status;
+ }
+
+ @Override
+ @Nullable
+ public String publishedBy() {
+ return publishedBy;
+ }
+
+ @Override
+ @Nullable
+ public Instant publishedAt() {
+ return publishedAt;
+ }
+
/** {@inheritDoc} */
@Override
public SupportsDomains supportsDomains() {
@@ -222,13 +253,18 @@ class GenericSemanticModel
&& Objects.equals(comment, that.comment)
&& definition.equals(that.definition)
&& properties.equals(that.properties)
- && audit.equals(that.audit);
+ && audit.equals(that.audit)
+ && revision == that.revision
+ && status == that.status
+ && Objects.equals(publishedBy, that.publishedBy)
+ && Objects.equals(publishedAt, that.publishedAt);
}
/** {@inheritDoc} */
@Override
public int hashCode() {
- return Objects.hash(name, comment, definition, properties, audit);
+ return Objects.hash(
+ name, comment, definition, properties, audit, revision, status, publishedBy, publishedAt);
}
/** {@inheritDoc} */
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericSemanticModel.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericSemanticModel.java
index e3ffff8c90..be09dd5cae 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericSemanticModel.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGenericSemanticModel.java
@@ -104,6 +104,26 @@ public class TestGenericSemanticModel {
private static SemanticModel semanticModel(
SemanticModelDefinition definition, Map<String, String> properties, Audit audit) {
return new SemanticModel() {
+ @Override
+ public int revision() {
+ return 1;
+ }
+
+ @Override
+ public Status status() {
+ return Status.PUBLISHED;
+ }
+
+ @Override
+ public String publishedBy() {
+ return "user";
+ }
+
+ @Override
+ public Instant publishedAt() {
+ return Instant.EPOCH;
+ }
+
@Override
public String name() {
return "sales_model";
diff --git a/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDTO.java b/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDTO.java
index 850b90b8b3..b7d9fe01f7 100644
--- a/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDTO.java
+++ b/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDTO.java
@@ -21,7 +21,10 @@ package org.apache.gravitino.dto.semantic;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.google.common.base.Preconditions;
+import java.time.Instant;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -32,12 +35,23 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.dto.AuditDTO;
import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelRevision;
/** DTO for a schema-scoped Semantic Model. */
@EqualsAndHashCode
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
-@JsonPropertyOrder({"name", "comment", "definition", "properties", "audit"})
+@JsonPropertyOrder({
+ "name",
+ "revision",
+ "status",
+ "publishedBy",
+ "publishedAt",
+ "comment",
+ "definition",
+ "properties",
+ "audit"
+})
public class SemanticModelDTO implements SemanticModel {
@JsonProperty("name")
@@ -56,6 +70,21 @@ public class SemanticModelDTO implements SemanticModel {
@JsonProperty("audit")
private AuditDTO audit;
+ @JsonProperty("revision")
+ private Integer revision;
+
+ @JsonProperty("status")
+ @JsonSerialize(using = ToStringSerializer.class)
+ private Status status;
+
+ @Nullable
+ @JsonProperty("publishedBy")
+ private String publishedBy;
+
+ @Nullable
+ @JsonProperty("publishedAt")
+ private Instant publishedAt;
+
private SemanticModelDTO() {}
private SemanticModelDTO(
@@ -63,12 +92,41 @@ public class SemanticModelDTO implements SemanticModel {
@Nullable String comment,
SemanticModelDefinitionDTO definition,
@Nullable Map<String, String> properties,
- AuditDTO audit) {
+ AuditDTO audit,
+ @Nullable SemanticModelRevision revisionInfo) {
this.name = name;
this.comment = comment;
this.definition = definition;
this.properties = immutableProperties(properties);
this.audit = audit;
+ if (revisionInfo != null) {
+ this.revision = revisionInfo.revision();
+ this.status = revisionInfo.status();
+ this.publishedBy = revisionInfo.publishedBy();
+ this.publishedAt = revisionInfo.publishedAt();
+ }
+ }
+
+ @Override
+ public int revision() {
+ return revision == null ? 0 : revision;
+ }
+
+ @Override
+ public Status status() {
+ return status;
+ }
+
+ @Override
+ @Nullable
+ public String publishedBy() {
+ return publishedBy;
+ }
+
+ @Override
+ @Nullable
+ public Instant publishedAt() {
+ return publishedAt;
}
@Override
@@ -124,6 +182,7 @@ public class SemanticModelDTO implements SemanticModel {
private SemanticModelDefinitionDTO definition;
@Nullable private Map<String, String> properties;
private AuditDTO audit;
+ @Nullable private SemanticModelRevision revisionInfo;
private Builder() {}
@@ -182,6 +241,17 @@ public class SemanticModelDTO implements SemanticModel {
return this;
}
+ /**
+ * Sets the revision and its publication metadata.
+ *
+ * @param revisionInfo The Semantic Model revision metadata.
+ * @return This builder.
+ */
+ public Builder withRevision(SemanticModelRevision revisionInfo) {
+ this.revisionInfo = revisionInfo;
+ return this;
+ }
+
/**
* Builds a Semantic Model DTO.
*
@@ -193,7 +263,7 @@ public class SemanticModelDTO implements SemanticModel {
Preconditions.checkArgument(definition != null, "definition cannot be null");
Preconditions.checkArgument(audit != null, "audit cannot be null");
- return new SemanticModelDTO(name, comment, definition, properties, audit);
+ return new SemanticModelDTO(name, comment, definition, properties, audit, revisionInfo);
}
}
diff --git a/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelRevisionDTO.java b/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelRevisionDTO.java
new file mode 100644
index 0000000000..34cdf5cf03
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelRevisionDTO.java
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.semantic;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
+import java.time.Instant;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+import org.apache.gravitino.dto.AuditDTO;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.semantic.SemanticModel.Status;
+import org.apache.gravitino.semantic.SemanticModelRevision;
+
+/** The wire representation of a retained revision summary. */
+@EqualsAndHashCode
+@ToString
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public final class SemanticModelRevisionDTO implements SemanticModelRevision {
+ @JsonProperty("revision")
+ private final int revision;
+
+ @JsonProperty("status")
+ @JsonSerialize(using = ToStringSerializer.class)
+ private final Status status;
+
+ @Nullable
+ @JsonProperty("publishedBy")
+ private final String publishedBy;
+
+ @Nullable
+ @JsonProperty("publishedAt")
+ private final Instant publishedAt;
+
+ @JsonProperty("audit")
+ private final AuditDTO audit;
+
+ /**
+ * Creates revision metadata with the writer audit and optional publisher details.
+ *
+ * @param revision The revision number.
+ * @param status The publication status.
+ * @param publishedBy The publishing principal, or null for a draft.
+ * @param publishedAt The publication time, or null for a draft.
+ * @param audit The revision writer's audit information.
+ */
+ @JsonCreator
+ public SemanticModelRevisionDTO(
+ @JsonProperty("revision") int revision,
+ @JsonProperty("status") Status status,
+ @JsonProperty("publishedBy") @Nullable String publishedBy,
+ @JsonProperty("publishedAt") @Nullable Instant publishedAt,
+ @JsonProperty("audit") AuditDTO audit) {
+ this.revision = revision;
+ this.status = status;
+ this.publishedBy = publishedBy;
+ this.publishedAt = publishedAt;
+ this.audit = audit;
+ }
+
+ /**
+ * Creates a wire summary from revision metadata.
+ *
+ * @param revision The retained revision to convert.
+ * @return The corresponding revision summary.
+ */
+ public static SemanticModelRevisionDTO fromRevision(SemanticModelRevision revision) {
+ return new SemanticModelRevisionDTO(
+ revision.revision(),
+ revision.status(),
+ revision.publishedBy(),
+ revision.publishedAt(),
+ DTOConverters.toDTO(revision.auditInfo()));
+ }
+
+ @Override
+ public int revision() {
+ return revision;
+ }
+
+ @Override
+ public Status status() {
+ return status;
+ }
+
+ @Override
+ @Nullable
+ public String publishedBy() {
+ return publishedBy;
+ }
+
+ @Override
+ @Nullable
+ public Instant publishedAt() {
+ return publishedAt;
+ }
+
+ @Override
+ public AuditDTO auditInfo() {
+ return audit;
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java b/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java
index 3eb61ace44..955a4ea4e5 100644
--- a/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java
+++ b/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java
@@ -361,6 +361,7 @@ public class DTOConverters {
*/
public static SemanticModelDTO toDTO(SemanticModel semanticModel) {
return SemanticModelDTO.builder()
+ .withRevision(semanticModel)
.withName(semanticModel.name())
.withComment(semanticModel.comment())
.withDefinition(SemanticModelDefinitionDTO.fromDefinition(semanticModel.definition()))
diff --git a/common/src/test/java/org/apache/gravitino/dto/util/TestSemanticModelDTOConverter.java b/common/src/test/java/org/apache/gravitino/dto/util/TestSemanticModelDTOConverter.java
index b33ab40588..ff47fe19d2 100644
--- a/common/src/test/java/org/apache/gravitino/dto/util/TestSemanticModelDTOConverter.java
+++ b/common/src/test/java/org/apache/gravitino/dto/util/TestSemanticModelDTOConverter.java
@@ -72,6 +72,26 @@ public class TestSemanticModelDTOConverter {
SemanticModel semanticModel =
new SemanticModel() {
+ @Override
+ public int revision() {
+ return 1;
+ }
+
+ @Override
+ public Status status() {
+ return Status.PUBLISHED;
+ }
+
+ @Override
+ public String publishedBy() {
+ return "user";
+ }
+
+ @Override
+ public Instant publishedAt() {
+ return Instant.EPOCH;
+ }
+
@Override
public String name() {
return "sales_model";
diff --git a/core/src/jmh/java/org/apache/gravitino/cache/it/AbstractEntityStorageBenchmark.java b/core/src/jmh/java/org/apache/gravitino/cache/it/AbstractEntityStorageBenchmark.java
index 429bc087ac..47d4f77167 100644
--- a/core/src/jmh/java/org/apache/gravitino/cache/it/AbstractEntityStorageBenchmark.java
+++ b/core/src/jmh/java/org/apache/gravitino/cache/it/AbstractEntityStorageBenchmark.java
@@ -41,6 +41,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.VERSION_RETENTION_COUNT;
import static org.mockito.Mockito.mock;
@@ -313,6 +314,7 @@ public class AbstractEntityStorageBenchmark<E extends Entity & HasIdentifier> {
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ Mockito.when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
// Fix cache config for test
Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(CACHE_ENABLED);
Mockito.when(config.get(Configs.CACHE_MAX_ENTRIES)).thenReturn(10_000);
diff --git a/core/src/main/java/org/apache/gravitino/Configs.java b/core/src/main/java/org/apache/gravitino/Configs.java
index fe19e24f3a..bcfa37634b 100644
--- a/core/src/main/java/org/apache/gravitino/Configs.java
+++ b/core/src/main/java/org/apache/gravitino/Configs.java
@@ -364,6 +364,17 @@ public class Configs {
MAX_VERSION_RETENTION_COUNT))
.createWithDefault(DEFAULT_VERSION_RETENTION_COUNT);
+ /** Number of newest revisions retained per Semantic Model. */
+ public static final ConfigEntry<Long> SEMANTIC_MODEL_VERSION_RETENTION_COUNT =
+ new ConfigBuilder("gravitino.entity.store.semanticModel.versionRetentionCount")
+ .doc(
+ "Number of newest Semantic Model revisions to retain (1–1000). The active "
+ + "revision is retained independently of this count.")
+ .version(ConfigConstants.VERSION_2_0_0)
+ .longConf()
+ .checkValue(v -> v >= 1L && v <= 1000L, "Semantic Model retention count must be 1–1000")
+ .createWithDefault(100L);
+
// The followings are configurations for tree lock
public static final ConfigEntry<Long> TREE_LOCK_MAX_NODE_IN_MEMORY =
diff --git a/core/src/main/java/org/apache/gravitino/EntityStore.java b/core/src/main/java/org/apache/gravitino/EntityStore.java
index cec6be9299..6a2730e5e6 100644
--- a/core/src/main/java/org/apache/gravitino/EntityStore.java
+++ b/core/src/main/java/org/apache/gravitino/EntityStore.java
@@ -30,11 +30,20 @@ import org.apache.commons.lang3.tuple.Pair;
import org.apache.gravitino.Entity.EntityType;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.SemanticModelEntity;
import org.apache.gravitino.semantic.SemanticModelMetric;
import org.apache.gravitino.utils.Executable;
public interface EntityStore extends Closeable {
+ /** Lists model identities for governance, irrespective of publication state. */
+ default List<NameIdentifier> listSemanticModelIdentifiers(Namespace namespace)
+ throws IOException {
+ return list(namespace, SemanticModelEntity.class, EntityType.SEMANTIC_MODEL).stream()
+ .map(SemanticModelEntity::nameIdentifier)
+ .toList();
+ }
+
/**
* Reads metric identifiers in a schema without loading complete Semantic Models.
*
diff --git a/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java b/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java
index ab4249ab8e..de81a6731f 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.catalog;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.time.Instant;
+import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
@@ -41,6 +42,7 @@ import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.SemanticModelEntity;
import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.semantic.SemanticModel.Status;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.semantic.SemanticModelMetric;
@@ -158,6 +160,15 @@ public class ManagedSemanticModelOperations {
}
}
+ /** Returns whether the identity exists, even when the model has no active revision. */
+ public boolean semanticModelExists(NameIdentifier ident) {
+ try {
+ return store.exists(ident, Entity.EntityType.SEMANTIC_MODEL);
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to check Semantic Model " + ident, e);
+ }
+ }
+
/**
* Creates a model with its validated source associations.
*
@@ -186,7 +197,8 @@ public class ManagedSemanticModelOperations {
writeValidator.accept(ident, definition);
sourceUpdate.validate(definition);
- Instant now = Instant.now();
+ Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS);
+ String writer = PrincipalUtils.getCurrentUserName();
SemanticModelEntity entity =
SemanticModelEntity.builder()
.withId(idGenerator.nextId())
@@ -196,11 +208,8 @@ public class ManagedSemanticModelOperations {
.withDefinition(definition)
.withSourceUpdate(sourceUpdate)
.withProperties(properties)
- .withAuditInfo(
- AuditInfo.builder()
- .withCreator(PrincipalUtils.getCurrentUserName())
- .withCreateTime(now)
- .build())
+ .withRevision(1, Status.PUBLISHED, writer, now)
+ .withAuditInfo(AuditInfo.builder().withCreator(writer).withCreateTime(now).build())
.build();
try {
@@ -335,6 +344,8 @@ public class ManagedSemanticModelOperations {
}
AuditInfo oldAudit = oldEntity.auditInfo();
+ Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS);
+ String writer = PrincipalUtils.getCurrentUserName();
return SemanticModelEntity.builder()
.withId(oldEntity.id())
.withName(newName)
@@ -343,12 +354,13 @@ public class ManagedSemanticModelOperations {
.withDefinition(newDefinition)
.withSourceUpdate(sourceUpdate)
.withProperties(newProperties)
+ .withRevision(Math.incrementExact(oldEntity.revision()), Status.PUBLISHED, writer, now)
.withAuditInfo(
AuditInfo.builder()
.withCreator(oldAudit.creator())
.withCreateTime(oldAudit.createTime())
- .withLastModifier(PrincipalUtils.getCurrentUserName())
- .withLastModifiedTime(Instant.now())
+ .withLastModifier(writer)
+ .withLastModifiedTime(now)
.build())
.build();
}
diff --git a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java
index 40d9b03509..fdbb1bb216 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java
@@ -161,13 +161,17 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher
@Override
public SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException {
- checkRelationalCatalog(ident.namespace());
- if (!schemaDispatcher.schemaExists(schemaIdentifier(ident))) {
- throw new NoSuchSemanticModelException("Semantic Model %s does not exist", ident);
- }
+ checkModelParent(ident);
return managedOperations.loadSemanticModel(ident);
}
+ @Override
+ public boolean semanticModelExists(NameIdentifier ident) {
+ checkRelationalCatalog(ident.namespace());
+ return schemaDispatcher.schemaExists(schemaIdentifier(ident))
+ && managedOperations.semanticModelExists(ident);
+ }
+
@Override
public SemanticModel createSemanticModel(
NameIdentifier ident,
@@ -233,6 +237,13 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher
return managedOperations.dropSemanticModel(ident);
}
+ private void checkModelParent(NameIdentifier ident) {
+ checkRelationalCatalog(ident.namespace());
+ if (!schemaDispatcher.schemaExists(schemaIdentifier(ident))) {
+ throw new NoSuchSemanticModelException("Semantic Model %s does not exist", ident);
+ }
+ }
+
private void checkRelationalCatalog(Namespace namespace) {
NameIdentifier catalogIdent = NameIdentifier.of(namespace.level(0), namespace.level(1));
Catalog catalog = catalogManager.loadCatalog(catalogIdent);
diff --git a/core/src/main/java/org/apache/gravitino/domain/DomainMembershipResolver.java b/core/src/main/java/org/apache/gravitino/domain/DomainMembershipResolver.java
index 94384947f6..98398f9a37 100644
--- a/core/src/main/java/org/apache/gravitino/domain/DomainMembershipResolver.java
+++ b/core/src/main/java/org/apache/gravitino/domain/DomainMembershipResolver.java
@@ -58,7 +58,6 @@ import org.apache.gravitino.meta.FilesetEntity;
import org.apache.gravitino.meta.GenericEntity;
import org.apache.gravitino.meta.ModelEntity;
import org.apache.gravitino.meta.SchemaEntity;
-import org.apache.gravitino.meta.SemanticModelEntity;
import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.meta.TagEntity;
import org.apache.gravitino.meta.TopicEntity;
@@ -611,8 +610,12 @@ final class DomainMembershipResolver {
break;
case SEMANTIC_MODEL:
leaves =
- listMetadataObjects(
- namespace, SemanticModelEntity.class, Entity.EntityType.SEMANTIC_MODEL);
+ store.listSemanticModelIdentifiers(namespace).stream()
+ .map(
+ ident ->
+ NameIdentifierUtil.toMetadataObject(
+ ident, Entity.EntityType.SEMANTIC_MODEL))
+ .toList();
break;
default:
throw new IllegalArgumentException("Unsupported domain member type " + type);
diff --git a/core/src/main/java/org/apache/gravitino/meta/SemanticModelEntity.java b/core/src/main/java/org/apache/gravitino/meta/SemanticModelEntity.java
index b4b89fa623..7b2ec2e7bb 100644
--- a/core/src/main/java/org/apache/gravitino/meta/SemanticModelEntity.java
+++ b/core/src/main/java/org/apache/gravitino/meta/SemanticModelEntity.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.meta;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
+import java.time.Instant;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
@@ -78,6 +79,10 @@ public class SemanticModelEntity implements Entity, Auditable, HasIdentifier, Se
private SemanticModelDefinition definition;
private Map<String, String> properties = Collections.emptyMap();
private AuditInfo auditInfo;
+ private int revision = 1;
+ private Status status = Status.PUBLISHED;
+ @Nullable private String publishedBy;
+ @Nullable private Instant publishedAt;
@JsonIgnore @ToString.Exclude
private transient SemanticModelSourceUpdate sourceUpdate = SemanticModelSourceUpdate.preserve();
@@ -186,6 +191,28 @@ public class SemanticModelEntity implements Entity, Auditable, HasIdentifier, Se
return auditInfo;
}
+ @Override
+ public int revision() {
+ return revision;
+ }
+
+ @Override
+ public Status status() {
+ return status;
+ }
+
+ @Override
+ @Nullable
+ public String publishedBy() {
+ return publishedBy;
+ }
+
+ @Override
+ @Nullable
+ public Instant publishedAt() {
+ return publishedAt;
+ }
+
/**
* Returns the Semantic Model entity type.
*
@@ -227,7 +254,11 @@ public class SemanticModelEntity implements Entity, Auditable, HasIdentifier, Se
&& Objects.equals(comment, that.comment)
&& Objects.equals(definition, that.definition)
&& Objects.equals(properties, that.properties)
- && Objects.equals(auditInfo, that.auditInfo);
+ && Objects.equals(auditInfo, that.auditInfo)
+ && revision == that.revision
+ && status == that.status
+ && Objects.equals(publishedBy, that.publishedBy)
+ && Objects.equals(publishedAt, that.publishedAt);
}
/**
@@ -237,7 +268,18 @@ public class SemanticModelEntity implements Entity, Auditable, HasIdentifier, Se
*/
@Override
public int hashCode() {
- return Objects.hash(id, name, namespace, comment, definition, properties, auditInfo);
+ return Objects.hash(
+ id,
+ name,
+ namespace,
+ comment,
+ definition,
+ properties,
+ auditInfo,
+ revision,
+ status,
+ publishedBy,
+ publishedAt);
}
/**
@@ -347,6 +389,16 @@ public class SemanticModelEntity implements Entity, Auditable, HasIdentifier, Se
return this;
}
+ /** Sets the snapshot number and its publication metadata. */
+ public Builder withRevision(
+ int revision, Status status, @Nullable String publishedBy, @Nullable Instant publishedAt) {
+ semanticModel.revision = revision;
+ semanticModel.status = status;
+ semanticModel.publishedBy = publishedBy;
+ semanticModel.publishedAt = publishedAt;
+ return this;
+ }
+
/**
* Builds and validates the Semantic Model entity.
*
@@ -354,6 +406,17 @@ public class SemanticModelEntity implements Entity, Auditable, HasIdentifier, Se
* @throws IllegalArgumentException If a required field is missing or has the wrong type.
*/
public SemanticModelEntity build() {
+ if (semanticModel.status == Status.PUBLISHED
+ && semanticModel.publishedBy == null
+ && semanticModel.auditInfo != null) {
+ AuditInfo audit = semanticModel.auditInfo;
+ semanticModel.publishedBy =
+ audit.lastModifier() == null ? audit.creator() : audit.lastModifier();
+ Instant writtenAt =
+ audit.lastModifiedTime() == null ? audit.createTime() : audit.lastModifiedTime();
+ semanticModel.publishedAt =
+ writtenAt == null ? null : Instant.ofEpochMilli(writtenAt.toEpochMilli());
+ }
semanticModel.validate();
return semanticModel;
}
diff --git a/core/src/main/java/org/apache/gravitino/semantic/SemanticModelRevisionSelector.java b/core/src/main/java/org/apache/gravitino/semantic/SemanticModelRevisionSelector.java
new file mode 100644
index 0000000000..19d25a3676
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/semantic/SemanticModelRevisionSelector.java
@@ -0,0 +1,53 @@
+/*
+ * 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.semantic;
+
+import com.google.common.base.Preconditions;
+
+/** Selects a snapshot relative to the Semantic Model identity. */
+public final class SemanticModelRevisionSelector {
+
+ /** Selects the revision visible to consumers. */
+ public static final SemanticModelRevisionSelector ACTIVE = new SemanticModelRevisionSelector(0);
+
+ /** Selects the latest saved revision. */
+ public static final SemanticModelRevisionSelector LATEST = new SemanticModelRevisionSelector(-1);
+
+ private final int number;
+
+ private SemanticModelRevisionSelector(int number) {
+ this.number = number;
+ }
+
+ /** Returns a selector for the given positive revision number. */
+ public static SemanticModelRevisionSelector numbered(int number) {
+ Preconditions.checkArgument(number > 0, "Revision must be positive: %s", number);
+ return new SemanticModelRevisionSelector(number);
+ }
+
+ /**
+ * Returns the revision number or the reserved value for a pointer selector.
+ *
+ * @return {@code 0} for {@link #ACTIVE}, {@code -1} for {@link #LATEST}, or the positive revision
+ * number for a numbered selector.
+ */
+ public int getNumber() {
+ return number;
+ }
+}
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 1c153f6686..a19f8a500c 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
@@ -142,6 +142,11 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
return SchemaMetaService.getInstance().listDescendantSchemas(identifier);
}
+ @Override
+ public List<NameIdentifier> listSemanticModelIdentifiers(Namespace namespace) throws IOException {
+ return SemanticModelMetaService.getInstance().listSemanticModelIdentifiers(namespace);
+ }
+
@Override
public List<NameIdentifier> listSemanticModelMetrics(Namespace namespace) throws IOException {
return SemanticModelMetricService.getInstance().listMetrics(namespace);
@@ -211,6 +216,9 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
@Override
public boolean exists(NameIdentifier ident, Entity.EntityType entityType) throws IOException {
+ if (entityType == Entity.EntityType.SEMANTIC_MODEL) {
+ return SemanticModelMetaService.getInstance().semanticModelExists(ident);
+ }
try {
Entity entity = get(ident, entityType);
return entity != null;
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java
index 476d6219e1..f3156e1d7c 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalBackend.java
@@ -37,6 +37,7 @@ import org.apache.gravitino.SupportsRelationOperations;
import org.apache.gravitino.SupportsTableIdLookup;
import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.SemanticModelEntity;
import org.apache.gravitino.semantic.SemanticModelMetric;
/** Interface defining the operations for a Relation Backend. */
@@ -56,6 +57,15 @@ public interface RelationalBackend
return get(identifier, Entity.EntityType.TABLE).id();
}
+ /** Lists model identities for governance, irrespective of publication state. */
+ default List<NameIdentifier> listSemanticModelIdentifiers(Namespace namespace)
+ throws IOException {
+ return this.<SemanticModelEntity>list(namespace, Entity.EntityType.SEMANTIC_MODEL, false)
+ .stream()
+ .map(SemanticModelEntity::nameIdentifier)
+ .toList();
+ }
+
/**
* Reads metric identifiers in a schema without loading complete Semantic Models.
*
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 13ef64a546..4183238a4a 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
@@ -259,6 +259,11 @@ public class RelationalEntityStore
return backend.listDescendantSchemas(identifier);
}
+ @Override
+ public List<NameIdentifier> listSemanticModelIdentifiers(Namespace namespace) throws IOException {
+ return backend.listSemanticModelIdentifiers(namespace);
+ }
+
@Override
public List<NameIdentifier> listSemanticModelMetrics(Namespace namespace) throws IOException {
return backend.listSemanticModelMetrics(namespace);
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalGarbageCollector.java b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalGarbageCollector.java
index efab318714..9b2b7a7e66 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/RelationalGarbageCollector.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/RelationalGarbageCollector.java
@@ -20,6 +20,7 @@
package org.apache.gravitino.storage.relational;
import static org.apache.gravitino.Configs.GARBAGE_COLLECTOR_SINGLE_DELETION_LIMIT;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.VERSION_RETENTION_COUNT;
@@ -43,6 +44,7 @@ public final class RelationalGarbageCollector implements Closeable {
private final long storeDeleteAfterTimeMillis;
private final long versionRetentionCount;
+ private final long semanticModelVersionRetentionCount;
@VisibleForTesting
final ScheduledExecutorService garbageCollectorPool =
@@ -59,6 +61,7 @@ public final class RelationalGarbageCollector implements Closeable {
this.backend = backend;
storeDeleteAfterTimeMillis = config.get(STORE_DELETE_AFTER_TIME);
versionRetentionCount = config.get(VERSION_RETENTION_COUNT);
+ semanticModelVersionRetentionCount = config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT);
}
public void start() {
@@ -114,13 +117,17 @@ public final class RelationalGarbageCollector implements Closeable {
LOG.info("Start to collect and delete old version data by thread {}", threadId);
for (Entity.EntityType entityType : Entity.EntityType.values()) {
long deletedCount = Long.MAX_VALUE;
+ long retentionCount =
+ entityType == Entity.EntityType.SEMANTIC_MODEL
+ ? semanticModelVersionRetentionCount
+ : versionRetentionCount;
LOG.debug(
"Try to softly delete {} old version data that has been over retention count {}",
entityType,
- versionRetentionCount);
+ retentionCount);
try {
while (deletedCount > 0) {
- deletedCount = backend.deleteOldVersionData(entityType, versionRetentionCount);
+ deletedCount = backend.deleteOldVersionData(entityType, retentionCount);
}
} catch (RuntimeException e) {
LOG.error(
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaMapper.java
index dc59fb0c1c..cdf36678f9 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaMapper.java
@@ -19,6 +19,8 @@
package org.apache.gravitino.storage.relational.mapper;
import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;
import org.apache.gravitino.storage.relational.po.SemanticModelPO;
import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
import org.apache.ibatis.annotations.DeleteProvider;
@@ -51,7 +53,9 @@ public interface SemanticModelMetaMapper {
@Result(property = "schemaId", column = "version_schema_id"),
@Result(property = "semanticModelId", column = "version_semantic_model_id"),
@Result(property = "version", column = "version"),
- @Result(property = "semanticModelName", column = "version_semantic_model_name"),
+ @Result(property = "publicationStatus", column = "publication_status"),
+ @Result(property = "publishedBy", column = "published_by"),
+ @Result(property = "publishedAt", column = "published_at"),
@Result(property = "semanticModelComment", column = "semantic_model_comment"),
@Result(property = "datasets", column = "datasets"),
@Result(property = "relationships", column = "relationships"),
@@ -75,6 +79,7 @@ public interface SemanticModelMetaMapper {
@Result(property = "catalogId", column = "catalog_id"),
@Result(property = "schemaId", column = "schema_id"),
@Result(property = "currentVersion", column = "current_version"),
+ @Result(property = "activeVersion", column = "active_version"),
@Result(property = "lastVersion", column = "last_version"),
@Result(property = "auditInfo", column = "audit_info"),
@Result(property = "deletedAt", column = "deleted_at"),
@@ -83,7 +88,7 @@ public interface SemanticModelMetaMapper {
javaType = SemanticModelVersionInfoPO.class,
column =
"{id,version_metalake_id,version_catalog_id,version_schema_id,"
- + "version_semantic_model_id,version,version_semantic_model_name,"
+ + "version_semantic_model_id,version,publication_status,published_by,published_at,"
+ "semantic_model_comment,datasets,relationships,metrics,ai_context,"
+ "custom_extensions,properties,"
+ "version_audit_info,version_deleted_at}",
@@ -92,7 +97,9 @@ public interface SemanticModelMetaMapper {
@SelectProvider(
type = SemanticModelMetaSQLProviderFactory.class,
method = "listSemanticModelPOsBySchemaId")
- List<SemanticModelPO> listSemanticModelPOsBySchemaId(@Param("schemaId") Long schemaId);
+ List<SemanticModelPO> listSemanticModelPOsBySchemaId(
+ @Param("schemaId") Long schemaId,
+ @Param("selector") @Nullable SemanticModelRevisionSelector selector);
/**
* Lists active Semantic Model identities by stable IDs without loading definition snapshots.
@@ -118,7 +125,8 @@ public interface SemanticModelMetaMapper {
List<SemanticModelPO> listSemanticModelPOsByFullQualifiedName(
@Param("metalakeName") String metalakeName,
@Param("catalogName") String catalogName,
- @Param("schemaName") String schemaName);
+ @Param("schemaName") String schemaName,
+ @Param("selector") @Nullable SemanticModelRevisionSelector selector);
/** Selects an active Semantic Model ID by schema ID and name. */
@SelectProvider(
@@ -133,7 +141,9 @@ public interface SemanticModelMetaMapper {
type = SemanticModelMetaSQLProviderFactory.class,
method = "selectSemanticModelMetaBySchemaIdAndName")
SemanticModelPO selectSemanticModelMetaBySchemaIdAndName(
- @Param("schemaId") Long schemaId, @Param("semanticModelName") String semanticModelName);
+ @Param("schemaId") Long schemaId,
+ @Param("semanticModelName") String semanticModelName,
+ @Param("selector") @Nullable SemanticModelRevisionSelector selector);
/** Selects and locks an active Semantic Model identity by schema ID and name. */
@SelectProvider(
@@ -147,7 +157,9 @@ public interface SemanticModelMetaMapper {
@SelectProvider(
type = SemanticModelMetaSQLProviderFactory.class,
method = "selectSemanticModelMetaById")
- SemanticModelPO selectSemanticModelMetaById(@Param("semanticModelId") Long semanticModelId);
+ SemanticModelPO selectSemanticModelMetaById(
+ @Param("semanticModelId") Long semanticModelId,
+ @Param("selector") SemanticModelRevisionSelector selector);
/** Selects and locks a Semantic Model identity by stable ID. */
@SelectProvider(
@@ -165,7 +177,8 @@ public interface SemanticModelMetaMapper {
@Param("metalakeName") String metalakeName,
@Param("catalogName") String catalogName,
@Param("schemaName") String schemaName,
- @Param("semanticModelName") String semanticModelName);
+ @Param("semanticModelName") String semanticModelName,
+ @Param("selector") @Nullable SemanticModelRevisionSelector selector);
/** Inserts a Semantic Model identity row. */
@InsertProvider(
@@ -181,13 +194,13 @@ public interface SemanticModelMetaMapper {
@Param("newSemanticModelMeta") SemanticModelPO newSemanticModelPO,
@Param("oldSemanticModelMeta") SemanticModelPO oldSemanticModelPO);
- /** Soft-deletes a Semantic Model identity by stable ID and expected current version. */
+ /** Soft-deletes a Semantic Model identity by stable ID and observed name. */
@UpdateProvider(
type = SemanticModelMetaSQLProviderFactory.class,
method = "softDeleteSemanticModelMetasBySemanticModelId")
Integer softDeleteSemanticModelMetasBySemanticModelId(
@Param("semanticModelId") Long semanticModelId,
- @Param("currentVersion") Integer currentVersion);
+ @Param("semanticModelName") String semanticModelName);
/** Soft-deletes Semantic Model identities under a metalake. */
@UpdateProvider(
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaSQLProviderFactory.java
index b0b7fe4d6a..dfab9228a2 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetaSQLProviderFactory.java
@@ -21,6 +21,8 @@ package org.apache.gravitino.storage.relational.mapper;
import com.google.common.collect.ImmutableMap;
import java.util.List;
import java.util.Map;
+import javax.annotation.Nullable;
+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;
import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;
import org.apache.gravitino.storage.relational.mapper.provider.base.SemanticModelMetaBaseSQLProvider;
import org.apache.gravitino.storage.relational.mapper.provider.postgresql.SemanticModelMetaPostgreSQLProvider;
@@ -53,17 +55,20 @@ public class SemanticModelMetaSQLProviderFactory {
static class SemanticModelMetaH2Provider extends SemanticModelMetaBaseSQLProvider {}
/** Provides SQL for listing Semantic Models by schema ID. */
- public static String listSemanticModelPOsBySchemaId(@Param("schemaId") Long schemaId) {
- return getProvider().listSemanticModelPOsBySchemaId(schemaId);
+ public static String listSemanticModelPOsBySchemaId(
+ @Param("schemaId") Long schemaId,
+ @Param("selector") @Nullable SemanticModelRevisionSelector selector) {
+ return getProvider().listSemanticModelPOsBySchemaId(schemaId, selector);
}
/** Provides SQL for listing Semantic Models by fully qualified schema name. */
public static String listSemanticModelPOsByFullQualifiedName(
@Param("metalakeName") String metalakeName,
@Param("catalogName") String catalogName,
- @Param("schemaName") String schemaName) {
+ @Param("schemaName") String schemaName,
+ @Param("selector") @Nullable SemanticModelRevisionSelector selector) {
return getProvider()
- .listSemanticModelPOsByFullQualifiedName(metalakeName, catalogName, schemaName);
+ .listSemanticModelPOsByFullQualifiedName(metalakeName, catalogName, schemaName, selector);
}
/** Provides SQL for selecting a Semantic Model ID by schema ID and name. */
@@ -74,8 +79,11 @@ public class SemanticModelMetaSQLProviderFactory {
/** Provides SQL for selecting a Semantic Model by schema ID and name. */
public static String selectSemanticModelMetaBySchemaIdAndName(
- @Param("schemaId") Long schemaId, @Param("semanticModelName") String semanticModelName) {
- return getProvider().selectSemanticModelMetaBySchemaIdAndName(schemaId, semanticModelName);
+ @Param("schemaId") Long schemaId,
+ @Param("semanticModelName") String semanticModelName,
+ @Param("selector") @Nullable SemanticModelRevisionSelector selector) {
+ return getProvider()
+ .selectSemanticModelMetaBySchemaIdAndName(schemaId, semanticModelName, selector);
}
/** Provides SQL for selecting and locking a Semantic Model identity by schema ID and name. */
@@ -86,8 +94,10 @@ public class SemanticModelMetaSQLProviderFactory {
}
/** Provides SQL for selecting a Semantic Model by stable ID. */
- public static String selectSemanticModelMetaById(@Param("semanticModelId") Long semanticModelId) {
- return getProvider().selectSemanticModelMetaById(semanticModelId);
+ public static String selectSemanticModelMetaById(
+ @Param("semanticModelId") Long semanticModelId,
+ @Param("selector") SemanticModelRevisionSelector selector) {
+ return getProvider().selectSemanticModelMetaById(semanticModelId, selector);
}
/** Provides SQL for selecting and locking a Semantic Model identity by stable ID. */
@@ -101,10 +111,11 @@ public class SemanticModelMetaSQLProviderFactory {
@Param("metalakeName") String metalakeName,
@Param("catalogName") String catalogName,
@Param("schemaName") String schemaName,
- @Param("semanticModelName") String semanticModelName) {
+ @Param("semanticModelName") String semanticModelName,
+ @Param("selector") @Nullable SemanticModelRevisionSelector selector) {
return getProvider()
.selectSemanticModelByFullQualifiedName(
- metalakeName, catalogName, schemaName, semanticModelName);
+ metalakeName, catalogName, schemaName, semanticModelName, selector);
}
/** Provides SQL for inserting a Semantic Model identity. */
@@ -120,12 +131,12 @@ public class SemanticModelMetaSQLProviderFactory {
return getProvider().updateSemanticModelMeta(newSemanticModelPO, oldSemanticModelPO);
}
- /** Provides SQL for soft-deleting a Semantic Model identity by stable ID and current version. */
+ /** Provides SQL for soft-deleting a Semantic Model identity by stable ID and observed name. */
public static String softDeleteSemanticModelMetasBySemanticModelId(
@Param("semanticModelId") Long semanticModelId,
- @Param("currentVersion") Integer currentVersion) {
+ @Param("semanticModelName") String semanticModelName) {
return getProvider()
- .softDeleteSemanticModelMetasBySemanticModelId(semanticModelId, currentVersion);
+ .softDeleteSemanticModelMetasBySemanticModelId(semanticModelId, semanticModelName);
}
/** Provides SQL for soft-deleting Semantic Model identities by metalake ID. */
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricMapper.java
index 549172b535..6abcd4bff0 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricMapper.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.storage.relational.mapper;
import java.util.List;
+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;
import org.apache.gravitino.storage.relational.po.SemanticModelMetricListingPO;
import org.apache.gravitino.storage.relational.po.SemanticModelMetricPO;
import org.apache.ibatis.annotations.DeleteProvider;
@@ -32,13 +33,6 @@ public interface SemanticModelMetricMapper {
/** The metric identity table name. */
String TABLE_NAME = "semantic_model_metric_meta";
- /** Lists live metric and model names in one statement without reading snapshots. */
- @SelectProvider(type = SemanticModelMetricSQLProviderFactory.class, method = "listMetricNames")
- List<SemanticModelMetricListingPO> listMetricNames(
- @Param("metalakeName") String metalakeName,
- @Param("catalogName") String catalogName,
- @Param("schemaName") String schemaName);
-
/** Lists model names and current metric arrays in one statement without reading identities. */
@SelectProvider(
type = SemanticModelMetricSQLProviderFactory.class,
@@ -46,7 +40,8 @@ public interface SemanticModelMetricMapper {
List<SemanticModelMetricListingPO> listMetricSnapshots(
@Param("metalakeName") String metalakeName,
@Param("catalogName") String catalogName,
- @Param("schemaName") String schemaName);
+ @Param("schemaName") String schemaName,
+ @Param("selector") SemanticModelRevisionSelector selector);
/** Inserts new metric identities in one statement. */
@InsertProvider(
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricSQLProviderFactory.java
index 17052032a7..bf3ed9248c 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelMetricSQLProviderFactory.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.storage.relational.mapper;
import com.google.common.collect.ImmutableMap;
import java.util.List;
import java.util.Map;
+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;
import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;
import org.apache.gravitino.storage.relational.mapper.provider.base.SemanticModelMetricBaseSQLProvider;
import org.apache.gravitino.storage.relational.mapper.provider.postgresql.SemanticModelMetricPostgreSQLProvider;
@@ -46,20 +47,13 @@ public class SemanticModelMetricSQLProviderFactory {
return PROVIDERS.get(JDBCBackendType.fromString(databaseId));
}
- /** Lists live metric and model names in one statement without reading snapshots. */
- public static String listMetricNames(
- @Param("metalakeName") String metalakeName,
- @Param("catalogName") String catalogName,
- @Param("schemaName") String schemaName) {
- return getProvider().listMetricNames(metalakeName, catalogName, schemaName);
- }
-
/** Lists model names and current metric arrays in one statement without reading identities. */
public static String listMetricSnapshots(
@Param("metalakeName") String metalakeName,
@Param("catalogName") String catalogName,
- @Param("schemaName") String schemaName) {
- return getProvider().listMetricSnapshots(metalakeName, catalogName, schemaName);
+ @Param("schemaName") String schemaName,
+ @Param("selector") SemanticModelRevisionSelector selector) {
+ return getProvider().listMetricSnapshots(metalakeName, catalogName, schemaName, selector);
}
/** Returns SQL for inserting new metric identities in one statement. */
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelSourceMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelSourceMapper.java
index c089751f53..dd14c92dad 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelSourceMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelSourceMapper.java
@@ -25,6 +25,7 @@ import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
+import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
/** Reads and persists dataset-to-source associations and their retirement state. */
@@ -36,16 +37,31 @@ public interface SemanticModelSourceMapper {
@Insert(
"""
<script>INSERT INTO semantic_model_source_rel
- (metalake_id, semantic_model_id, dataset_name, source_type, source_id, deleted_at) VALUES
+ (metalake_id, semantic_model_id, dataset_name, source_type, source_id, from_version, deleted_at) VALUES
<foreach collection='sources' item='source' separator=','>
- (#{metalakeId}, #{modelId}, #{source.datasetName}, #{source.sourceType}, #{source.sourceId}, 0)
+ (#{metalakeId}, #{modelId}, #{source.datasetName}, #{source.sourceType}, #{source.sourceId}, #{revision}, 0)
</foreach></script>
""")
void insertSources(
@Param("metalakeId") long metalakeId,
@Param("modelId") long modelId,
+ @Param("revision") int revision,
@Param("sources") List<SemanticModelSource> sources);
+ /** Closes the open ranges when a new snapshot replaces their associations. */
+ @Update(
+ """
+ UPDATE semantic_model_source_rel SET to_version = #{revision}
+ WHERE semantic_model_id = #{modelId} AND to_version = 0 AND deleted_at = 0
+ """)
+ int closeSourceRanges(@Param("modelId") long modelId, @Param("revision") int revision);
+
+ /** Retires ranges that no longer cover a retained revision. */
+ @UpdateProvider(
+ type = SemanticModelSourceSQLProviderFactory.class,
+ method = "softDeleteUnreferencedRanges")
+ int softDeleteUnreferencedRanges(@Param("modelId") long modelId);
+
/** Retires all live associations of a model. */
@UpdateProvider(
type = SemanticModelSourceSQLProviderFactory.class,
@@ -88,7 +104,9 @@ public interface SemanticModelSourceMapper {
JOIN schema_meta ON schema_meta.schema_id = model.schema_id AND schema_meta.deleted_at = 0
JOIN catalog_meta catalog ON catalog.catalog_id = model.catalog_id AND catalog.deleted_at = 0
JOIN metalake_meta metalake ON metalake.metalake_id = rel.metalake_id AND metalake.deleted_at = 0
- WHERE rel.deleted_at = 0 AND rel.metalake_id = #{metalakeId} AND rel.source_type = #{sourceType} AND rel.source_id = #{sourceId}
+ WHERE rel.from_version <= model.active_version
+ AND (rel.to_version = 0 OR rel.to_version > model.active_version)
+ AND rel.deleted_at = 0 AND rel.metalake_id = #{metalakeId} AND rel.source_type = #{sourceType} AND rel.source_id = #{sourceId}
""")
List<SemanticModelSourceListingPO> listForSource(
@Param("metalakeId") long metalakeId,
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelSourceSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelSourceSQLProviderFactory.java
index 34d6edafeb..b86a6dde59 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelSourceSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelSourceSQLProviderFactory.java
@@ -50,6 +50,11 @@ public class SemanticModelSourceSQLProviderFactory {
return getProvider().softDeleteByModelId(modelId);
}
+ /** Provides SQL for retiring closed ranges without a retained snapshot. */
+ public static String softDeleteUnreferencedRanges(@Param("modelId") long modelId) {
+ return getProvider().softDeleteUnreferencedRanges(modelId);
+ }
+
/** Retires live associations owned by models in the given schemas. */
public static String softDeleteBySchemaIds(@Param("schemaIds") List<Long> schemaIds) {
return getProvider().softDeleteBySchemaIds(schemaIds);
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoMapper.java
index 81437cc584..8626445843 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoMapper.java
@@ -92,5 +92,6 @@ public interface SemanticModelVersionInfoMapper {
Integer softDeleteSemanticModelVersionsByRetentionLine(
@Param("semanticModelId") Long semanticModelId,
@Param("versionRetentionLine") long versionRetentionLine,
+ @Param("activeVersion") int activeVersion,
@Param("limit") int limit);
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoSQLProviderFactory.java
index d069d814ab..a4147f800a 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoSQLProviderFactory.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelVersionInfoSQLProviderFactory.java
@@ -106,9 +106,10 @@ public class SemanticModelVersionInfoSQLProviderFactory {
public static String softDeleteSemanticModelVersionsByRetentionLine(
@Param("semanticModelId") Long semanticModelId,
@Param("versionRetentionLine") long versionRetentionLine,
+ @Param("activeVersion") int activeVersion,
@Param("limit") int limit) {
return getProvider()
.softDeleteSemanticModelVersionsByRetentionLine(
- semanticModelId, versionRetentionLine, limit);
+ semanticModelId, versionRetentionLine, activeVersion, limit);
}
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetaBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetaBaseSQLProvider.java
index 0f114f3900..71890395a8 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetaBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetaBaseSQLProvider.java
@@ -22,6 +22,8 @@ import static org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMa
import static org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper.VERSION_TABLE_NAME;
import java.util.List;
+import javax.annotation.Nullable;
+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
@@ -31,40 +33,72 @@ import org.apache.ibatis.annotations.Param;
/** Provides MySQL-compatible SQL for Semantic Model identity metadata. */
public class SemanticModelMetaBaseSQLProvider {
- private static final String CURRENT_SNAPSHOT_COLUMNS =
- " smm.semantic_model_id, smm.semantic_model_name, smm.metalake_id,"
- + " smm.catalog_id, smm.schema_id, smm.current_version, smm.last_version,"
- + " smm.audit_info, smm.deleted_at, smvi.id,"
- + " smvi.metalake_id as version_metalake_id,"
- + " smvi.catalog_id as version_catalog_id,"
- + " smvi.schema_id as version_schema_id,"
- + " smvi.semantic_model_id as version_semantic_model_id, smvi.version,"
- + " smvi.semantic_model_name as version_semantic_model_name,"
+ private static final String MODEL_COLUMNS =
+ " smm.semantic_model_id, smm.semantic_model_name, smm.current_version,"
+ + " smm.active_version, smm.last_version, smm.audit_info, smm.deleted_at";
+
+ private static final String SNAPSHOT_COLUMNS =
+ ", smvi.id, smvi.metalake_id AS version_metalake_id,"
+ + " smvi.catalog_id AS version_catalog_id, smvi.schema_id AS version_schema_id,"
+ + " smvi.semantic_model_id AS version_semantic_model_id, smvi.version,"
+ + " smvi.publication_status, smvi.published_by, smvi.published_at,"
+ " smvi.semantic_model_comment, smvi.datasets, smvi.relationships, smvi.metrics,"
+ " smvi.ai_context, smvi.custom_extensions, smvi.properties,"
- + " smvi.audit_info as version_audit_info,"
- + " smvi.deleted_at as version_deleted_at";
+ + " smvi.audit_info AS version_audit_info, smvi.deleted_at AS version_deleted_at";
- /** Returns SQL for listing current Semantic Model snapshots by schema ID. */
- public String listSemanticModelPOsBySchemaId(@Param("schemaId") Long schemaId) {
- return "SELECT"
- + CURRENT_SNAPSHOT_COLUMNS
- + " FROM "
- + TABLE_NAME
- + " smm INNER JOIN "
- + VERSION_TABLE_NAME
- + " smvi ON smm.semantic_model_id = smvi.semantic_model_id"
- + " AND smm.current_version = smvi.version"
- + " WHERE smm.schema_id = #{schemaId}"
- + " AND smm.deleted_at = 0 AND smvi.deleted_at = 0";
+ /** Returns SQL for listing Semantic Models with the selected snapshots by schema ID. */
+ public String listSemanticModelPOsBySchemaId(
+ @Param("schemaId") Long schemaId,
+ @Param("selector") @Nullable SemanticModelRevisionSelector selector) {
+ return selectModels(selector) + " AND smm.schema_id = #{schemaId}";
}
- /** Returns SQL for listing current Semantic Model snapshots by qualified schema name. */
+ /** Returns SQL for listing Semantic Models by qualified schema name. */
public String listSemanticModelPOsByFullQualifiedName(
@Param("metalakeName") String metalakeName,
@Param("catalogName") String catalogName,
- @Param("schemaName") String schemaName) {
- return qualifiedNameSelect(false);
+ @Param("schemaName") String schemaName,
+ @Param("selector") @Nullable SemanticModelRevisionSelector selector) {
+ return qualifiedNameSelect(false, selector);
+ }
+
+ /**
+ * Joins the selected live snapshot to a model identity. A null selector reads identity only.
+ *
+ * @param model The model alias declared by the provider.
+ * @param snapshot The snapshot alias declared by the provider.
+ * @param selector The snapshot selector, or null for identity-only reads.
+ * @return The join clause.
+ */
+ public static String snapshotJoin(
+ String model, String snapshot, @Nullable SemanticModelRevisionSelector selector) {
+ if (selector == null) {
+ return "";
+ }
+ String version;
+ if (selector == SemanticModelRevisionSelector.ACTIVE) {
+ version = model + ".active_version";
+ } else if (selector == SemanticModelRevisionSelector.LATEST) {
+ version = model + ".current_version";
+ } else {
+ version = "#{selector.number}";
+ }
+ return " LEFT JOIN "
+ + VERSION_TABLE_NAME
+ + " "
+ + snapshot
+ + " ON "
+ + snapshot
+ + ".semantic_model_id = "
+ + model
+ + ".semantic_model_id"
+ + " AND "
+ + snapshot
+ + ".version = "
+ + version
+ + " AND "
+ + snapshot
+ + ".deleted_at = 0";
}
/** Returns SQL for selecting an active Semantic Model ID by schema ID and name. */
@@ -76,20 +110,14 @@ public class SemanticModelMetaBaseSQLProvider {
+ " AND semantic_model_name = #{semanticModelName} AND deleted_at = 0";
}
- /** Returns SQL for selecting a current Semantic Model snapshot by schema ID and name. */
+ /** Returns SQL for selecting a Semantic Model by schema ID and name. */
public String selectSemanticModelMetaBySchemaIdAndName(
- @Param("schemaId") Long schemaId, @Param("semanticModelName") String semanticModelName) {
- return "SELECT"
- + CURRENT_SNAPSHOT_COLUMNS
- + " FROM "
- + TABLE_NAME
- + " smm INNER JOIN "
- + VERSION_TABLE_NAME
- + " smvi ON smm.semantic_model_id = smvi.semantic_model_id"
- + " AND smm.current_version = smvi.version"
- + " WHERE smm.schema_id = #{schemaId}"
- + " AND smm.semantic_model_name = #{semanticModelName}"
- + " AND smm.deleted_at = 0 AND smvi.deleted_at = 0";
+ @Param("schemaId") Long schemaId,
+ @Param("semanticModelName") String semanticModelName,
+ @Param("selector") @Nullable SemanticModelRevisionSelector selector) {
+ return selectModels(selector)
+ + " AND smm.schema_id = #{schemaId}"
+ + " AND smm.semantic_model_name = #{semanticModelName}";
}
/** Returns SQL for selecting and locking an active Semantic Model identity by natural key. */
@@ -98,7 +126,8 @@ public class SemanticModelMetaBaseSQLProvider {
return "SELECT semantic_model_id as semanticModelId,"
+ " semantic_model_name as semanticModelName, metalake_id as metalakeId,"
+ " catalog_id as catalogId, schema_id as schemaId,"
- + " current_version as currentVersion, last_version as lastVersion,"
+ + " current_version as currentVersion, active_version as activeVersion,"
+ + " last_version as lastVersion,"
+ " audit_info as auditInfo, deleted_at as deletedAt"
+ " FROM "
+ TABLE_NAME
@@ -107,18 +136,11 @@ public class SemanticModelMetaBaseSQLProvider {
+ " AND deleted_at = 0 FOR UPDATE";
}
- /** Returns SQL for selecting a current Semantic Model snapshot by stable ID. */
- public String selectSemanticModelMetaById(@Param("semanticModelId") Long semanticModelId) {
- return "SELECT"
- + CURRENT_SNAPSHOT_COLUMNS
- + " FROM "
- + TABLE_NAME
- + " smm INNER JOIN "
- + VERSION_TABLE_NAME
- + " smvi ON smm.semantic_model_id = smvi.semantic_model_id"
- + " AND smm.current_version = smvi.version"
- + " WHERE smm.semantic_model_id = #{semanticModelId}"
- + " AND smm.deleted_at = 0 AND smvi.deleted_at = 0";
+ /** Returns SQL for selecting a Semantic Model's requested snapshot by stable ID. */
+ public String selectSemanticModelMetaById(
+ @Param("semanticModelId") Long semanticModelId,
+ @Param("selector") SemanticModelRevisionSelector selector) {
+ return selectModels(selector) + " AND smm.semantic_model_id = #{semanticModelId}";
}
/** Returns SQL for selecting and locking a Semantic Model identity by stable ID. */
@@ -127,7 +149,8 @@ public class SemanticModelMetaBaseSQLProvider {
return "SELECT semantic_model_id as semanticModelId,"
+ " semantic_model_name as semanticModelName, metalake_id as metalakeId,"
+ " catalog_id as catalogId, schema_id as schemaId,"
- + " current_version as currentVersion, last_version as lastVersion,"
+ + " current_version as currentVersion, active_version as activeVersion,"
+ + " last_version as lastVersion,"
+ " audit_info as auditInfo, deleted_at as deletedAt FROM "
+ TABLE_NAME
+ " WHERE semantic_model_id = #{semanticModelId} AND deleted_at = 0 FOR UPDATE";
@@ -139,11 +162,12 @@ public class SemanticModelMetaBaseSQLProvider {
return "INSERT INTO "
+ TABLE_NAME
+ " (semantic_model_id, semantic_model_name, metalake_id, catalog_id, schema_id,"
- + " current_version, last_version, audit_info, deleted_at)"
+ + " current_version, active_version, last_version, audit_info, deleted_at)"
+ " VALUES (#{semanticModelMeta.semanticModelId},"
+ " #{semanticModelMeta.semanticModelName}, #{semanticModelMeta.metalakeId},"
+ " #{semanticModelMeta.catalogId}, #{semanticModelMeta.schemaId},"
- + " #{semanticModelMeta.currentVersion}, #{semanticModelMeta.lastVersion},"
+ + " #{semanticModelMeta.currentVersion}, #{semanticModelMeta.activeVersion},"
+ + " #{semanticModelMeta.lastVersion},"
+ " #{semanticModelMeta.auditInfo}, #{semanticModelMeta.deletedAt})";
}
@@ -154,14 +178,12 @@ public class SemanticModelMetaBaseSQLProvider {
return "UPDATE "
+ TABLE_NAME
+ " SET semantic_model_name = #{newSemanticModelMeta.semanticModelName},"
- + " metalake_id = #{newSemanticModelMeta.metalakeId},"
- + " catalog_id = #{newSemanticModelMeta.catalogId},"
- + " schema_id = #{newSemanticModelMeta.schemaId},"
- + " current_version = #{newSemanticModelMeta.currentVersion},"
- + " last_version = #{newSemanticModelMeta.lastVersion},"
+ " audit_info = #{newSemanticModelMeta.auditInfo},"
- + " deleted_at = #{newSemanticModelMeta.deletedAt}"
+ + " current_version = #{newSemanticModelMeta.currentVersion},"
+ + " last_version = #{newSemanticModelMeta.lastVersion}"
+ + ", active_version = #{newSemanticModelMeta.activeVersion}"
+ " WHERE semantic_model_id = #{oldSemanticModelMeta.semanticModelId}"
+ + " AND semantic_model_name = #{oldSemanticModelMeta.semanticModelName}"
+ " AND current_version = #{oldSemanticModelMeta.currentVersion}"
+ " AND deleted_at = 0"
+ " AND NOT EXISTS (SELECT 1 FROM "
@@ -171,12 +193,12 @@ public class SemanticModelMetaBaseSQLProvider {
+ " AND smvi.deleted_at = 0)";
}
- /** Returns SQL for soft-deleting a Semantic Model identity with an optimistic version check. */
+ /** Returns SQL for soft-deleting a Semantic Model identity guarded by the observed name. */
public String softDeleteSemanticModelMetasBySemanticModelId(
@Param("semanticModelId") Long semanticModelId,
- @Param("currentVersion") Integer currentVersion) {
+ @Param("semanticModelName") String semanticModelName) {
return softDeleteBy(
- "semantic_model_id = #{semanticModelId} AND current_version = #{currentVersion}");
+ "semantic_model_id = #{semanticModelId} AND semantic_model_name = #{semanticModelName}");
}
/** Returns SQL for soft-deleting Semantic Model identities by metalake ID. */
@@ -208,73 +230,50 @@ public class SemanticModelMetaBaseSQLProvider {
+ " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit}";
}
- /** Returns SQL for selecting a current Semantic Model by fully qualified name. */
+ /** Returns SQL for selecting a Semantic Model by fully qualified name. */
public String selectSemanticModelByFullQualifiedName(
@Param("metalakeName") String metalakeName,
@Param("catalogName") String catalogName,
@Param("schemaName") String schemaName,
- @Param("semanticModelName") String semanticModelName) {
- return qualifiedNameSelect(true);
+ @Param("semanticModelName") String semanticModelName,
+ @Param("selector") @Nullable SemanticModelRevisionSelector selector) {
+ return qualifiedNameSelect(true, selector);
+ }
+
+ private static String selectModels(@Nullable SemanticModelRevisionSelector selector) {
+ return "SELECT smm.metalake_id, smm.catalog_id, smm.schema_id,"
+ + MODEL_COLUMNS
+ + (selector == null ? "" : SNAPSHOT_COLUMNS)
+ + " FROM "
+ + TABLE_NAME
+ + " smm"
+ + snapshotJoin("smm", "smvi", selector)
+ + " WHERE smm.deleted_at = 0";
}
- private String qualifiedNameSelect(boolean filterBySemanticModelName) {
+ private String qualifiedNameSelect(
+ boolean filterBySemanticModelName, @Nullable SemanticModelRevisionSelector selector) {
String semanticModelNameCondition =
filterBySemanticModelName ? " AND smm.semantic_model_name = #{semanticModelName}" : "";
return """
- SELECT
- mm.metalake_id,
- cm.catalog_id,
- sm.schema_id,
- smm.semantic_model_id,
- smm.semantic_model_name,
- smm.current_version,
- smm.last_version,
- smm.audit_info,
- smm.deleted_at,
- smvi.id,
- smvi.metalake_id as version_metalake_id,
- smvi.catalog_id as version_catalog_id,
- smvi.schema_id as version_schema_id,
- smvi.semantic_model_id as version_semantic_model_id,
- smvi.version,
- smvi.semantic_model_name as version_semantic_model_name,
- smvi.semantic_model_comment,
- smvi.datasets,
- smvi.relationships,
- smvi.metrics,
- smvi.ai_context,
- smvi.custom_extensions,
- smvi.properties,
- smvi.audit_info as version_audit_info,
- smvi.deleted_at as version_deleted_at
- FROM
- %s mm
- INNER JOIN
- %s cm ON mm.metalake_id = cm.metalake_id
- AND cm.catalog_name = #{catalogName}
- AND cm.deleted_at = 0
- LEFT JOIN
- %s sm ON cm.catalog_id = sm.catalog_id
- AND sm.schema_name = #{schemaName}
- AND sm.deleted_at = 0
- LEFT JOIN
- %s smm ON sm.schema_id = smm.schema_id%s
- AND smm.deleted_at = 0
- LEFT JOIN
- %s smvi ON smm.semantic_model_id = smvi.semantic_model_id
- AND smm.current_version = smvi.version
- AND smvi.deleted_at = 0
- WHERE
- mm.metalake_name = #{metalakeName}
- AND mm.deleted_at = 0
+ SELECT mm.metalake_id, cm.catalog_id, sm.schema_id, %s
+ FROM %s mm
+ INNER JOIN %s cm ON mm.metalake_id = cm.metalake_id
+ AND cm.catalog_name = #{catalogName} AND cm.deleted_at = 0
+ LEFT JOIN %s sm ON cm.catalog_id = sm.catalog_id
+ AND sm.schema_name = #{schemaName} AND sm.deleted_at = 0
+ LEFT JOIN %s smm ON sm.schema_id = smm.schema_id%s AND smm.deleted_at = 0
+ %s
+ WHERE mm.metalake_name = #{metalakeName} AND mm.deleted_at = 0
"""
.formatted(
+ MODEL_COLUMNS + (selector == null ? "" : SNAPSHOT_COLUMNS),
MetalakeMetaMapper.TABLE_NAME,
CatalogMetaMapper.TABLE_NAME,
SchemaMetaMapper.TABLE_NAME,
TABLE_NAME,
semanticModelNameCondition,
- VERSION_TABLE_NAME);
+ snapshotJoin("smm", "smvi", selector));
}
private String softDeleteBy(String condition) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetricBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetricBaseSQLProvider.java
index 6267b2f78d..d7f09abfc7 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetricBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelMetricBaseSQLProvider.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.storage.relational.mapper.provider.base;
import static org.apache.gravitino.storage.relational.mapper.SemanticModelMetricMapper.TABLE_NAME;
import java.util.List;
+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;
import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
@@ -31,31 +32,15 @@ import org.apache.ibatis.annotations.Param;
/** Provides MySQL-compatible SQL for Semantic Model metric identities. */
public class SemanticModelMetricBaseSQLProvider {
- /** Returns a single statement selecting live metric names and their current model names. */
- public String listMetricNames(
- @Param("metalakeName") String metalakeName,
- @Param("catalogName") String catalogName,
- @Param("schemaName") String schemaName) {
- return discoverySelect(
- "metric.metric_name AS metricName",
- "LEFT JOIN "
- + TABLE_NAME
- + " metric"
- + " ON model.semantic_model_id = metric.semantic_model_id AND metric.deleted_at = 0");
- }
-
- /** Returns a single statement selecting only metrics from each current model snapshot. */
+ /** Returns a single statement selecting only metrics from each selected model snapshot. */
public String listMetricSnapshots(
@Param("metalakeName") String metalakeName,
@Param("catalogName") String catalogName,
- @Param("schemaName") String schemaName) {
+ @Param("schemaName") String schemaName,
+ @Param("selector") SemanticModelRevisionSelector selector) {
return discoverySelect(
"snapshot.version, snapshot.metrics",
- "LEFT JOIN "
- + SemanticModelMetaMapper.VERSION_TABLE_NAME
- + " snapshot"
- + " ON model.semantic_model_id = snapshot.semantic_model_id"
- + " AND model.current_version = snapshot.version AND snapshot.deleted_at = 0");
+ SemanticModelMetaBaseSQLProvider.snapshotJoin("model", "snapshot", selector));
}
/** Returns SQL for inserting new identities in one statement. */
@@ -135,7 +120,7 @@ public class SemanticModelMetricBaseSQLProvider {
private String discoverySelect(String projection, String metricJoin) {
// Left joins distinguish an empty schema from a missing schema. They also keep a live model
- // whose current snapshot is missing, so detailed discovery fails instead of silently omitting
+ // whose active snapshot is missing, so detailed discovery fails instead of silently omitting
// it.
return """
SELECT schema_meta.schema_id AS schemaId, model.semantic_model_id AS semanticModelId,
@@ -145,7 +130,7 @@ public class SemanticModelMetricBaseSQLProvider {
AND catalog.catalog_name = #{catalogName} AND catalog.deleted_at = 0
LEFT JOIN %s schema_meta ON catalog.catalog_id = schema_meta.catalog_id
AND schema_meta.schema_name = #{schemaName} AND schema_meta.deleted_at = 0
- LEFT JOIN %s model ON schema_meta.schema_id = model.schema_id AND model.deleted_at = 0
+ LEFT JOIN %s model ON schema_meta.schema_id = model.schema_id AND model.deleted_at = 0 AND model.active_version > 0
%s
WHERE metalake.metalake_name = #{metalakeName} AND metalake.deleted_at = 0
"""
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelSourceBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelSourceBaseSQLProvider.java
index 99f9718924..f2af3a97ae 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelSourceBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelSourceBaseSQLProvider.java
@@ -22,11 +22,26 @@ import static org.apache.gravitino.storage.relational.mapper.SemanticModelSource
import java.util.List;
import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
import org.apache.ibatis.annotations.Param;
/** Provides MySQL-compatible SQL for retiring dataset source associations. */
public class SemanticModelSourceBaseSQLProvider {
+ /** Returns SQL for retiring closed ranges that contain no retained snapshot. */
+ public String softDeleteUnreferencedRanges(@Param("modelId") long modelId) {
+ return softDeleteBy(
+ "semantic_model_id = #{modelId} AND to_version <> 0 AND NOT EXISTS (SELECT 1 FROM "
+ + SemanticModelVersionInfoMapper.TABLE_NAME
+ + " revision WHERE revision.semantic_model_id = #{modelId} AND revision.deleted_at = 0"
+ + " AND revision.version >= "
+ + TABLE_NAME
+ + ".from_version"
+ + " AND revision.version < "
+ + TABLE_NAME
+ + ".to_version)");
+ }
+
/** Returns SQL for retiring a model's live associations. */
public String softDeleteByModelId(@Param("modelId") Long modelId) {
return softDeleteBy("semantic_model_id = #{modelId}");
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelVersionInfoBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelVersionInfoBaseSQLProvider.java
index d4502eb3f2..2e850719b1 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelVersionInfoBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/SemanticModelVersionInfoBaseSQLProvider.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.storage.relational.mapper.provider.base;
import java.util.List;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
import org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
import org.apache.ibatis.annotations.Param;
@@ -32,13 +33,14 @@ public class SemanticModelVersionInfoBaseSQLProvider {
return "INSERT INTO "
+ SemanticModelVersionInfoMapper.TABLE_NAME
+ " (metalake_id, catalog_id, schema_id, semantic_model_id, version,"
- + " semantic_model_name, semantic_model_comment, datasets, relationships, metrics,"
+ + " publication_status, published_by, published_at, semantic_model_comment, datasets, relationships, metrics,"
+ " ai_context, custom_extensions,"
+ " properties, audit_info, deleted_at)"
+ " VALUES (#{semanticModelVersionInfo.metalakeId},"
+ " #{semanticModelVersionInfo.catalogId}, #{semanticModelVersionInfo.schemaId},"
+ " #{semanticModelVersionInfo.semanticModelId}, #{semanticModelVersionInfo.version},"
- + " #{semanticModelVersionInfo.semanticModelName},"
+ + " #{semanticModelVersionInfo.publicationStatus},"
+ + " #{semanticModelVersionInfo.publishedBy}, #{semanticModelVersionInfo.publishedAt},"
+ " #{semanticModelVersionInfo.semanticModelComment},"
+ " #{semanticModelVersionInfo.datasets}, #{semanticModelVersionInfo.relationships},"
+ " #{semanticModelVersionInfo.metrics}, #{semanticModelVersionInfo.aiContext},"
@@ -52,7 +54,8 @@ public class SemanticModelVersionInfoBaseSQLProvider {
@Param("semanticModelId") Long semanticModelId, @Param("version") Integer version) {
return "SELECT id as id, metalake_id as metalakeId, catalog_id as catalogId,"
+ " schema_id as schemaId, semantic_model_id as semanticModelId, version as version,"
- + " semantic_model_name as semanticModelName,"
+ + " publication_status AS publicationStatus, published_by AS publishedBy,"
+ + " published_at AS publishedAt,"
+ " semantic_model_comment as semanticModelComment,"
+ " datasets as datasets, relationships as relationships, metrics as metrics,"
+ " ai_context as aiContext, custom_extensions as customExtensions, properties as properties,"
@@ -98,26 +101,34 @@ public class SemanticModelVersionInfoBaseSQLProvider {
+ " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit}";
}
- /** Returns SQL for finding Semantic Models that exceed a version retention count. */
+ /** Returns SQL for finding Semantic Models with snapshots eligible for retention cleanup. */
public String selectSemanticModelVersionsByRetentionCount(
@Param("versionRetentionCount") Long versionRetentionCount) {
- return "SELECT semantic_model_id as semanticModelId, MAX(version) as version FROM "
+ // Keep the cutoff nonnegative for unsigned version columns.
+ return "SELECT smm.semantic_model_id AS semanticModelId, smm.current_version AS version FROM "
+ + SemanticModelMetaMapper.TABLE_NAME
+ + " smm WHERE smm.current_version > #{versionRetentionCount} AND smm.deleted_at = 0"
+ + " AND EXISTS (SELECT 1 FROM "
+ SemanticModelVersionInfoMapper.TABLE_NAME
- + " WHERE version > #{versionRetentionCount} AND deleted_at = 0"
- + " GROUP BY semantic_model_id";
+ + " smvi WHERE smvi.semantic_model_id = smm.semantic_model_id"
+ + " AND smvi.version <= smm.current_version"
+ + " - LEAST(smm.current_version, #{versionRetentionCount})"
+ + " AND smvi.version <> smm.active_version AND smvi.deleted_at = 0)";
}
/** Returns SQL for soft-deleting snapshots through a per-model retention line. */
public String softDeleteSemanticModelVersionsByRetentionLine(
@Param("semanticModelId") Long semanticModelId,
@Param("versionRetentionLine") long versionRetentionLine,
+ @Param("activeVersion") int activeVersion,
@Param("limit") int limit) {
return "UPDATE "
+ SemanticModelVersionInfoMapper.TABLE_NAME
+ " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"
+ " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"
+ " WHERE semantic_model_id = #{semanticModelId}"
- + " AND version <= #{versionRetentionLine} AND deleted_at = 0 LIMIT #{limit}";
+ + " AND version <= #{versionRetentionLine} AND version <> #{activeVersion}"
+ + " AND deleted_at = 0 LIMIT #{limit}";
}
private String softDeleteBy(String condition) {
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelMetaPostgreSQLProvider.java
index 83457e5704..5925d5ce3c 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelMetaPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelMetaPostgreSQLProvider.java
@@ -30,9 +30,9 @@ public class SemanticModelMetaPostgreSQLProvider extends SemanticModelMetaBaseSQ
@Override
public String softDeleteSemanticModelMetasBySemanticModelId(
@Param("semanticModelId") Long semanticModelId,
- @Param("currentVersion") Integer currentVersion) {
+ @Param("semanticModelName") String semanticModelName) {
return softDeleteBy(
- "semantic_model_id = #{semanticModelId} AND current_version = #{currentVersion}");
+ "semantic_model_id = #{semanticModelId} AND semantic_model_name = #{semanticModelName}");
}
@Override
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelVersionInfoPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelVersionInfoPostgreSQLProvider.java
index 52643579ef..186a73fa09 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelVersionInfoPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelVersionInfoPostgreSQLProvider.java
@@ -68,6 +68,7 @@ public class SemanticModelVersionInfoPostgreSQLProvider
public String softDeleteSemanticModelVersionsByRetentionLine(
@Param("semanticModelId") Long semanticModelId,
@Param("versionRetentionLine") long versionRetentionLine,
+ @Param("activeVersion") int activeVersion,
@Param("limit") int limit) {
return "UPDATE "
+ SemanticModelVersionInfoMapper.TABLE_NAME
@@ -75,7 +76,7 @@ public class SemanticModelVersionInfoPostgreSQLProvider
+ " WHERE id IN (SELECT id FROM "
+ SemanticModelVersionInfoMapper.TABLE_NAME
+ " WHERE semantic_model_id = #{semanticModelId}"
- + " AND version <= #{versionRetentionLine}"
+ + " AND version <= #{versionRetentionLine} AND version <> #{activeVersion}"
+ " AND deleted_at = 0 LIMIT #{limit})";
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelMetricListingPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelMetricListingPO.java
index c75086233f..54747b577d 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelMetricListingPO.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelMetricListingPO.java
@@ -27,7 +27,6 @@ public class SemanticModelMetricListingPO {
@Nullable private Long schemaId;
@Nullable private Long semanticModelId;
@Nullable private String semanticModelName;
- @Nullable private String metricName;
@Nullable private Integer version;
@Nullable private String metrics;
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java
index c50c6ab4d6..fe0312f1d0 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelPO.java
@@ -22,6 +22,7 @@ import static org.apache.gravitino.storage.relational.utils.POConverters.DEFAULT
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Preconditions;
+import java.time.Instant;
import java.util.Collections;
import java.util.Map;
import javax.annotation.Nullable;
@@ -37,13 +38,16 @@ import org.apache.gravitino.dto.semantic.DatasetDTO;
import org.apache.gravitino.dto.semantic.MetricDTO;
import org.apache.gravitino.dto.semantic.RelationshipDTO;
import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;
+import org.apache.gravitino.dto.semantic.SemanticModelRevisionDTO;
import org.apache.gravitino.json.JsonUtils;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.NamespacedEntityId;
import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.semantic.SemanticModel.Status;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO.PublicationStatus;
import org.apache.gravitino.storage.relational.service.EntityIdService;
-/** The persistent object for Semantic Model identity metadata and its current version snapshot. */
+/** The persistent object for Semantic Model identity metadata and a selected version snapshot. */
@Getter
@EqualsAndHashCode(exclude = "semanticModelVersionInfoPO")
@ToString
@@ -59,6 +63,7 @@ public class SemanticModelPO {
private Long schemaId;
private String auditInfo;
private Integer currentVersion;
+ private Integer activeVersion;
private Integer lastVersion;
private Long deletedAt;
private SemanticModelVersionInfoPO semanticModelVersionInfoPO;
@@ -71,7 +76,7 @@ public class SemanticModelPO {
// Lombok generates the builder methods.
}
- @lombok.Builder(setterPrefix = "with")
+ @lombok.Builder(setterPrefix = "with", toBuilder = true)
private SemanticModelPO(
Long semanticModelId,
String semanticModelName,
@@ -80,6 +85,7 @@ public class SemanticModelPO {
Long schemaId,
String auditInfo,
Integer currentVersion,
+ Integer activeVersion,
Integer lastVersion,
Long deletedAt,
SemanticModelVersionInfoPO semanticModelVersionInfoPO) {
@@ -100,13 +106,14 @@ public class SemanticModelPO {
this.schemaId = schemaId;
this.auditInfo = auditInfo;
this.currentVersion = currentVersion;
+ this.activeVersion = activeVersion;
this.lastVersion = lastVersion;
this.deletedAt = deletedAt;
this.semanticModelVersionInfoPO = semanticModelVersionInfoPO;
}
/**
- * Converts a persistent object and its current version snapshot to a Semantic Model entity.
+ * Converts a persistent object and its selected version snapshot to a Semantic Model entity.
*
* @param semanticModelPO The persistent object to convert.
* @param namespace The Semantic Model namespace.
@@ -116,6 +123,7 @@ public class SemanticModelPO {
SemanticModelPO semanticModelPO, Namespace namespace) {
try {
SemanticModelVersionInfoPO versionPO = semanticModelPO.getSemanticModelVersionInfoPO();
+ SemanticModelRevisionDTO revision = versionPO.revisionInfo();
SemanticModelDefinitionDTO definitionDTO =
SemanticModelDefinitionDTO.builder()
.withDatasets(deserializeField(versionPO.datasets(), DatasetDTO[].class, "datasets"))
@@ -144,13 +152,17 @@ public class SemanticModelPO {
return SemanticModelEntity.builder()
.withId(semanticModelPO.getSemanticModelId())
- .withName(versionPO.semanticModelName())
+ .withName(semanticModelPO.getSemanticModelName())
+ .withRevision(
+ revision.revision(),
+ revision.status(),
+ revision.publishedBy(),
+ revision.publishedAt())
.withNamespace(namespace)
.withComment(versionPO.semanticModelComment())
.withDefinition(definitionDTO.toDefinition())
.withProperties(properties)
- .withAuditInfo(
- JsonUtils.anyFieldMapper().readValue(semanticModelPO.getAuditInfo(), AuditInfo.class))
+ .withAuditInfo(versionPO.writerAudit())
.build();
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to deserialize Semantic Model JSON", e);
@@ -189,13 +201,21 @@ public class SemanticModelPO {
? null
: JsonUtils.anyFieldMapper().writeValueAsString(semanticModelEntity.properties());
+ boolean published = semanticModelEntity.status() == Status.PUBLISHED;
+ AuditInfo audit = semanticModelEntity.auditInfo();
+ String writer = audit.lastModifier() == null ? audit.creator() : audit.lastModifier();
+ Instant saveTime =
+ audit.lastModifiedTime() == null ? audit.createTime() : audit.lastModifiedTime();
return SemanticModelVersionInfoPO.builder()
.withSemanticModelId(semanticModelEntity.id())
.withMetalakeId(namespacedEntityId.namespaceIds()[0])
.withCatalogId(namespacedEntityId.namespaceIds()[1])
.withSchemaId(namespacedEntityId.entityId())
.withVersion(version)
- .withSemanticModelName(semanticModelEntity.name())
+ .withPublicationStatus(
+ published ? PublicationStatus.PUBLISHED_ON_SAVE : PublicationStatus.DRAFT)
+ .withPublishedBy(published ? writer : "")
+ .withPublishedAt(published ? saveTime.toEpochMilli() : 0L)
.withSemanticModelComment(semanticModelEntity.comment())
.withDatasets(JsonUtils.anyFieldMapper().writeValueAsString(definitionDTO.getDatasets()))
.withRelationships(serializeOptionalField(definitionDTO.getRelationships()))
@@ -238,6 +258,7 @@ public class SemanticModelPO {
.withAuditInfo(
JsonUtils.anyFieldMapper().writeValueAsString(semanticModelEntity.auditInfo()))
.withCurrentVersion(version)
+ .withActiveVersion(semanticModelEntity.status() == Status.PUBLISHED ? version : 0)
.withLastVersion(version)
.withSemanticModelVersionInfoPO(versionPO)
.withDeletedAt(DEFAULT_DELETED_AT)
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelVersionInfoPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelVersionInfoPO.java
index ba87dde18b..55683966e5 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelVersionInfoPO.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelVersionInfoPO.java
@@ -18,13 +18,20 @@
*/
package org.apache.gravitino.storage.relational.po;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Preconditions;
+import java.time.Instant;
import javax.annotation.Nullable;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.dto.semantic.SemanticModelRevisionDTO;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.semantic.SemanticModel.Status;
/** The persistent object for a complete Semantic Model version snapshot. */
@EqualsAndHashCode
@@ -33,13 +40,23 @@ import org.apache.commons.lang3.StringUtils;
@Accessors(fluent = true)
public class SemanticModelVersionInfoPO {
+ /** Database publication state. */
+ public enum PublicationStatus {
+ /** A revision that has not been published. */
+ DRAFT,
+ /** A revision made active at save time. */
+ PUBLISHED_ON_SAVE
+ }
+
private Long id;
private Long metalakeId;
private Long catalogId;
private Long schemaId;
private Long semanticModelId;
private Integer version;
- private String semanticModelName;
+ private PublicationStatus publicationStatus;
+ private String publishedBy;
+ private Long publishedAt;
private String semanticModelComment;
private String datasets;
@Nullable private String relationships;
@@ -53,7 +70,7 @@ public class SemanticModelVersionInfoPO {
/** Creates an empty persistent object for MyBatis. */
public SemanticModelVersionInfoPO() {}
- @lombok.Builder(setterPrefix = "with")
+ @lombok.Builder(setterPrefix = "with", toBuilder = true)
private SemanticModelVersionInfoPO(
Long id,
Long metalakeId,
@@ -61,7 +78,9 @@ public class SemanticModelVersionInfoPO {
Long schemaId,
Long semanticModelId,
Integer version,
- String semanticModelName,
+ PublicationStatus publicationStatus,
+ String publishedBy,
+ Long publishedAt,
String semanticModelComment,
String datasets,
@Nullable String relationships,
@@ -76,8 +95,6 @@ public class SemanticModelVersionInfoPO {
Preconditions.checkArgument(schemaId != null, "Schema id is required");
Preconditions.checkArgument(semanticModelId != null, "Semantic Model id is required");
Preconditions.checkArgument(version != null, "Semantic Model version is required");
- Preconditions.checkArgument(
- StringUtils.isNotBlank(semanticModelName), "Semantic Model name cannot be empty");
Preconditions.checkArgument(
StringUtils.isNotBlank(datasets), "Semantic Model datasets cannot be empty");
Preconditions.checkArgument(StringUtils.isNotBlank(auditInfo), "Audit info cannot be empty");
@@ -89,7 +106,9 @@ public class SemanticModelVersionInfoPO {
this.schemaId = schemaId;
this.semanticModelId = semanticModelId;
this.version = version;
- this.semanticModelName = semanticModelName;
+ this.publicationStatus = publicationStatus;
+ this.publishedBy = publishedBy;
+ this.publishedAt = publishedAt;
this.semanticModelComment = semanticModelComment;
this.datasets = datasets;
this.relationships = relationships;
@@ -100,4 +119,24 @@ public class SemanticModelVersionInfoPO {
this.auditInfo = auditInfo;
this.deletedAt = deletedAt;
}
+
+ /** Returns the public metadata for this retained revision, without its definition. */
+ public SemanticModelRevisionDTO revisionInfo() {
+ boolean draft = publicationStatus == PublicationStatus.DRAFT;
+ return new SemanticModelRevisionDTO(
+ version,
+ draft ? Status.DRAFT : Status.PUBLISHED,
+ draft ? null : publishedBy,
+ draft ? null : Instant.ofEpochMilli(publishedAt),
+ DTOConverters.toDTO(writerAudit()));
+ }
+
+ /** Returns the audit information recorded when this snapshot was saved. */
+ public AuditInfo writerAudit() {
+ try {
+ return JsonUtils.anyFieldMapper().readValue(auditInfo, AuditInfo.class);
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException("Failed to deserialize Semantic Model revision audit", e);
+ }
+ }
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java
index ffe5e6ccb2..ec955bfce1 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java
@@ -19,6 +19,8 @@
package org.apache.gravitino.storage.relational.service;
import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.semantic.SemanticModelRevisionSelector.ACTIVE;
+import static org.apache.gravitino.semantic.SemanticModelRevisionSelector.LATEST;
import static org.apache.gravitino.storage.relational.po.SemanticModelPO.buildSemanticModelPO;
import static org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
import static org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
@@ -33,21 +35,23 @@ import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
-import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
+import javax.annotation.Nullable;
import org.apache.gravitino.Entity;
import org.apache.gravitino.GravitinoEnv;
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.exceptions.NoSuchSemanticModelRevisionException;
import org.apache.gravitino.exceptions.OptimisticLockException;
import org.apache.gravitino.meta.SemanticModelEntity;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.semantic.Metric;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;
import org.apache.gravitino.semantic.SemanticModelSource;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.storage.relational.EntityChangeLogWriter;
@@ -74,16 +78,19 @@ public class SemanticModelMetaService {
private static final int SOURCE_INSERT_BATCH_SIZE = 1000;
private static final SemanticModelMetaService INSTANCE = new SemanticModelMetaService();
- private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+ private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> activeOps =
+ opsFor(ACTIVE);
+ private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> latestOps =
+ opsFor(LATEST);
+ private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> identityOps =
+ opsFor(null);
/** Returns the singleton Semantic Model metadata service. */
public static SemanticModelMetaService getInstance() {
return INSTANCE;
}
- private SemanticModelMetaService() {
- this.ops = new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps());
- }
+ private SemanticModelMetaService() {}
/**
* Resolves a Semantic Model stable ID by schema ID and name.
@@ -97,17 +104,17 @@ public class SemanticModelMetaService {
metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
baseMetricName = "getSemanticModelIdBySchemaIdAndName")
public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String semanticModelName) {
- SemanticModelPO semanticModelPO =
+ Long id =
SessionUtils.getWithoutCommit(
SemanticModelMetaMapper.class,
- mapper -> ops.getPO(mapper, schemaId, semanticModelName));
- if (semanticModelPO == null) {
+ mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, semanticModelName));
+ if (id == null) {
throw new NoSuchEntityException(
NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
semanticModelName);
}
- return semanticModelPO.getSemanticModelId();
+ return id;
}
/**
@@ -121,8 +128,13 @@ public class SemanticModelMetaService {
baseMetricName = "listSemanticModelsByNamespace")
public List<SemanticModelEntity> listSemanticModelsByNamespace(Namespace namespace) {
NamespaceUtil.checkSemanticModel(namespace);
- return listSemanticModelPOs(namespace).stream()
- .map(po -> fromSemanticModelPO(po, namespace))
+ return listSemanticModelPOs(namespace, activeOps).stream()
+ .filter(po -> po.getActiveVersion() > 0)
+ .map(
+ po -> {
+ requireSnapshot(po, po.getActiveVersion(), "active");
+ return fromSemanticModelPO(po, namespace);
+ })
.collect(Collectors.toList());
}
@@ -137,8 +149,45 @@ public class SemanticModelMetaService {
metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
baseMetricName = "getSemanticModelByIdentifier")
public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier identifier) {
- SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
- return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+ return getSemanticModelByIdentifier(identifier, ACTIVE);
+ }
+
+ /** Loads the selected revision of an existing Semantic Model. */
+ public SemanticModelEntity getSemanticModelByIdentifier(
+ NameIdentifier identifier, SemanticModelRevisionSelector selector) {
+ SemanticModelPO po =
+ selectModel(
+ identifier,
+ selector == ACTIVE ? activeOps : selector == LATEST ? latestOps : opsFor(selector));
+ if (selector == ACTIVE) {
+ if (po.getActiveVersion() == 0) {
+ throw missingModel(identifier);
+ }
+ requireSnapshot(po, po.getActiveVersion(), "active");
+ } else if (selector == LATEST) {
+ requireSnapshot(po, po.getCurrentVersion(), "latest");
+ } else if (po.getSemanticModelVersionInfoPO() == null) {
+ throw missingRevision(identifier, selector.getNumber(), po.getCurrentVersion());
+ }
+ return fromSemanticModelPO(po, identifier.namespace());
+ }
+
+ /** Checks for a live identity, including a model with only drafts. */
+ public boolean semanticModelExists(NameIdentifier identifier) {
+ try {
+ selectModel(identifier, identityOps);
+ return true;
+ } catch (NoSuchEntityException e) {
+ return false;
+ }
+ }
+
+ /** Lists model identities under a schema for governance operations. */
+ public List<NameIdentifier> listSemanticModelIdentifiers(Namespace namespace) {
+ NamespaceUtil.checkSemanticModel(namespace);
+ return listSemanticModelPOs(namespace, identityOps).stream()
+ .map(po -> NameIdentifier.of(namespace, po.getSemanticModelName()))
+ .toList();
}
/**
@@ -177,7 +226,7 @@ public class SemanticModelMetaService {
if (storedPO == null) {
// Keep missing-row imports strict. A losing concurrent insert must not
// overwrite a persisted identity with a different ID.
- ops.insertPO(mapper, po, false);
+ mapper.insertSemanticModelMeta(po);
return;
}
@@ -189,7 +238,9 @@ public class SemanticModelMetaService {
}
persistedPO.set(replacementPO);
}),
- () -> reconcileMetricIdentities(persistedPO.get(), semanticModelEntity.definition()),
+ () ->
+ reconcileMetricIdentities(
+ persistedPO.get(), metricNames(semanticModelEntity.definition())),
() -> replaceSources(persistedPO.get(), semanticModelEntity),
() ->
SessionUtils.doWithoutCommit(
@@ -220,83 +271,48 @@ public class SemanticModelMetaService {
baseMetricName = "updateSemanticModel")
public <E extends Entity & HasIdentifier> SemanticModelEntity updateSemanticModel(
NameIdentifier identifier, Function<E, E> updater) throws IOException {
- SemanticModelPO oldSemanticModelPO = getSemanticModelPOByIdentifier(identifier);
- SemanticModelEntity oldSemanticModelEntity =
- fromSemanticModelPO(oldSemanticModelPO, identifier.namespace());
- SemanticModelEntity newEntity = (SemanticModelEntity) updater.apply((E) oldSemanticModelEntity);
+ SemanticModelPO observed = getSemanticModelPOByIdentifier(identifier);
+ SemanticModelEntity oldEntity = fromSemanticModelPO(observed, identifier.namespace());
+ SemanticModelEntity newEntity = (SemanticModelEntity) updater.apply((E) oldEntity);
Preconditions.checkArgument(
- Objects.equals(oldSemanticModelEntity.id(), newEntity.id()),
- "The updated Semantic Model entity id: %s should be same with the entity id before: %s",
- newEntity.id(),
- oldSemanticModelEntity.id());
+ oldEntity.id().equals(newEntity.id()), "Semantic Model ID cannot change");
Preconditions.checkArgument(
- oldSemanticModelEntity.namespace().equals(newEntity.namespace()),
+ oldEntity.namespace().equals(newEntity.namespace()),
"Semantic Model namespace cannot change from %s to %s",
- oldSemanticModelEntity.namespace(),
+ oldEntity.namespace(),
newEntity.namespace());
- AtomicInteger updateResult = new AtomicInteger(-1);
try {
- SemanticModelPO newSemanticModelPO = updateSemanticModelPO(oldSemanticModelPO, newEntity);
- String metalakeName = identifier.namespace().level(0);
- String catalogName = identifier.namespace().level(1);
- String schemaName = identifier.namespace().level(2);
- NameIdentifier oldSemanticModelIdent =
- NameIdentifierUtil.ofSemanticModel(
- metalakeName, catalogName, schemaName, oldSemanticModelPO.getSemanticModelName());
- boolean isRenamed =
- !Objects.equals(
- oldSemanticModelPO.getSemanticModelName(), newSemanticModelPO.getSemanticModelName());
-
- SessionUtils.doMultipleWithCommit(
- // The Semantic Model and its parent were read before this transaction started. Lock the
- // observed parent again before either identity or version writes, so a schema cascade
- // cannot finish its cleanup and then let this update recreate child state below it.
- () ->
- SchemaMetaService.getInstance()
- .lockSchemaForEntityWrite(
- identifier,
- oldSemanticModelPO.getSchemaId(),
- oldSemanticModelPO.getCatalogId(),
- oldSemanticModelPO.getMetalakeId()),
- () -> {
- updateResult.set(
- SessionUtils.getWithoutCommit(
- SemanticModelMetaMapper.class,
- mapper -> ops.updatePO(mapper, newSemanticModelPO, oldSemanticModelPO)));
- if (updateResult.get() == 0) {
- throw semanticModelWriteFailure(identifier, oldSemanticModelPO);
+ return SessionUtils.doWithCommitAndFetchResult(
+ SemanticModelMetaMapper.class,
+ mapper -> {
+ lockParent(identifier, observed);
+ SemanticModelPO next = updateSemanticModelPO(observed, newEntity);
+ if (mapper.updateSemanticModelMeta(next, observed) != 1) {
+ throw semanticModelWriteFailure(identifier, observed);
}
- },
- () -> {
if (!Objects.equals(
- oldSemanticModelPO.getSemanticModelVersionInfoPO().metrics(),
- newSemanticModelPO.getSemanticModelVersionInfoPO().metrics())
- && !metricNames(oldSemanticModelEntity.definition())
+ observed.getSemanticModelVersionInfoPO().metrics(),
+ next.getSemanticModelVersionInfoPO().metrics())
+ && !metricNames(oldEntity.definition())
.equals(metricNames(newEntity.definition()))) {
- reconcileMetricIdentities(newSemanticModelPO, newEntity.definition());
+ reconcileMetricIdentities(next, metricNames(newEntity.definition()));
}
- },
- () -> replaceSources(newSemanticModelPO, newEntity),
- () ->
- SessionUtils.doWithoutCommit(
- SemanticModelVersionInfoMapper.class,
- mapper ->
- mapper.insertSemanticModelVersionInfo(
- newSemanticModelPO.getSemanticModelVersionInfoPO())),
- () -> {
- if (isRenamed && updateResult.get() > 0) {
+ replaceSources(next, newEntity);
+ SessionUtils.doWithoutCommit(
+ SemanticModelVersionInfoMapper.class,
+ versions ->
+ versions.insertSemanticModelVersionInfo(next.getSemanticModelVersionInfoPO()));
+ if (!observed.getSemanticModelName().equals(next.getSemanticModelName())) {
EntityChangeLogWriter.append(
- oldSemanticModelIdent, Entity.EntityType.SEMANTIC_MODEL, OperateType.ALTER);
+ identifier, Entity.EntityType.SEMANTIC_MODEL, OperateType.ALTER);
}
+ return fromSemanticModelPO(next, identifier.namespace());
});
- return newEntity;
- } catch (OptimisticLockException optimisticLockException) {
- throw optimisticLockException;
- } catch (RuntimeException re) {
+ } catch (RuntimeException e) {
ExceptionUtils.checkSQLException(
- re, Entity.EntityType.SEMANTIC_MODEL, newEntity.nameIdentifier().toString());
- throw re;
+ e, Entity.EntityType.SEMANTIC_MODEL, newEntity.nameIdentifier().toString());
+ throw e;
}
}
@@ -307,14 +323,13 @@ public class SemanticModelMetaService {
* @param identifier The Semantic Model identifier.
* @return {@code true} when an active identity was deleted.
* @throws NoSuchEntityException If the Semantic Model is already deleted or renamed.
- * @throws OptimisticLockException If the internal transaction loses a concurrent update race.
*/
@Monitored(
metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
baseMetricName = "deleteSemanticModel")
public boolean deleteSemanticModel(NameIdentifier identifier) {
- SemanticModelPO semanticModelPO = getSemanticModelPOByIdentifier(identifier);
- deleteSemanticModelWithVersion(identifier, semanticModelPO);
+ SemanticModelPO semanticModelPO = selectModel(identifier, identityOps);
+ deleteObservedSemanticModel(identifier, semanticModelPO);
return true;
}
@@ -366,38 +381,52 @@ public class SemanticModelMetaService {
mapper -> mapper.selectSemanticModelVersionsByRetentionCount(versionRetentionCount));
int totalDeletedCount = 0;
- for (SemanticModelVersionInfoPO currentVersion : currentVersions) {
- long versionRetentionLine = currentVersion.version() - versionRetentionCount;
+ for (SemanticModelVersionInfoPO candidate : currentVersions) {
int deletedCount =
SessionUtils.doWithCommitAndFetchResult(
- SemanticModelVersionInfoMapper.class,
- mapper ->
- mapper.softDeleteSemanticModelVersionsByRetentionLine(
- currentVersion.semanticModelId(), versionRetentionLine, limit));
+ SemanticModelMetaMapper.class,
+ mapper -> {
+ SemanticModelPO model =
+ mapper.selectSemanticModelMetaByIdForUpdate(candidate.semanticModelId());
+ if (model == null) {
+ return 0;
+ }
+ long cutoff = model.getCurrentVersion() - versionRetentionCount;
+ int count =
+ SessionUtils.getWithoutCommit(
+ SemanticModelVersionInfoMapper.class,
+ snapshots ->
+ snapshots.softDeleteSemanticModelVersionsByRetentionLine(
+ model.getSemanticModelId(),
+ cutoff,
+ model.getActiveVersion(),
+ limit));
+ SessionUtils.doWithoutCommit(
+ SemanticModelSourceMapper.class,
+ sources -> sources.softDeleteUnreferencedRanges(model.getSemanticModelId()));
+ return count;
+ });
totalDeletedCount += deletedCount;
- LOG.info(
- "Soft delete Semantic Model versions count: {} through retention line: {},"
- + " current Semantic Model id and version: <{}, {}>.",
+ LOG.debug(
+ "Soft-deleted {} revisions for Semantic Model {}",
deletedCount,
- versionRetentionLine,
- currentVersion.semanticModelId(),
- currentVersion.version());
+ candidate.semanticModelId());
}
return totalDeletedCount;
}
/** Returns the persistent-object operations used by this service. */
public BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops() {
- return ops;
+ return activeOps;
}
/**
* Deletes the observed Semantic Model and its snapshots in one transaction.
*
- * <p>Package-private access lets concurrency tests submit a stale snapshot through the same
- * compare-and-set path as public deletion.
+ * <p>Package-private access lets concurrency tests submit an observed identity through the same
+ * name guard as public deletion.
*/
- void deleteSemanticModelWithVersion(
+ void deleteObservedSemanticModel(
NameIdentifier identifier, SemanticModelPO observedSemanticModelPO) {
Long semanticModelId = observedSemanticModelPO.getSemanticModelId();
String metalakeName = identifier.namespace().level(0);
@@ -417,7 +446,7 @@ public class SemanticModelMetaService {
SemanticModelMetaMapper.class,
mapper ->
mapper.softDeleteSemanticModelMetasBySemanticModelId(
- semanticModelId, observedSemanticModelPO.getCurrentVersion())),
+ semanticModelId, observedSemanticModelPO.getSemanticModelName())),
() -> semanticModelWriteFailure(identifier, observedSemanticModelPO)),
() ->
SessionUtils.doWithoutCommit(
@@ -444,21 +473,19 @@ public class SemanticModelMetaService {
SessionUtils.doWithoutCommit(
SemanticModelSourceMapper.class,
mapper -> {
- mapper.softDeleteByModelId(po.getSemanticModelId());
+ mapper.closeSourceRanges(po.getSemanticModelId(), po.getCurrentVersion());
List<SemanticModelSource> sources = entity.sourceUpdate().sources();
for (int start = 0; start < sources.size(); start += SOURCE_INSERT_BATCH_SIZE) {
mapper.insertSources(
po.getMetalakeId(),
po.getSemanticModelId(),
+ po.getCurrentVersion(),
sources.subList(start, Math.min(start + SOURCE_INSERT_BATCH_SIZE, sources.size())));
}
});
}
- private static void reconcileMetricIdentities(
- SemanticModelPO model, SemanticModelDefinition definition) {
- Set<String> names = metricNames(definition);
-
+ private static void reconcileMetricIdentities(SemanticModelPO model, Set<String> names) {
// The caller has already inserted or version-checked the model in this transaction. A locking
// read also observes the latest identities on backends using repeatable-read isolation.
SessionUtils.doWithoutCommit(
@@ -553,6 +580,7 @@ public class SemanticModelMetaService {
.withSchemaId(persistedPO.getSchemaId())
.withAuditInfo(source.getAuditInfo())
.withCurrentVersion(nextVersion)
+ .withActiveVersion(nextVersion)
.withLastVersion(nextVersion)
.withDeletedAt(source.getDeletedAt())
.withSemanticModelVersionInfoPO(
@@ -563,40 +591,71 @@ public class SemanticModelMetaService {
private static SemanticModelVersionInfoPO versionInfoForOverwrite(
SemanticModelVersionInfoPO source, SemanticModelPO persistedPO, int nextVersion) {
- return SemanticModelVersionInfoPO.builder()
+ return source.toBuilder()
.withMetalakeId(persistedPO.getMetalakeId())
.withCatalogId(persistedPO.getCatalogId())
.withSchemaId(persistedPO.getSchemaId())
.withSemanticModelId(persistedPO.getSemanticModelId())
.withVersion(nextVersion)
- .withSemanticModelName(source.semanticModelName())
- .withSemanticModelComment(source.semanticModelComment())
- .withDatasets(source.datasets())
- .withRelationships(source.relationships())
- .withMetrics(source.metrics())
- .withAiContext(source.aiContext())
- .withCustomExtensions(source.customExtensions())
- .withProperties(source.properties())
- .withAuditInfo(source.auditInfo())
- .withDeletedAt(source.deletedAt())
.build();
}
SemanticModelPO getSemanticModelPOByIdentifier(NameIdentifier identifier) {
+ SemanticModelPO po = selectModel(identifier, latestOps);
+ requireSnapshot(po, po.getCurrentVersion(), "latest");
+ return po;
+ }
+
+ private static void lockParent(NameIdentifier identifier, SemanticModelPO observed) {
+ SchemaMetaService.getInstance()
+ .lockSchemaForEntityWrite(
+ identifier, observed.getSchemaId(), observed.getCatalogId(), observed.getMetalakeId());
+ }
+
+ private static void requireSnapshot(SemanticModelPO po, int revision, String pointer) {
+ Preconditions.checkState(
+ po.getSemanticModelVersionInfoPO() != null,
+ "Missing %s snapshot %s for Semantic Model %s",
+ pointer,
+ revision,
+ po.getSemanticModelId());
+ }
+
+ private static NoSuchEntityException missingModel(NameIdentifier identifier) {
+ return new NoSuchEntityException(
+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+ Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+ identifier.name());
+ }
+
+ private static NoSuchSemanticModelRevisionException missingRevision(
+ NameIdentifier identifier, int revision, int latest) {
+ return revision <= latest
+ ? new NoSuchSemanticModelRevisionException(
+ "Revision %s of Semantic Model %s was removed by version retention",
+ revision, identifier)
+ : new NoSuchSemanticModelRevisionException(
+ "Revision %s of Semantic Model %s does not exist", revision, identifier);
+ }
+
+ private SemanticModelPO selectModel(
+ NameIdentifier identifier, BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops) {
NameIdentifierUtil.checkSemanticModel(identifier);
- SemanticModelPO semanticModelPO =
+ SemanticModelPO po =
SessionUtils.getWithoutCommit(
SemanticModelMetaMapper.class,
mapper ->
POStorageReadRouting.getPO(
mapper, identifier, ops, Entity.EntityType.SEMANTIC_MODEL));
- if (semanticModelPO == null) {
- throw new NoSuchEntityException(
- NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
- Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
- identifier.name());
+ if (po == null) {
+ throw missingModel(identifier);
}
- return semanticModelPO;
+ return po;
+ }
+
+ private static BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> opsFor(
+ @Nullable SemanticModelRevisionSelector selector) {
+ return new HierarchicalConversionPOStorageOps<>(new SemanticModelPOStorageOps(selector));
}
private RuntimeException semanticModelWriteFailure(
@@ -620,7 +679,8 @@ public class SemanticModelMetaService {
current.getMetalakeId(), observedSemanticModelPO.getMetalakeId()));
}
- private List<SemanticModelPO> listSemanticModelPOs(Namespace namespace) {
+ private List<SemanticModelPO> listSemanticModelPOs(
+ Namespace namespace, BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops) {
return SessionUtils.getWithoutCommit(
SemanticModelMetaMapper.class,
mapper ->
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetricService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetricService.java
index ad3d342c57..a52ff0f09b 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetricService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetricService.java
@@ -20,7 +20,10 @@ package org.apache.gravitino.storage.relational.service;
import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.List;
@@ -32,6 +35,7 @@ import org.apache.gravitino.json.JsonUtils;
import org.apache.gravitino.metrics.Monitored;
import org.apache.gravitino.semantic.ImmutableSemanticModelMetric;
import org.apache.gravitino.semantic.SemanticModelMetric;
+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;
import org.apache.gravitino.storage.relational.mapper.SemanticModelMetricMapper;
import org.apache.gravitino.storage.relational.po.SemanticModelMetricListingPO;
import org.apache.gravitino.storage.relational.utils.SessionUtils;
@@ -50,7 +54,7 @@ public class SemanticModelMetricService {
}
/**
- * Lists live metric identifiers without reading definition snapshots.
+ * Lists live metric identifiers from the metrics of published snapshots.
*
* @param namespace The full schema namespace.
* @return Metric identifiers with the containing model as the last namespace level.
@@ -60,13 +64,38 @@ public class SemanticModelMetricService {
metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
baseMetricName = "listSemanticModelMetrics")
public List<NameIdentifier> listMetrics(Namespace namespace) {
- return read(namespace, false).stream()
- .filter(po -> po.getMetricName() != null)
- .map(
- po ->
- NameIdentifier.of(
- metricNamespace(namespace, po.getSemanticModelName()), po.getMetricName()))
- .toList();
+ List<NameIdentifier> results = new ArrayList<>();
+ for (SemanticModelMetricListingPO po : read(namespace)) {
+ if (po.getMetrics() == null) {
+ continue;
+ }
+ Namespace metricNamespace = metricNamespace(namespace, po.getSemanticModelName());
+ for (String name : decodeMetricNames(po.getMetrics())) {
+ results.add(NameIdentifier.of(metricNamespace, name));
+ }
+ }
+ return results;
+ }
+
+ /** Decodes metric names without constructing metric definitions. */
+ static List<String> decodeMetricNames(String json) {
+ try {
+ MetricName[] metrics = JsonUtils.anyFieldMapper().readValue(json, MetricName[].class);
+ Preconditions.checkArgument(metrics != null, "metrics JSON must be an array");
+ List<String> names = new ArrayList<>(metrics.length);
+ for (MetricName metric : metrics) {
+ Preconditions.checkArgument(
+ metric != null
+ && metric.name != null
+ && metric.name.isTextual()
+ && !metric.name.textValue().isEmpty(),
+ "Metric name must be present");
+ names.add(metric.name.textValue());
+ }
+ return names;
+ } catch (JsonProcessingException | IllegalArgumentException e) {
+ throw new IllegalStateException("Failed to decode Semantic Model metric names", e);
+ }
}
/**
@@ -82,14 +111,7 @@ public class SemanticModelMetricService {
baseMetricName = "listSemanticModelMetricInfos")
public List<SemanticModelMetric> listMetricInfos(Namespace namespace) {
List<SemanticModelMetric> results = new ArrayList<>();
- for (SemanticModelMetricListingPO po : read(namespace, true)) {
- if (po.getSemanticModelId() == null) {
- continue;
- }
- Preconditions.checkState(
- po.getVersion() != null,
- "Missing current snapshot for Semantic Model %s",
- po.getSemanticModelId());
+ for (SemanticModelMetricListingPO po : read(namespace)) {
if (po.getMetrics() == null) {
continue;
}
@@ -112,7 +134,7 @@ public class SemanticModelMetricService {
return results;
}
- private List<SemanticModelMetricListingPO> read(Namespace namespace, boolean details) {
+ private List<SemanticModelMetricListingPO> read(Namespace namespace) {
NamespaceUtil.checkSemanticModel(namespace);
String schemaName =
HierarchicalSchemaUtil.logicalToPhysical(
@@ -121,16 +143,32 @@ public class SemanticModelMetricService {
SessionUtils.getWithoutCommit(
SemanticModelMetricMapper.class,
mapper ->
- details
- ? mapper.listMetricSnapshots(namespace.level(0), namespace.level(1), schemaName)
- : mapper.listMetricNames(namespace.level(0), namespace.level(1), schemaName));
+ mapper.listMetricSnapshots(
+ namespace.level(0),
+ namespace.level(1),
+ schemaName,
+ SemanticModelRevisionSelector.ACTIVE));
if (rows.isEmpty() || rows.get(0) == null || rows.get(0).getSchemaId() == null) {
throw new NoSuchEntityException("Schema %s does not exist", namespace);
}
- return rows;
+ List<SemanticModelMetricListingPO> snapshots =
+ rows.stream().filter(po -> po.getSemanticModelId() != null).toList();
+ for (SemanticModelMetricListingPO snapshot : snapshots) {
+ Preconditions.checkState(
+ snapshot.getVersion() != null,
+ "Missing active snapshot for Semantic Model %s",
+ snapshot.getSemanticModelId());
+ }
+ return snapshots;
}
private Namespace metricNamespace(Namespace schema, String modelName) {
return Namespace.of(schema.level(0), schema.level(1), schema.level(2), modelName);
}
+
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ private static class MetricName {
+ @JsonProperty("name")
+ private JsonNode name;
+ }
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java
index e1e2ac5f31..2eac4b7b70 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java
@@ -22,10 +22,12 @@ import com.google.common.base.Preconditions;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
+import javax.annotation.Nullable;
import org.apache.gravitino.Entity;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;
import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
import org.apache.gravitino.storage.relational.po.SemanticModelPO;
@@ -33,8 +35,12 @@ import org.apache.gravitino.storage.relational.po.SemanticModelPO;
public class SemanticModelPOStorageOps
extends BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> {
- /** Creates Semantic Model persistent-object operations. */
- public SemanticModelPOStorageOps() {}
+ @Nullable private final SemanticModelRevisionSelector selector;
+
+ /** Creates operations selecting a revision, or only identity when the selector is null. */
+ public SemanticModelPOStorageOps(@Nullable SemanticModelRevisionSelector selector) {
+ this.selector = selector;
+ }
/**
* {@inheritDoc}
@@ -60,7 +66,7 @@ public class SemanticModelPOStorageOps
@Override
public SemanticModelPO getPO(
SemanticModelMetaMapper mapper, Long parentId, String semanticModelName) {
- return mapper.selectSemanticModelMetaBySchemaIdAndName(parentId, semanticModelName);
+ return mapper.selectSemanticModelMetaBySchemaIdAndName(parentId, semanticModelName, selector);
}
@Override
@@ -69,7 +75,11 @@ public class SemanticModelPOStorageOps
Namespace namespace = identifier.namespace();
SemanticModelPO po =
mapper.selectSemanticModelByFullQualifiedName(
- namespace.level(0), namespace.level(1), namespace.level(2), identifier.name());
+ namespace.level(0),
+ namespace.level(1),
+ namespace.level(2),
+ identifier.name(),
+ selector);
if (po == null) {
throw new NoSuchEntityException(
NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
@@ -90,7 +100,7 @@ public class SemanticModelPOStorageOps
@Override
public List<SemanticModelPO> listPOs(SemanticModelMetaMapper mapper, Long parentId) {
- return mapper.listSemanticModelPOsBySchemaId(parentId);
+ return mapper.listSemanticModelPOsBySchemaId(parentId, selector);
}
@Override
@@ -98,7 +108,7 @@ public class SemanticModelPOStorageOps
SemanticModelMetaMapper mapper, Namespace namespace) {
List<SemanticModelPO> pos =
mapper.listSemanticModelPOsByFullQualifiedName(
- namespace.level(0), namespace.level(1), namespace.level(2));
+ namespace.level(0), namespace.level(1), namespace.level(2), selector);
if (pos.isEmpty()) {
throw new NoSuchEntityException(
NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java b/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java
index 4719912553..427de8ba35 100644
--- a/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java
+++ b/core/src/test/java/org/apache/gravitino/authorization/TestAccessControlManager.java
@@ -37,6 +37,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.SERVICE_ADMINS;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
@@ -171,6 +172,7 @@ public class TestAccessControlManager {
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ Mockito.when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
Mockito.when(config.get(CATALOG_CACHE_EVICTION_INTERVAL_MS)).thenReturn(1000L);
// Fix cache for testing.
Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(true);
diff --git a/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java b/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
index 6ca49cecda..9dfeee88e8 100644
--- a/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
+++ b/core/src/test/java/org/apache/gravitino/authorization/TestOwnerManager.java
@@ -37,6 +37,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
import static org.apache.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;
@@ -140,6 +141,7 @@ public class TestOwnerManager {
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ Mockito.when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
Mockito.when(config.get(CATALOG_CACHE_EVICTION_INTERVAL_MS)).thenReturn(1000L);
// Fix the cache config for testing
Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(true);
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java
index 4c684a9a39..a8767f5653 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java
@@ -34,7 +34,9 @@ import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.Config;
import org.apache.gravitino.Configs;
@@ -59,7 +61,10 @@ import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.storage.relational.RelationalEntityStore;
import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetricMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelMetricPO;
import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
import org.apache.gravitino.utils.NamespaceUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.AfterEach;
@@ -75,6 +80,7 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {
private Config previousConfig;
private NameIdentifier modelIdent;
private ManagedSemanticModelOperations operations;
+ private RelationalEntityStore store;
@BeforeAll
public void captureEnvironmentConfig() {
@@ -97,7 +103,7 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {
Config config = new Config(false) {};
config.set(Configs.CACHE_ENABLED, false);
- RelationalEntityStore store = new RelationalEntityStore();
+ store = new RelationalEntityStore();
FieldUtils.writeField(store, "backend", backend, true);
FieldUtils.writeField(store, "cache", new NoOpsCache(config), true);
operations =
@@ -130,6 +136,10 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {
assertNotSame(created, loaded);
assertEquals(created, loaded);
+ assertEquals(1, loaded.revision());
+ assertEquals(SemanticModel.Status.PUBLISHED, loaded.status());
+ assertEquals(loaded.auditInfo().creator(), loaded.publishedBy());
+ assertEquals(loaded.auditInfo().createTime(), loaded.publishedAt());
assertEquals(definition, loaded.definition());
assertEquals(1, writeValidationCount.get());
assertTrue(backend.exists(modelIdent, Entity.EntityType.SEMANTIC_MODEL));
@@ -163,6 +173,8 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {
SemanticModelChange.setProperty("tier", "gold"),
SemanticModelChange.replaceDefinition(replacement));
+ assertEquals(2, altered.revision());
+ assertEquals(SemanticModel.Status.PUBLISHED, altered.status());
assertEquals(renamedIdent.name(), altered.name());
assertEquals("Updated", altered.comment());
assertEquals(replacement, altered.definition());
@@ -347,6 +359,36 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {
assertEquals(2, writeValidationCount.get());
}
+ private static Set<String> metricIdentities(long modelId) {
+ return SessionUtils.getWithoutCommit(
+ SemanticModelMetricMapper.class,
+ mapper -> mapper.selectSemanticModelMetricsByModelIdForUpdate(modelId))
+ .stream()
+ .map(SemanticModelMetricPO::metricName)
+ .collect(Collectors.toSet());
+ }
+
+ private static SemanticModelSourceUpdate associations(TableEntity source) {
+ return SemanticModelSourceUpdate.replace(
+ List.of(new SemanticModelSource(source.name(), source.type(), source.id())));
+ }
+
+ private static int retainedSourceRangeCount(long modelId) throws Exception {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+ PreparedStatement statement =
+ session
+ .getConnection()
+ .prepareStatement(
+ "SELECT COUNT(*) FROM semantic_model_source_rel WHERE semantic_model_id = ? AND deleted_at = 0")) {
+ statement.setLong(1, modelId);
+ try (ResultSet result = statement.executeQuery()) {
+ assertTrue(result.next());
+ return result.getInt(1);
+ }
+ }
+ }
+
private List<Association> liveAssociations(long modelId) throws Exception {
try (SqlSession session =
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
@@ -355,7 +397,7 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {
.getConnection()
.prepareStatement(
"SELECT id, dataset_name, source_type, source_id FROM semantic_model_source_rel"
- + " WHERE semantic_model_id = ? AND deleted_at = 0 ORDER BY id")) {
+ + " WHERE semantic_model_id = ? AND deleted_at = 0 AND to_version = 0 ORDER BY id")) {
statement.setLong(1, modelId);
try (ResultSet result = statement.executeQuery()) {
List<Association> rows = new ArrayList<>();
diff --git a/core/src/test/java/org/apache/gravitino/domain/TestDomainManager.java b/core/src/test/java/org/apache/gravitino/domain/TestDomainManager.java
index 5f87311c3c..32b68187cb 100644
--- a/core/src/test/java/org/apache/gravitino/domain/TestDomainManager.java
+++ b/core/src/test/java/org/apache/gravitino/domain/TestDomainManager.java
@@ -36,6 +36,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
import static org.apache.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;
@@ -1255,6 +1256,7 @@ public class TestDomainManager {
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ Mockito.when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(true);
Mockito.when(config.get(Configs.CACHE_MAX_ENTRIES)).thenReturn(10_000);
Mockito.when(config.get(Configs.CACHE_EXPIRATION_TIME)).thenReturn(3_600_000L);
diff --git a/core/src/test/java/org/apache/gravitino/domain/TestDomainMembershipResolver.java b/core/src/test/java/org/apache/gravitino/domain/TestDomainMembershipResolver.java
index 847595bd5e..0afc98d2aa 100644
--- a/core/src/test/java/org/apache/gravitino/domain/TestDomainMembershipResolver.java
+++ b/core/src/test/java/org/apache/gravitino/domain/TestDomainMembershipResolver.java
@@ -511,6 +511,32 @@ class TestDomainMembershipResolver {
new DomainRelation[] {DomainRelation.inherited(SCHEMA)}, expanded[0].relations());
}
+ @Test
+ void testSemanticModelMembershipUsesIdentityForDirectAndInheritedMembers() throws Exception {
+ DomainEntity finance = domain(1, "Finance", null, 10L, null);
+ DomainEntity[] domains = {finance};
+ MetadataObject directModel = object("cat.db.direct_draft", MetadataObject.Type.SEMANTIC_MODEL);
+ MetadataObject inheritedModel =
+ object("cat.db.inherited_draft", MetadataObject.Type.SEMANTIC_MODEL);
+ candidate(10, SCHEMA, directModel);
+ assign(SCHEMA, tag(10, "department"));
+ assign(directModel, tag(10, "department"));
+ when(store.listSemanticModelIdentifiers(Namespace.of(METALAKE, "cat", "db")))
+ .thenReturn(
+ List.of(
+ NameIdentifier.of(METALAKE, "cat", "db", directModel.name()),
+ NameIdentifier.of(METALAKE, "cat", "db", inheritedModel.name())));
+
+ assertArrayEquals(
+ new MetadataObject[] {SCHEMA, directModel},
+ objects(resolver.listMembers(METALAKE, finance, domains, direct().build())));
+ DomainMember[] expanded = resolver.listMembers(METALAKE, finance, domains, all());
+ assertArrayEquals(new MetadataObject[] {directModel, inheritedModel}, objects(expanded));
+ assertArrayEquals(
+ new DomainRelation[] {DomainRelation.inherited(SCHEMA)}, expanded[1].relations());
+ verify(store).listSemanticModelIdentifiers(Namespace.of(METALAKE, "cat", "db"));
+ }
+
@Test
void testDirectMembersStorageFailureAndUnknownScopes() throws Exception {
DomainEntity finance = domain(1, "Finance", null, 10L, null);
diff --git a/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java
index f8b4843656..2d8b7939db 100644
--- a/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/hook/TestFilesetHookDispatcher.java
@@ -37,6 +37,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.SERVICE_ADMINS;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
@@ -263,6 +264,7 @@ public class TestFilesetHookDispatcher extends TestOperationDispatcher {
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ Mockito.when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
Mockito.when(config.get(CATALOG_CACHE_EVICTION_INTERVAL_MS)).thenReturn(1000L);
Mockito.doReturn(100000L).when(config).get(TREE_LOCK_MAX_NODE_IN_MEMORY);
Mockito.doReturn(1000L).when(config).get(TREE_LOCK_MIN_NODE_IN_MEMORY);
diff --git a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
index 05a175727f..c11cf8fbae 100644
--- a/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
+++ b/core/src/test/java/org/apache/gravitino/policy/TestPolicyManager.java
@@ -37,6 +37,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
import static org.apache.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;
@@ -307,6 +308,7 @@ public class TestPolicyManager {
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ Mockito.when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
// Fix cache config for test
Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(true);
Mockito.when(config.get(Configs.CACHE_MAX_ENTRIES)).thenReturn(10_000);
diff --git a/core/src/test/java/org/apache/gravitino/semantic/TestSemanticModelRevisionSelector.java b/core/src/test/java/org/apache/gravitino/semantic/TestSemanticModelRevisionSelector.java
new file mode 100644
index 0000000000..f896fa2f13
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/semantic/TestSemanticModelRevisionSelector.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.gravitino.semantic;
+
+import static org.apache.gravitino.semantic.SemanticModelRevisionSelector.ACTIVE;
+import static org.apache.gravitino.semantic.SemanticModelRevisionSelector.LATEST;
+import static org.apache.gravitino.semantic.SemanticModelRevisionSelector.numbered;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import org.junit.jupiter.api.Test;
+
+class TestSemanticModelRevisionSelector {
+ @Test
+ void testSelectorNumbers() {
+ assertEquals(0, ACTIVE.getNumber());
+ assertEquals(-1, LATEST.getNumber());
+ assertEquals(1, numbered(1).getNumber());
+ assertThrows(IllegalArgumentException.class, () -> numbered(ACTIVE.getNumber()));
+ assertThrows(IllegalArgumentException.class, () -> numbered(LATEST.getNumber()));
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/stats/TestStatisticManager.java b/core/src/test/java/org/apache/gravitino/stats/TestStatisticManager.java
index 862effb935..2316f7bd64 100644
--- a/core/src/test/java/org/apache/gravitino/stats/TestStatisticManager.java
+++ b/core/src/test/java/org/apache/gravitino/stats/TestStatisticManager.java
@@ -37,6 +37,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
import static org.apache.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;
@@ -133,6 +134,7 @@ public class TestStatisticManager {
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ Mockito.when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
// Fix cache config for test
Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(true);
Mockito.when(config.get(Configs.CACHE_MAX_ENTRIES)).thenReturn(10_000);
diff --git a/core/src/test/java/org/apache/gravitino/storage/AbstractEntityStorageTest.java b/core/src/test/java/org/apache/gravitino/storage/AbstractEntityStorageTest.java
index 4e2ed6ea5e..d2c1dbea45 100644
--- a/core/src/test/java/org/apache/gravitino/storage/AbstractEntityStorageTest.java
+++ b/core/src/test/java/org/apache/gravitino/storage/AbstractEntityStorageTest.java
@@ -40,6 +40,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.VERSION_RETENTION_COUNT;
import static org.apache.gravitino.file.Fileset.LOCATION_NAME_UNKNOWN;
@@ -166,6 +167,7 @@ abstract class AbstractEntityStorageTest {
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ Mockito.when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
// Fix cache config for test
Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(true);
Mockito.when(config.get(Configs.CACHE_MAX_ENTRIES)).thenReturn(10_000);
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreHierarchicalCache.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreHierarchicalCache.java
index 11d66d3ca4..f3a73b57de 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreHierarchicalCache.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreHierarchicalCache.java
@@ -209,6 +209,7 @@ public class TestRelationalEntityStoreHierarchicalCache {
.thenReturn(Configs.DEFAULT_RELATIONAL_JDBC_BACKEND_MAX_WAIT_MILLISECONDS);
Mockito.when(config.get(Configs.STORE_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
Mockito.when(config.get(Configs.VERSION_RETENTION_COUNT)).thenReturn(1L);
+ Mockito.when(config.get(Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreLockWaitTimeout.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreLockWaitTimeout.java
index 663c46f502..e1218806e3 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreLockWaitTimeout.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalEntityStoreLockWaitTimeout.java
@@ -500,6 +500,7 @@ public class TestRelationalEntityStoreLockWaitTimeout {
.thenReturn(Configs.DEFAULT_RELATIONAL_JDBC_BACKEND_MAX_WAIT_MILLISECONDS);
Mockito.when(config.get(Configs.STORE_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
Mockito.when(config.get(Configs.VERSION_RETENTION_COUNT)).thenReturn(1L);
+ Mockito.when(config.get(Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_POLL_INTERVAL_SECS)).thenReturn(3L);
Mockito.when(config.get(Configs.ENTITY_CHANGE_LOG_POLL_BATCH_SIZE))
.thenReturn(Configs.DEFAULT_ENTITY_CHANGE_LOG_POLL_BATCH_SIZE);
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalGarbageCollector.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalGarbageCollector.java
index 51c3014500..470f4908a6 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalGarbageCollector.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestRelationalGarbageCollector.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.storage.relational;
import static org.apache.gravitino.Configs.GARBAGE_COLLECTOR_SINGLE_DELETION_LIMIT;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.VERSION_RETENTION_COUNT;
import static org.mockito.Mockito.mock;
@@ -28,6 +29,7 @@ import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import org.apache.gravitino.Config;
+import org.apache.gravitino.Entity;
import org.apache.gravitino.MetadataObject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -46,12 +48,16 @@ public class TestRelationalGarbageCollector {
Config config = mock(Config.class);
when(config.get(STORE_DELETE_AFTER_TIME)).thenReturn(1000L);
when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
when(orphanedRelationCleanup.softDeleteOrphanedRelations(
MetadataObject.Type.TABLE, GARBAGE_COLLECTOR_SINGLE_DELETION_LIMIT))
.thenReturn(2, 0);
new RelationalGarbageCollector(backend, config).collectAndClean();
+ verify(backend).deleteOldVersionData(Entity.EntityType.SEMANTIC_MODEL, 100L);
+ verify(backend).deleteOldVersionData(Entity.EntityType.TABLE, 1L);
+
for (MetadataObject.Type type : MetadataObject.Type.values()) {
int expectedInvocations = type == MetadataObject.Type.TABLE ? 2 : 1;
verify(orphanedRelationCleanup, times(expectedInvocations))
@@ -65,6 +71,7 @@ public class TestRelationalGarbageCollector {
Config config = mock(Config.class);
when(config.get(STORE_DELETE_AFTER_TIME)).thenReturn(1000L);
when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
Assertions.assertDoesNotThrow(
() -> new RelationalGarbageCollector(backend, config).collectAndClean());
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.java
index c939e0dd50..8d99a71e8f 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.java
@@ -74,6 +74,7 @@ import org.apache.gravitino.semantic.Field;
import org.apache.gravitino.semantic.Metric;
import org.apache.gravitino.semantic.Relationship;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.storage.relational.mapper.EntityChangeLogMapper;
import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
@@ -299,11 +300,11 @@ public class TestSemanticModelJDBCBackend extends TestJDBCBackend {
backend.insert(original, false);
assertEquals(original, backend.get(original.nameIdentifier(), original.type()));
backend.update(original.nameIdentifier(), original.type(), ignored -> empty);
- assertEquals(empty, backend.get(original.nameIdentifier(), original.type()));
+ assertSnapshot(empty, 2);
backend.update(original.nameIdentifier(), original.type(), ignored -> absent);
- assertEquals(absent, backend.get(original.nameIdentifier(), original.type()));
+ assertSnapshot(absent, 3);
backend.insert(original, true);
- assertEquals(original, backend.get(original.nameIdentifier(), original.type()));
+ assertSnapshot(original, 4);
assertEquals(4, getSemanticModelPO(original.id()).getCurrentVersion());
assertEquals(List.of(1, 2, 3, 4), activeSnapshotVersions(original.id()));
@@ -400,8 +401,7 @@ public class TestSemanticModelJDBCBackend extends TestJDBCBackend {
backend.insert(original, false);
backend.insert(replacement, true);
- assertEquals(
- replacement, backend.get(original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL));
+ assertSnapshot(replacement, 2);
SemanticModelPO persisted = getSemanticModelPO(original.id());
assertEquals(2, persisted.getCurrentVersion());
assertEquals(2, persisted.getLastVersion());
@@ -433,8 +433,7 @@ public class TestSemanticModelJDBCBackend extends TestJDBCBackend {
backend.insert(original, false);
backend.insert(replacement, true);
- assertEquals(
- expected, backend.get(original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL));
+ assertSnapshot(expected, 2);
SemanticModelPO persisted = getSemanticModelPO(original.id());
assertEquals(2, persisted.getCurrentVersion());
assertEquals(2, persisted.getLastVersion());
@@ -605,7 +604,10 @@ public class TestSemanticModelJDBCBackend extends TestJDBCBackend {
assertEquals(List.of(1, 2, 3), activeSnapshotVersions(created.id()));
SemanticModelEntity winner =
backend.get(created.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL);
- assertTrue(winner.equals(overwriteOne) || winner.equals(overwriteTwo));
+ assertEquals(3, winner.revision());
+ assertTrue(
+ winner.fields().equals(overwriteOne.fields())
+ || winner.fields().equals(overwriteTwo.fields()));
assertEquals(0, countEntityChanges());
}
@@ -631,17 +633,10 @@ public class TestSemanticModelJDBCBackend extends TestJDBCBackend {
SemanticModelEntity renamed =
semanticModel(
- original.id(),
- namespace,
- "renamed_sales_model",
- false,
- ImmutableMap.of("domain", "sales_v2"));
- assertEquals(
- renamed,
- backend.update(
- original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL, ignored -> renamed));
+ original.id(), namespace, "renamed_sales_model", false, original.properties());
+ backend.update(original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL, ignored -> renamed);
assertFalse(backend.exists(original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL));
- assertEquals(renamed, backend.get(renamed.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL));
+ assertSnapshot(renamed, 2);
assertTrue(backend.delete(renamed.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL, false));
assertFalse(backend.exists(renamed.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL));
@@ -909,11 +904,22 @@ public class TestSemanticModelJDBCBackend extends TestJDBCBackend {
}
}
+ private void assertSnapshot(SemanticModelEntity expected, int revision) throws IOException {
+ SemanticModelEntity loaded = backend.get(expected.nameIdentifier(), expected.type());
+ assertEquals(expected.fields(), loaded.fields());
+ assertEquals(revision, loaded.revision());
+ assertEquals(expected.status(), loaded.status());
+ assertEquals(expected.publishedAt(), loaded.publishedAt());
+ assertEquals(expected.publishedBy(), loaded.publishedBy());
+ }
+
private SemanticModelPO getSemanticModelPO(Long semanticModelId) {
SemanticModelPO po =
SessionUtils.getWithoutCommit(
SemanticModelMetaMapper.class,
- mapper -> mapper.selectSemanticModelMetaById(semanticModelId));
+ mapper ->
+ mapper.selectSemanticModelMetaById(
+ semanticModelId, SemanticModelRevisionSelector.LATEST));
assertNotNull(po);
return po;
}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/po/TestSemanticModelPO.java b/core/src/test/java/org/apache/gravitino/storage/relational/po/TestSemanticModelPO.java
index 3bb806ce0d..aceff0aed3 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/po/TestSemanticModelPO.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/po/TestSemanticModelPO.java
@@ -177,7 +177,7 @@ class TestSemanticModelPO {
private static SemanticModelPO identity(SemanticModelVersionInfoPO snapshot) {
return SemanticModelPO.builder()
.withSemanticModelId(snapshot.semanticModelId())
- .withSemanticModelName(snapshot.semanticModelName())
+ .withSemanticModelName("sales_model")
.withMetalakeId(snapshot.metalakeId())
.withCatalogId(snapshot.catalogId())
.withSchemaId(snapshot.schemaId())
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetaService.java
index e2f4d94f01..2952e67277 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetaService.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.storage.relational.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -45,7 +46,6 @@ import org.apache.gravitino.EntityAlreadyExistsException;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.exceptions.NoSuchEntityException;
-import org.apache.gravitino.exceptions.OptimisticLockException;
import org.apache.gravitino.integration.test.util.GravitinoITUtils;
import org.apache.gravitino.meta.SchemaEntity;
import org.apache.gravitino.meta.SemanticModelEntity;
@@ -56,6 +56,7 @@ import org.apache.gravitino.semantic.DialectExpression;
import org.apache.gravitino.semantic.Expression;
import org.apache.gravitino.semantic.Metric;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelRevisionSelector;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.storage.relational.EntityChangeLogNameIdentifierCodec;
import org.apache.gravitino.storage.relational.TestJDBCBackend;
@@ -139,10 +140,12 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
"overwritten comment",
"overwritten");
SemanticModelMetaService.getInstance().insertSemanticModel(overwritten, true);
- assertEquals(
- overwritten,
+ SemanticModelEntity loaded =
SemanticModelMetaService.getInstance()
- .getSemanticModelByIdentifier(overwritten.nameIdentifier()));
+ .getSemanticModelByIdentifier(overwritten.nameIdentifier());
+ assertEquals(overwritten.definition(), loaded.definition());
+ assertEquals(overwritten.comment(), loaded.comment());
+ assertEquals(2, loaded.revision());
assertEquals(2, listSemanticModelVersions(original.id()).size());
assertThrows(
@@ -153,7 +156,7 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
}
@TestTemplate
- public void testUpdateCreatesFullSnapshotAndRenameChangeLog() throws IOException {
+ public void testUpdateAndRenameCreatePublishedSnapshots() throws IOException {
String oldName = GravitinoITUtils.genRandomName("sales_model_old");
String newName = GravitinoITUtils.genRandomName("sales_model_new");
SemanticModelEntity original =
@@ -163,40 +166,50 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
long lastChangeId = maxEntityChangeId();
SemanticModelEntity expected =
- semanticModelEntity(original.id(), newName, "orders_v2", "v2 comment", "v2");
+ semanticModelEntity(original.id(), oldName, "orders_v2", "v2 comment", "v2");
SemanticModelEntity updated =
SemanticModelMetaService.getInstance()
.updateSemanticModel(original.nameIdentifier(), ignored -> expected);
- assertEquals(expected, updated);
+ assertEquals(expected.definition(), updated.definition());
+ assertEquals(2, updated.revision());
+ SemanticModelEntity renamed =
+ semanticModelEntity(original.id(), newName, "orders_v2", "v2 comment", "v2");
+ SemanticModelMetaService service = SemanticModelMetaService.getInstance();
+ assertEquals(
+ 3, service.updateSemanticModel(original.nameIdentifier(), ignored -> renamed).revision());
+ assertEquals(
+ newName,
+ service
+ .getSemanticModelByIdentifier(
+ renamed.nameIdentifier(), SemanticModelRevisionSelector.numbered(1))
+ .name());
assertThrows(
NoSuchEntityException.class,
() ->
SemanticModelMetaService.getInstance()
.getSemanticModelByIdentifier(original.nameIdentifier()));
assertEquals(
- expected,
- SemanticModelMetaService.getInstance()
- .getSemanticModelByIdentifier(expected.nameIdentifier()));
+ updated.definition(),
+ service.getSemanticModelByIdentifier(renamed.nameIdentifier()).definition());
assertEquals(
original.id(),
SemanticModelMetaService.getInstance()
.getSemanticModelIdBySchemaIdAndName(schemaId, newName));
Map<Integer, VersionState> versions = listSemanticModelVersions(original.id());
- assertEquals(2, versions.size());
- assertEquals(oldName, versions.get(1).name);
+ assertEquals(3, versions.size());
assertEquals("v1 comment", versions.get(1).comment);
assertTrue(versions.get(1).datasets.contains("orders_v1"));
- assertEquals(newName, versions.get(2).name);
assertEquals("v2 comment", versions.get(2).comment);
assertTrue(versions.get(2).datasets.contains("orders_v2"));
assertEquals(0L, versions.get(1).deletedAt);
assertEquals(0L, versions.get(2).deletedAt);
+ assertEquals(0L, versions.get(3).deletedAt);
long[] identityVersions = semanticModelIdentityVersions(original.id());
- assertEquals(2L, identityVersions[0]);
- assertEquals(2L, identityVersions[1]);
+ assertEquals(3L, identityVersions[0]);
+ assertEquals(3L, identityVersions[1]);
assertEntityChange(lastChangeId, oldName, OperateType.ALTER);
}
@@ -211,7 +224,7 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
long lastChangeId = maxEntityChangeId();
SemanticModelEntity renamed =
- semanticModelEntity(original.id(), newName, "orders", "renamed", "v2");
+ semanticModelEntity(original.id(), newName, "orders", "original", "v1");
SemanticModelMetaService.getInstance()
.updateSemanticModel(original.nameIdentifier(), ignored -> renamed);
assertEntityChange(lastChangeId, oldName, OperateType.ALTER);
@@ -411,7 +424,7 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
}
@TestTemplate
- public void testOptimisticDropRejectsStaleInternalVersion() throws IOException {
+ public void testDropUsesObservedNameAfterConcurrentSnapshotWrite() throws IOException {
String semanticModelName = GravitinoITUtils.genRandomName("optimistic_drop_model");
SemanticModelEntity original =
semanticModelEntity(
@@ -429,20 +442,46 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
SemanticModelMetaService.getInstance()
.updateSemanticModel(original.nameIdentifier(), ignored -> updated);
- assertThrows(
- OptimisticLockException.class,
- () ->
- SemanticModelMetaService.getInstance()
- .deleteSemanticModelWithVersion(original.nameIdentifier(), stalePO));
+ SemanticModelMetaService service = SemanticModelMetaService.getInstance();
+ service.deleteObservedSemanticModel(original.nameIdentifier(), stalePO);
- assertEquals(
- updated,
- SemanticModelMetaService.getInstance()
- .getSemanticModelByIdentifier(updated.nameIdentifier()));
+ assertThrows(
+ NoSuchEntityException.class,
+ () -> service.getSemanticModelByIdentifier(original.nameIdentifier()));
Map<Integer, VersionState> versions = listSemanticModelVersions(original.id());
assertEquals(2, versions.size());
- assertEquals(0L, versions.get(1).deletedAt);
- assertEquals(0L, versions.get(2).deletedAt);
+ assertTrue(versions.get(1).deletedAt > 0L);
+ assertTrue(versions.get(2).deletedAt > 0L);
+ }
+
+ @TestTemplate
+ public void testAlterAndDropGuardTheObservedName() throws IOException {
+ String name = GravitinoITUtils.genRandomName("observed_name");
+ SemanticModelEntity original =
+ semanticModelEntity(RandomIdGenerator.INSTANCE.nextId(), name, "orders", "original", "v1");
+ SemanticModelMetaService service = SemanticModelMetaService.getInstance();
+ service.insertSemanticModel(original, false);
+ SemanticModelPO observed = service.getSemanticModelPOByIdentifier(original.nameIdentifier());
+ SemanticModelEntity renamed =
+ semanticModelEntity(original.id(), name + "_renamed", "orders", "original", "v1");
+ SemanticModelEntity updated =
+ semanticModelEntity(original.id(), name, "orders", "changed", "v1");
+
+ assertThrows(
+ NoSuchEntityException.class,
+ () ->
+ service.updateSemanticModel(
+ original.nameIdentifier(),
+ ignored -> {
+ renameObservedModel(service, original, renamed);
+ return updated;
+ }));
+ assertThrows(
+ NoSuchEntityException.class,
+ () -> service.deleteObservedSemanticModel(original.nameIdentifier(), observed));
+ assertEquals(
+ "original", service.getSemanticModelByIdentifier(renamed.nameIdentifier()).comment());
+ assertEquals(2, listSemanticModelVersions(original.id()).size());
}
@TestTemplate
@@ -458,7 +497,7 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
assertTrue(service.deleteSemanticModel(original.nameIdentifier()));
assertThrows(
NoSuchEntityException.class,
- () -> service.deleteSemanticModelWithVersion(original.nameIdentifier(), stalePO));
+ () -> service.deleteObservedSemanticModel(original.nameIdentifier(), stalePO));
assertEquals(1, listSemanticModelVersions(original.id()).size());
}
@@ -486,6 +525,7 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
.updateSemanticModel(current.nameIdentifier(), ignored -> next);
}
+ assertTrue(isRetentionCandidate(current.id(), 1L));
assertEquals(
2,
SemanticModelMetaService.getInstance()
@@ -494,6 +534,7 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
assertTrue(retainedVersions.get(1).deletedAt > 0L);
assertTrue(retainedVersions.get(2).deletedAt > 0L);
assertEquals(0L, retainedVersions.get(3).deletedAt);
+ assertFalse(isRetentionCandidate(current.id(), 1L));
SemanticModelEntity finalCurrent = current;
long lastChangeId = maxEntityChangeId();
@@ -515,6 +556,14 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
assertEquals(0, countSemanticModelIdentities(finalCurrent.id()));
}
+ private boolean isRetentionCandidate(long modelId, long retentionCount) {
+ return SessionUtils.getWithoutCommit(
+ SemanticModelVersionInfoMapper.class,
+ mapper ->
+ mapper.selectSemanticModelVersionsByRetentionCount(retentionCount).stream()
+ .anyMatch(candidate -> candidate.semanticModelId() == modelId));
+ }
+
private SemanticModelEntity semanticModelEntity(
Long id, String name, String datasetName, String comment, String extensionData) {
return SemanticModelEntity.builder()
@@ -620,6 +669,15 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
});
}
+ private static void renameObservedModel(
+ SemanticModelMetaService service, SemanticModelEntity original, SemanticModelEntity renamed) {
+ try {
+ service.updateSemanticModel(original.nameIdentifier(), current -> renamed);
+ } catch (IOException e) {
+ throw new AssertionError(e);
+ }
+ }
+
private Map<Integer, VersionState> listSemanticModelVersions(Long semanticModelId) {
Map<Integer, VersionState> versions = new HashMap<>();
try (SqlSession sqlSession =
@@ -629,7 +687,7 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
ResultSet resultSet =
statement.executeQuery(
String.format(
- "SELECT version, semantic_model_name, semantic_model_comment,"
+ "SELECT version, semantic_model_comment,"
+ " datasets, deleted_at"
+ " FROM semantic_model_version_info WHERE semantic_model_id = %d",
semanticModelId))) {
@@ -637,7 +695,6 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
versions.put(
resultSet.getInt("version"),
new VersionState(
- resultSet.getString("semantic_model_name"),
resultSet.getString("semantic_model_comment"),
resultSet.getString("datasets"),
resultSet.getLong("deleted_at")));
@@ -708,13 +765,11 @@ public class TestSemanticModelMetaService extends TestJDBCBackend {
}
private static class VersionState {
- private final String name;
private final String comment;
private final String datasets;
private final long deletedAt;
- private VersionState(String name, String comment, String datasets, long deletedAt) {
- this.name = name;
+ private VersionState(String comment, String datasets, long deletedAt) {
this.comment = comment;
this.datasets = datasets;
this.deletedAt = deletedAt;
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricDiscovery.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricDiscovery.java
index c6190e916a..b846e56482 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricDiscovery.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricDiscovery.java
@@ -127,15 +127,18 @@ public class TestSemanticModelMetricDiscovery extends TestJDBCBackend {
Namespace namespace = parents();
SemanticModelEntity original = model(namespace, "before", metric("removed"), metric("kept"));
backend.insert(original, false);
- SemanticModelEntity replacement = copy(original, "after", metric("added"), metric("kept"));
+ SemanticModelEntity replacement =
+ copy(original, original.name(), metric("added"), metric("kept"));
backend.update(original.nameIdentifier(), original.type(), old -> replacement);
+ SemanticModelEntity renamed = copy(replacement, "after", metric("added"), metric("kept"));
+ backend.update(replacement.nameIdentifier(), replacement.type(), old -> renamed);
ManagedSemanticModelOperations operations = operations();
NameIdentifier[] expected = {
identifier(namespace, "after", "added"), identifier(namespace, "after", "kept")
};
assertArrayEquals(expected, operations.listMetrics(namespace));
assertArrayEquals(expected, identifiers(operations.listMetricInfos(namespace)));
- backend.delete(replacement.nameIdentifier(), replacement.type(), false);
+ backend.delete(renamed.nameIdentifier(), renamed.type(), false);
assertEquals(0, operations.listMetrics(namespace).length);
assertEquals(0, operations.listMetricInfos(namespace).length);
backend.insert(model(namespace, "after", metric("new")), false);
@@ -168,40 +171,43 @@ public class TestSemanticModelMetricDiscovery extends TestJDBCBackend {
}
@TestTemplate
- void testNamesDoNotReadSnapshotsAndDetailsDoNotReadIdentities() throws Exception {
+ void testDiscoveryUsesActiveSnapshotsAndDetectsMissingSnapshots() throws Exception {
Namespace namespace = parents();
SemanticModelEntity model = model(namespace, "sales", metric("revenue"));
backend.insert(model, false);
execute("DELETE FROM semantic_model_metric_meta WHERE semantic_model_id = ?", model.id());
- assertTrue(backend.listSemanticModelMetrics(namespace).isEmpty());
assertEquals(
- metric("revenue"), backend.listSemanticModelMetricInfos(namespace).get(0).metric());
- SemanticModelEntity independent = model(namespace, "names_only", metric("count"));
- backend.insert(independent, false);
- execute(
- "DELETE FROM semantic_model_version_info WHERE semantic_model_id = ?", independent.id());
- assertEquals(
- List.of(identifier(namespace, "names_only", "count")),
+ List.of(identifier(namespace, "sales", "revenue")),
backend.listSemanticModelMetrics(namespace));
+ assertEquals(
+ metric("revenue"), backend.listSemanticModelMetricInfos(namespace).get(0).metric());
+ execute("DELETE FROM semantic_model_version_info WHERE semantic_model_id = ?", model.id());
+ assertThrows(
+ IllegalStateException.class, () -> backend.get(model.nameIdentifier(), model.type()));
+ assertThrows(IllegalStateException.class, () -> backend.listSemanticModelMetrics(namespace));
assertThrows(
IllegalStateException.class, () -> backend.listSemanticModelMetricInfos(namespace));
}
@TestTemplate
- void testMalformedMetricsFailWholeDetailedRead() throws Exception {
+ void testMalformedMetricsFailTheReadAndNamesOnlyRequireNames() throws Exception {
Namespace namespace = parents();
backend.insert(model(namespace, "valid", metric("good")), false);
SemanticModelEntity broken = model(namespace, "broken", metric("bad"));
backend.insert(broken, false);
- for (String json : List.of("not-json", "null", "{}", "[null]", "[{\"name\":\"bad\"}]")) {
- execute(
- "UPDATE semantic_model_version_info SET metrics = ? WHERE semantic_model_id = ?",
- json,
- broken.id());
- assertEquals(2, backend.listSemanticModelMetrics(namespace).size());
+ String update =
+ "UPDATE semantic_model_version_info SET metrics = ? WHERE semantic_model_id = ?";
+ for (String json : List.of("not-json", "null", "{}", "[null]")) {
+ execute(update, json, broken.id());
+ assertThrows(
+ IllegalStateException.class, () -> backend.listSemanticModelMetrics(namespace), json);
assertThrows(
IllegalStateException.class, () -> backend.listSemanticModelMetricInfos(namespace), json);
}
+ execute(update, "[{\"name\":\"bad\"}]", broken.id());
+ assertEquals(2, backend.listSemanticModelMetrics(namespace).size());
+ assertThrows(
+ IllegalStateException.class, () -> backend.listSemanticModelMetricInfos(namespace));
}
@TestTemplate
@@ -228,12 +234,12 @@ public class TestSemanticModelMetricDiscovery extends TestJDBCBackend {
}
@TestTemplate
- void testReadsDuringReplaceAndRenameSeeOnlyCommittedState() throws Exception {
+ void testReadsDuringReplacementSeeOnlyCommittedState() throws Exception {
for (boolean rollback : List.of(false, true)) {
Namespace namespace = parents();
SemanticModelEntity original = model(namespace, "before", metric("before"));
backend.insert(original, false);
- SemanticModelEntity replacement = copy(original, "after", metric("after"));
+ SemanticModelEntity replacement = copy(original, original.name(), metric("after"));
CountDownLatch staged = new CountDownLatch(1);
CountDownLatch finish = new CountDownLatch(1);
ExecutorService executor = Executors.newSingleThreadExecutor();
@@ -269,7 +275,8 @@ public class TestSemanticModelMetricDiscovery extends TestJDBCBackend {
return null;
});
assertTrue(staged.await(30, TimeUnit.SECONDS));
- // The writer has updated the name, version pointer, and identities, but has not committed.
+ // The writer has advanced the version pointer and updated identities inside its
+ // transaction.
assertArrayEquals(
new NameIdentifier[] {identifier(namespace, "before", "before")},
operations().listMetrics(namespace));
@@ -280,10 +287,10 @@ public class TestSemanticModelMetricDiscovery extends TestJDBCBackend {
writer.get(30, TimeUnit.SECONDS);
String committed = rollback ? "before" : "after";
assertArrayEquals(
- new NameIdentifier[] {identifier(namespace, committed, committed)},
+ new NameIdentifier[] {identifier(namespace, original.name(), committed)},
operations().listMetrics(namespace));
assertArrayEquals(
- new NameIdentifier[] {identifier(namespace, committed, committed)},
+ new NameIdentifier[] {identifier(namespace, original.name(), committed)},
identifiers(operations().listMetricInfos(namespace)));
} finally {
finish.countDown();
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricIdentities.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricIdentities.java
index 09376b147a..ba4be67440 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricIdentities.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelMetricIdentities.java
@@ -103,16 +103,20 @@ public class TestSemanticModelMetricIdentities extends TestJDBCBackend {
.withDescription("Updated description")
.build())
.toArray(Metric[]::new);
- SemanticModelEntity renamed = copy(original, original.id(), "renamed", reordered);
+ SemanticModelEntity updated = copy(original, original.id(), original.name(), reordered);
+ backend.update(original.nameIdentifier(), original.type(), old -> updated);
+ SemanticModelEntity renamed = copy(updated, updated.id(), "renamed", reordered);
try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class, CALLS_REAL_METHODS)) {
backend.update(original.nameIdentifier(), original.type(), old -> renamed);
sessions.verify(
() -> SessionUtils.doWithoutCommit(eq(SemanticModelMetricMapper.class), any()), never());
}
- assertEquals(renamed, backend.get(renamed.nameIdentifier(), renamed.type()));
+ SemanticModelEntity loaded = backend.get(renamed.nameIdentifier(), renamed.type());
+ assertEquals(renamed.fields(), loaded.fields());
+ assertEquals(3, loaded.revision());
assertEquals(
- 2, service().getSemanticModelPOByIdentifier(renamed.nameIdentifier()).getCurrentVersion());
- assertEquals(2, count("semantic_model_version_info", original.id()));
+ 3, service().getSemanticModelPOByIdentifier(renamed.nameIdentifier()).getCurrentVersion());
+ assertEquals(3, count("semantic_model_version_info", original.id()));
assertEquals(initial, liveIds(original.id()));
assertEquals(4, count("semantic_model_metric_meta", original.id()));
@@ -130,7 +134,7 @@ public class TestSemanticModelMetricIdentities extends TestJDBCBackend {
}
@TestTemplate
- void testUnchangedMetricsSkipIdentityReconciliation() throws Exception {
+ void testUnchangedMetricsKeepTheirIdentities() throws Exception {
Namespace namespace = parents();
SemanticModelEntity original = model(namespace, "sales", "revenue");
backend.insert(original, false);
@@ -138,13 +142,9 @@ public class TestSemanticModelMetricIdentities extends TestJDBCBackend {
SemanticModelEntity replacement =
copy(original, original.id(), original.name(), original.definition().metrics());
- try (MockedStatic<SessionUtils> sessions = mockStatic(SessionUtils.class, CALLS_REAL_METHODS)) {
- backend.update(original.nameIdentifier(), original.type(), old -> replacement);
- sessions.verify(
- () -> SessionUtils.doWithoutCommit(eq(SemanticModelMetricMapper.class), any()), never());
- }
-
- assertEquals(replacement, backend.get(replacement.nameIdentifier(), replacement.type()));
+ backend.update(original.nameIdentifier(), original.type(), old -> replacement);
+ SemanticModelEntity loaded = backend.get(replacement.nameIdentifier(), replacement.type());
+ assertEquals(replacement.fields(), loaded.fields());
assertEquals(
2,
service().getSemanticModelPOByIdentifier(replacement.nameIdentifier()).getCurrentVersion());
@@ -190,7 +190,8 @@ public class TestSemanticModelMetricIdentities extends TestJDBCBackend {
assertTrue(liveIds(original.id()).isEmpty());
assertEquals(2, count("semantic_model_metric_meta", original.id()));
- assertEquals(empty, backend.get(original.nameIdentifier(), original.type()));
+ SemanticModelEntity loaded = backend.get(original.nameIdentifier(), original.type());
+ assertEquals(empty.fields(), loaded.fields());
assertEquals(
4, service().getSemanticModelPOByIdentifier(original.nameIdentifier()).getCurrentVersion());
}
@@ -361,7 +362,7 @@ public class TestSemanticModelMetricIdentities extends TestJDBCBackend {
}
@TestTemplate
- void testStaleUpdateAndDropLeaveWinningIdentities() throws Exception {
+ void testStaleUpdateKeepsWinningIdentitiesAndDropUsesTheObservedName() throws Exception {
SemanticModelEntity original = model(parents(), "sales", "original", "kept");
backend.insert(original, false);
SemanticModelPO stale = service().getSemanticModelPOByIdentifier(original.nameIdentifier());
@@ -383,13 +384,14 @@ public class TestSemanticModelMetricIdentities extends TestJDBCBackend {
}
return loser;
}));
- assertThrows(
- OptimisticLockException.class,
- () -> service().deleteSemanticModelWithVersion(original.nameIdentifier(), stale));
assertEquals(Set.of("winner", "kept"), liveIds(original.id()).keySet());
assertEquals(keptId, liveIds(original.id()).get("kept"));
assertEquals(3, count("semantic_model_metric_meta", original.id()));
- assertEquals(winner, backend.get(original.nameIdentifier(), original.type()));
+ SemanticModelEntity loaded = backend.get(original.nameIdentifier(), original.type());
+ assertEquals(winner.fields(), loaded.fields());
+ assertEquals(2, loaded.revision());
+ service().deleteObservedSemanticModel(original.nameIdentifier(), stale);
+ assertTrue(liveIds(original.id()).isEmpty());
}
@TestTemplate
@@ -427,7 +429,8 @@ public class TestSemanticModelMetricIdentities extends TestJDBCBackend {
executor.shutdownNow();
}
SemanticModelEntity current = backend.get(original.nameIdentifier(), original.type());
- assertTrue(current.equals(first) || current.equals(second));
+ assertEquals(3, current.revision());
+ assertTrue(current.fields().equals(first.fields()) || current.fields().equals(second.fields()));
assertSnapshotNames(current);
assertEquals(keptId, liveIds(original.id()).get("kept"));
assertEquals(4, count("semantic_model_metric_meta", original.id()));
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSnapshotJoins.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSnapshotJoins.java
new file mode 100644
index 0000000000..d9700625e9
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSnapshotJoins.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.service;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.Test;
+
+class TestSemanticModelSnapshotJoins {
+ private static final Pattern SNAPSHOT_TABLE_REFERENCE =
+ Pattern.compile(
+ "\\bsemantic_model_version_info\\b"
+ + "|\\bSemanticModelVersionInfoMapper\\s*\\.\\s*TABLE_NAME\\b"
+ + "|\\bSemanticModelMetaMapper\\s*\\.\\s*VERSION_TABLE_NAME\\b",
+ Pattern.CASE_INSENSITIVE);
+ private static final Pattern DIRECT_LATEST_JOIN =
+ Pattern.compile(
+ "\\bcurrent_version\\s*=\\s*\\w+\\.version\\b|\\.version\\s*=\\s*\\w+\\.current_version\\b",
+ Pattern.CASE_INSENSITIVE);
+
+ @Test
+ void testSnapshotProvidersSelectRevisionsThroughTheSharedJoin() throws Exception {
+ Path packages = Path.of("src/main/java/org/apache/gravitino/storage/relational/mapper");
+ int checked = 0;
+ try (Stream<Path> files = Files.walk(packages)) {
+ for (Path provider : files.filter(path -> path.toString().endsWith(".java")).toList()) {
+ String source = Files.readString(provider);
+ if (!SNAPSHOT_TABLE_REFERENCE.matcher(source).find()) {
+ continue;
+ }
+ assertFalse(
+ DIRECT_LATEST_JOIN.matcher(source).find(),
+ () -> "Select revision joins through snapshotJoin in " + provider);
+ checked++;
+ }
+ }
+ assertTrue(checked > 1);
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceAssociations.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceAssociations.java
index 07634e026a..e799c7cf97 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceAssociations.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceAssociations.java
@@ -106,7 +106,7 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {
}
@TestTemplate
- void testReplaceEntireSetAndRetirePreviousRows() throws Exception {
+ void testReplaceEntireSetAndClosePreviousRanges() throws Exception {
SemanticModelEntity original = model("staff", source.id(), "employee", "manager");
backend.insert(original, false);
Set<Long> initialIds = liveIds(original.id());
@@ -117,9 +117,10 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {
old -> copy(original, "staff", changed.definition(), changed.sourceUpdate()));
assertEquals(Set.of("manager", "renamed", "added"), datasetNames(original.id()));
assertTrue(liveIds(original.id()).stream().noneMatch(initialIds::contains));
- List<Association> retired =
- rows(original.id()).stream().filter(row -> row.deletedAt() > 0).toList();
- assertEquals(2, retired.size());
+ List<Association> closed =
+ rows(original.id()).stream().filter(row -> row.toVersion() == 2).toList();
+ assertEquals(2, closed.size());
+ assertTrue(closed.stream().allMatch(row -> row.fromVersion() == 1 && row.deletedAt() == 0));
SemanticModelEntity reordered = model("staff", source.id(), "added", "renamed", "manager");
backend.update(
@@ -127,7 +128,7 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {
original.type(),
old -> copy(original, "staff", reordered.definition(), reordered.sourceUpdate()));
assertEquals(Set.of("manager", "renamed", "added"), datasetNames(original.id()));
- assertTrue(rows(original.id()).containsAll(retired));
+ assertTrue(rows(original.id()).containsAll(closed));
assertEquals(8, rows(original.id()).size());
assertEquals(
3, service().getSemanticModelPOByIdentifier(original.nameIdentifier()).getCurrentVersion());
@@ -141,11 +142,17 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {
assertTrue(backend.delete(source.nameIdentifier(), source.type(), false));
TableEntity replacement = createAndInsertTableEntity(sourceNamespace, source.name());
assertNotEquals(source.id(), replacement.id());
+ SemanticModelEntity updated =
+ copy(
+ original, original.name(), original.definition(), SemanticModelSourceUpdate.preserve());
+ backend.update(original.nameIdentifier(), original.type(), old -> updated);
SemanticModelEntity renamed =
- copy(original, "renamed", original.definition(), SemanticModelSourceUpdate.preserve());
- backend.update(original.nameIdentifier(), original.type(), old -> renamed);
+ copy(updated, "renamed", updated.definition(), SemanticModelSourceUpdate.preserve());
+ backend.update(updated.nameIdentifier(), updated.type(), old -> renamed);
assertEquals(initial, rows(original.id()));
- assertEquals(renamed, service().getSemanticModelByIdentifier(renamed.nameIdentifier()));
+ SemanticModelEntity loaded = service().getSemanticModelByIdentifier(renamed.nameIdentifier());
+ assertEquals(renamed.fields(), loaded.fields());
+ assertEquals(3, loaded.revision());
SemanticModelSourceUpdate rebound =
SemanticModelSourceUpdate.replace(
@@ -156,7 +163,8 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {
old -> copy(renamed, renamed.name(), renamed.definition(), rebound));
assertEquals(Set.copyOf(rebound.sources()), sourceSet(original.id()));
assertEquals(2, rows(original.id()).size());
- assertTrue(rows(original.id()).get(0).deletedAt() > 0);
+ assertEquals(4, rows(original.id()).get(0).toVersion());
+ assertEquals(0, rows(original.id()).get(0).deletedAt());
}
@TestTemplate
@@ -171,7 +179,9 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {
copy(original, original.name(), changedDefinition, SemanticModelSourceUpdate.preserve());
backend.update(original.nameIdentifier(), original.type(), old -> changed);
- assertEquals(changed, service().getSemanticModelByIdentifier(original.nameIdentifier()));
+ SemanticModelEntity loaded = service().getSemanticModelByIdentifier(original.nameIdentifier());
+ assertEquals(changed.fields(), loaded.fields());
+ assertEquals(2, loaded.revision());
assertEquals(initial, rows(original.id()));
assertEquals(2, snapshotCount(original.id()));
}
@@ -252,7 +262,7 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {
old ->
copy(
original,
- "renamed",
+ original.name(),
original.definition(),
SemanticModelSourceUpdate.replace(sources))));
assertTrue(
@@ -399,12 +409,13 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {
old ->
copy(original, original.name(), replacement.definition(), replacement.sourceUpdate()));
List<Association> current = live(original.id());
+ assertEquals(0, service().deleteSemanticModelMetasByLegacyTimeline(Long.MAX_VALUE, 100));
+ assertEquals(1, service().deleteSemanticModelVersionsByRetentionCount(1L, 100));
execute("UPDATE semantic_model_source_rel SET deleted_at = 10 WHERE deleted_at > 0");
assertEquals(0, service().deleteSemanticModelMetasByLegacyTimeline(10L, 1));
assertEquals(1, service().deleteSemanticModelMetasByLegacyTimeline(11L, 1));
assertEquals(2, rows(original.id()).size());
assertEquals(1, service().deleteSemanticModelMetasByLegacyTimeline(11L, 1));
- assertEquals(1, service().deleteSemanticModelVersionsByRetentionCount(1L, 100));
service().deleteSemanticModelMetasByLegacyTimeline(Long.MAX_VALUE, 100);
assertEquals(current, rows(original.id()));
assertEquals(1, snapshotCount(original.id()));
@@ -474,7 +485,7 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {
session
.getConnection()
.prepareStatement(
- "SELECT id, metalake_id, dataset_name, source_type, source_id, deleted_at"
+ "SELECT id, metalake_id, dataset_name, source_type, source_id, deleted_at, from_version, to_version"
+ " FROM semantic_model_source_rel WHERE semantic_model_id = ? ORDER BY id")) {
statement.setLong(1, modelId);
try (ResultSet result = statement.executeQuery()) {
@@ -487,7 +498,9 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {
result.getString(3),
result.getString(4),
result.getLong(5),
- result.getLong(6)));
+ result.getLong(6),
+ result.getInt(7),
+ result.getInt(8)));
}
return rows;
}
@@ -495,7 +508,9 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {
}
private List<Association> live(long modelId) throws Exception {
- return rows(modelId).stream().filter(row -> row.deletedAt() == 0).toList();
+ return rows(modelId).stream()
+ .filter(row -> row.deletedAt() == 0 && row.toVersion() == 0)
+ .toList();
}
private Set<Long> liveIds(long modelId) throws Exception {
@@ -585,5 +600,7 @@ public class TestSemanticModelSourceAssociations extends TestJDBCBackend {
String datasetName,
String sourceType,
long sourceId,
- long deletedAt) {}
+ long deletedAt,
+ int fromVersion,
+ int toVersion) {}
}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceService.java
index a90ed65c01..4cdb4607f3 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceService.java
@@ -112,6 +112,7 @@ public class TestSemanticModelSourceService extends TestJDBCBackend {
mapper.insertSources(
metalakeId,
first.id(),
+ 1,
List.of(new SemanticModelSource("employee", source.type(), source.id()))));
Map<Long, List<String>> found =
lookup(source.nameIdentifier(), source.type()).stream()
@@ -198,9 +199,17 @@ public class TestSemanticModelSourceService extends TestJDBCBackend {
TableEntity renamed =
createTableEntity(source.id(), sourceNamespace, "employees_v2", AUDIT_INFO);
backend.update(source.nameIdentifier(), source.type(), old -> renamed);
- SemanticModelEntity renamedModel =
+ SemanticModelEntity updated =
copy(
original,
+ original.name(),
+ original.definition(),
+ SemanticModelSourceUpdate.preserve(),
+ original.id());
+ backend.update(original.nameIdentifier(), original.type(), old -> updated);
+ SemanticModelEntity renamedModel =
+ copy(
+ updated,
"staff_v2",
original.definition(),
SemanticModelSourceUpdate.preserve(),
diff --git a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
index f12b9da0d1..c5980a84b2 100644
--- a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
+++ b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
@@ -36,6 +36,7 @@ import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_JDBC_BACKEND_WAIT_M
import static org.apache.gravitino.Configs.ENTITY_RELATIONAL_STORE;
import static org.apache.gravitino.Configs.ENTITY_STORE;
import static org.apache.gravitino.Configs.RELATIONAL_ENTITY_STORE;
+import static org.apache.gravitino.Configs.SEMANTIC_MODEL_VERSION_RETENTION_COUNT;
import static org.apache.gravitino.Configs.STORE_DELETE_AFTER_TIME;
import static org.apache.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
import static org.apache.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;
@@ -251,6 +252,7 @@ public class TestTagManager {
Mockito.when(config.get(ENTITY_CHANGE_LOG_RETENTION_SECS)).thenReturn(24 * 60 * 60L);
Mockito.when(config.get(ENTITY_CHANGE_LOG_CLEANUP_INTERVAL_SECS)).thenReturn(60 * 60L);
Mockito.when(config.get(VERSION_RETENTION_COUNT)).thenReturn(1L);
+ Mockito.when(config.get(SEMANTIC_MODEL_VERSION_RETENTION_COUNT)).thenReturn(100L);
// Fix cache config for test
Mockito.when(config.get(Configs.CACHE_ENABLED)).thenReturn(true);
Mockito.when(config.get(Configs.CACHE_MAX_ENTRIES)).thenReturn(10_000);
diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sql
index eb3bd04c66..b64f3ba8e8 100644
--- a/scripts/h2/schema-2.0.0-h2.sql
+++ b/scripts/h2/schema-2.0.0-h2.sql
@@ -589,6 +589,7 @@ CREATE TABLE IF NOT EXISTS `semantic_model_meta` (
`schema_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'schema id',
`audit_info` CLOB NOT NULL COMMENT 'semantic model identity audit info',
`current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'current version',
+ `active_version` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT 'published revision, 0 if none',
`last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'last allocated version',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'semantic model deleted at',
PRIMARY KEY (`semantic_model_id`),
@@ -604,7 +605,9 @@ CREATE TABLE IF NOT EXISTS `semantic_model_version_info` (
`schema_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'schema id',
`semantic_model_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'semantic model id',
`version` INT UNSIGNED NOT NULL COMMENT 'semantic model version',
- `semantic_model_name` VARCHAR(128) NOT NULL COMMENT 'semantic model name snapshot',
+ `publication_status` VARCHAR(32) NOT NULL DEFAULT 'DRAFT' COMMENT 'publication status of the revision',
+ `published_by` VARCHAR(128) NOT NULL DEFAULT '' COMMENT 'publishing principal, empty for a draft',
+ `published_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'publication time in epoch millis, 0 for a draft',
`semantic_model_comment` CLOB DEFAULT NULL COMMENT 'semantic model comment snapshot',
`datasets` CLOB NOT NULL COMMENT 'dataset definitions snapshot (JSON)',
`relationships` CLOB DEFAULT NULL COMMENT 'relationship definitions snapshot (JSON)',
@@ -794,12 +797,14 @@ CREATE TABLE IF NOT EXISTS `semantic_model_source_rel` (
`id` BIGINT AUTO_INCREMENT COMMENT 'auto increment id',
`metalake_id` BIGINT NOT NULL COMMENT 'containing metalake id',
`semantic_model_id` BIGINT NOT NULL COMMENT 'containing semantic model id',
- `dataset_name` CLOB NOT NULL COMMENT 'exact dataset name in the current definition',
+ `dataset_name` CLOB NOT NULL COMMENT 'exact dataset name in the associated revisions',
`source_type` VARCHAR(64) NOT NULL COMMENT 'TABLE or VIEW',
`source_id` BIGINT NOT NULL COMMENT 'resolved source object id',
+ `from_version` INT UNSIGNED NOT NULL COMMENT 'first revision containing this association',
+ `to_version` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT 'first revision without it, 0 if open',
`deleted_at` BIGINT NOT NULL DEFAULT 0 COMMENT 'association retired at',
PRIMARY KEY (`id`)
-) COMMENT='current semantic model dataset source associations';
+) COMMENT='versioned semantic model dataset source associations';
CREATE INDEX IF NOT EXISTS `idx_smsr_model` ON `semantic_model_source_rel` (`semantic_model_id`, `deleted_at`);
CREATE INDEX IF NOT EXISTS `idx_smsr_source` ON `semantic_model_source_rel` (`metalake_id`, `source_type`, `source_id`, `deleted_at`);
CREATE INDEX IF NOT EXISTS `idx_smsr_deleted_at` ON `semantic_model_source_rel` (`deleted_at`);
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 a2fc064ad1..a01f377f9f 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
@@ -104,6 +104,7 @@ CREATE TABLE IF NOT EXISTS `semantic_model_meta` (
`schema_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'schema id',
`audit_info` CLOB NOT NULL COMMENT 'semantic model identity audit info',
`current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'current version',
+ `active_version` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT 'published revision, 0 if none',
`last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'last allocated version',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'semantic model deleted at',
PRIMARY KEY (`semantic_model_id`),
@@ -119,7 +120,9 @@ CREATE TABLE IF NOT EXISTS `semantic_model_version_info` (
`schema_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'schema id',
`semantic_model_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'semantic model id',
`version` INT UNSIGNED NOT NULL COMMENT 'semantic model version',
- `semantic_model_name` VARCHAR(128) NOT NULL COMMENT 'semantic model name snapshot',
+ `publication_status` VARCHAR(32) NOT NULL DEFAULT 'DRAFT' COMMENT 'publication status of the revision',
+ `published_by` VARCHAR(128) NOT NULL DEFAULT '' COMMENT 'publishing principal, empty for a draft',
+ `published_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'publication time in epoch millis, 0 for a draft',
`semantic_model_comment` CLOB DEFAULT NULL COMMENT 'semantic model comment snapshot',
`datasets` CLOB NOT NULL COMMENT 'dataset definitions snapshot (JSON)',
`relationships` CLOB DEFAULT NULL COMMENT 'relationship definitions snapshot (JSON)',
@@ -264,12 +267,14 @@ CREATE TABLE IF NOT EXISTS `semantic_model_source_rel` (
`id` BIGINT AUTO_INCREMENT COMMENT 'auto increment id',
`metalake_id` BIGINT NOT NULL COMMENT 'containing metalake id',
`semantic_model_id` BIGINT NOT NULL COMMENT 'containing semantic model id',
- `dataset_name` CLOB NOT NULL COMMENT 'exact dataset name in the current definition',
+ `dataset_name` CLOB NOT NULL COMMENT 'exact dataset name in the associated revisions',
`source_type` VARCHAR(64) NOT NULL COMMENT 'TABLE or VIEW',
`source_id` BIGINT NOT NULL COMMENT 'resolved source object id',
+ `from_version` INT UNSIGNED NOT NULL COMMENT 'first revision containing this association',
+ `to_version` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT 'first revision without it, 0 if open',
`deleted_at` BIGINT NOT NULL DEFAULT 0 COMMENT 'association retired at',
PRIMARY KEY (`id`)
-) COMMENT='current semantic model dataset source associations';
+) COMMENT='versioned semantic model dataset source associations';
CREATE INDEX IF NOT EXISTS `idx_smsr_model` ON `semantic_model_source_rel` (`semantic_model_id`, `deleted_at`);
CREATE INDEX IF NOT EXISTS `idx_smsr_source` ON `semantic_model_source_rel` (`metalake_id`, `source_type`, `source_id`, `deleted_at`);
CREATE INDEX IF NOT EXISTS `idx_smsr_deleted_at` ON `semantic_model_source_rel` (`deleted_at`);
diff --git a/scripts/mysql/schema-2.0.0-mysql.sql b/scripts/mysql/schema-2.0.0-mysql.sql
index ec56f314a5..3403c8c1b4 100644
--- a/scripts/mysql/schema-2.0.0-mysql.sql
+++ b/scripts/mysql/schema-2.0.0-mysql.sql
@@ -580,6 +580,7 @@ CREATE TABLE IF NOT EXISTS `semantic_model_meta` (
`schema_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'schema id',
`audit_info` MEDIUMTEXT NOT NULL COMMENT 'semantic model identity audit info',
`current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'current version',
+ `active_version` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT 'published revision, 0 if none',
`last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'last allocated version',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'semantic model deleted at',
PRIMARY KEY (`semantic_model_id`),
@@ -595,7 +596,9 @@ CREATE TABLE IF NOT EXISTS `semantic_model_version_info` (
`schema_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'schema id',
`semantic_model_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'semantic model id',
`version` INT UNSIGNED NOT NULL COMMENT 'semantic model version',
- `semantic_model_name` VARCHAR(128) NOT NULL COMMENT 'semantic model name snapshot',
+ `publication_status` VARCHAR(32) NOT NULL DEFAULT 'DRAFT' COMMENT 'publication status of the revision',
+ `published_by` VARCHAR(128) NOT NULL DEFAULT '' COMMENT 'publishing principal, empty for a draft',
+ `published_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'publication time in epoch millis, 0 for a draft',
`semantic_model_comment` TEXT DEFAULT NULL COMMENT 'semantic model comment snapshot',
`datasets` MEDIUMTEXT NOT NULL COMMENT 'dataset definitions snapshot (JSON)',
`relationships` MEDIUMTEXT DEFAULT NULL COMMENT 'relationship definitions snapshot (JSON)',
@@ -781,16 +784,18 @@ CREATE TABLE IF NOT EXISTS `semantic_model_source_rel` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',
`metalake_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'containing metalake id',
`semantic_model_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'containing semantic model id',
- `dataset_name` MEDIUMTEXT NOT NULL COMMENT 'exact dataset name in the current definition',
+ `dataset_name` MEDIUMTEXT NOT NULL COMMENT 'exact dataset name in the associated revisions',
`source_type` VARCHAR(64) NOT NULL COMMENT 'TABLE or VIEW',
`source_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'resolved source object id',
+ `from_version` INT UNSIGNED NOT NULL COMMENT 'first revision containing this association',
+ `to_version` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT 'first revision without it, 0 if open',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'association retired at',
PRIMARY KEY (`id`),
KEY `idx_smsr_model` (`semantic_model_id`, `deleted_at`),
KEY `idx_smsr_source` (`metalake_id`, `source_type`, `source_id`, `deleted_at`),
KEY `idx_smsr_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
- COMMENT 'current semantic model dataset source associations';
+ COMMENT 'versioned semantic model dataset source associations';
CREATE TABLE IF NOT EXISTS `domain_meta` (
`domain_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'domain id',
diff --git a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql
index eb74441695..2f6e568c68 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
@@ -587,6 +587,7 @@ CREATE TABLE IF NOT EXISTS `semantic_model_meta` (
`schema_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'schema id',
`audit_info` MEDIUMTEXT NOT NULL COMMENT 'semantic model identity audit info',
`current_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'current version',
+ `active_version` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT 'published revision, 0 if none',
`last_version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT 'last allocated version',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'semantic model deleted at',
PRIMARY KEY (`semantic_model_id`),
@@ -602,7 +603,9 @@ CREATE TABLE IF NOT EXISTS `semantic_model_version_info` (
`schema_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'schema id',
`semantic_model_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'semantic model id',
`version` INT UNSIGNED NOT NULL COMMENT 'semantic model version',
- `semantic_model_name` VARCHAR(128) NOT NULL COMMENT 'semantic model name snapshot',
+ `publication_status` VARCHAR(32) NOT NULL DEFAULT 'DRAFT' COMMENT 'publication status of the revision',
+ `published_by` VARCHAR(128) NOT NULL DEFAULT '' COMMENT 'publishing principal, empty for a draft',
+ `published_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'publication time in epoch millis, 0 for a draft',
`semantic_model_comment` TEXT DEFAULT NULL COMMENT 'semantic model comment snapshot',
`datasets` MEDIUMTEXT NOT NULL COMMENT 'dataset definitions snapshot (JSON)',
`relationships` MEDIUMTEXT DEFAULT NULL COMMENT 'relationship definitions snapshot (JSON)',
@@ -765,16 +768,18 @@ CREATE TABLE IF NOT EXISTS `semantic_model_source_rel` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',
`metalake_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'containing metalake id',
`semantic_model_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'containing semantic model id',
- `dataset_name` MEDIUMTEXT NOT NULL COMMENT 'exact dataset name in the current definition',
+ `dataset_name` MEDIUMTEXT NOT NULL COMMENT 'exact dataset name in the associated revisions',
`source_type` VARCHAR(64) NOT NULL COMMENT 'TABLE or VIEW',
`source_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'resolved source object id',
+ `from_version` INT UNSIGNED NOT NULL COMMENT 'first revision containing this association',
+ `to_version` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT 'first revision without it, 0 if open',
`deleted_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'association retired at',
PRIMARY KEY (`id`),
KEY `idx_smsr_model` (`semantic_model_id`, `deleted_at`),
KEY `idx_smsr_source` (`metalake_id`, `source_type`, `source_id`, `deleted_at`),
KEY `idx_smsr_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
- COMMENT 'current semantic model dataset source associations';
+ COMMENT 'versioned semantic model dataset source associations';
-- Clear governance attached to retired external registrations before their IDs can be reused.
-- A retry must preserve relationships attached to a new active registration of the same ID.
diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql b/scripts/postgresql/schema-2.0.0-postgresql.sql
index 1d4ead2b16..94df6f911b 100644
--- a/scripts/postgresql/schema-2.0.0-postgresql.sql
+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql
@@ -1017,6 +1017,7 @@ CREATE TABLE IF NOT EXISTS semantic_model_meta (
schema_id BIGINT NOT NULL,
audit_info TEXT NOT NULL,
current_version INT NOT NULL DEFAULT 1,
+ active_version INT NOT NULL DEFAULT 0,
last_version INT NOT NULL DEFAULT 1,
deleted_at BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (semantic_model_id),
@@ -1034,6 +1035,7 @@ COMMENT ON COLUMN semantic_model_meta.catalog_id IS 'catalog id';
COMMENT ON COLUMN semantic_model_meta.schema_id IS 'schema id';
COMMENT ON COLUMN semantic_model_meta.audit_info IS 'semantic model identity audit info';
COMMENT ON COLUMN semantic_model_meta.current_version IS 'current version';
+COMMENT ON COLUMN semantic_model_meta.active_version IS 'published revision, 0 if none';
COMMENT ON COLUMN semantic_model_meta.last_version IS 'last allocated version';
COMMENT ON COLUMN semantic_model_meta.deleted_at IS 'semantic model deleted at';
@@ -1044,7 +1046,9 @@ CREATE TABLE IF NOT EXISTS semantic_model_version_info (
schema_id BIGINT NOT NULL,
semantic_model_id BIGINT NOT NULL,
version INT NOT NULL,
- semantic_model_name VARCHAR(128) NOT NULL,
+ publication_status VARCHAR(32) NOT NULL DEFAULT 'DRAFT',
+ published_by VARCHAR(128) NOT NULL DEFAULT '',
+ published_at BIGINT NOT NULL DEFAULT 0,
semantic_model_comment TEXT DEFAULT NULL,
datasets TEXT NOT NULL,
relationships TEXT DEFAULT NULL,
@@ -1069,7 +1073,9 @@ COMMENT ON COLUMN semantic_model_version_info.catalog_id IS 'catalog id';
COMMENT ON COLUMN semantic_model_version_info.schema_id IS 'schema id';
COMMENT ON COLUMN semantic_model_version_info.semantic_model_id IS 'semantic model id';
COMMENT ON COLUMN semantic_model_version_info.version IS 'semantic model version';
-COMMENT ON COLUMN semantic_model_version_info.semantic_model_name IS 'semantic model name snapshot';
+COMMENT ON COLUMN semantic_model_version_info.publication_status IS 'publication status of the revision';
+COMMENT ON COLUMN semantic_model_version_info.published_by IS 'publishing principal, empty for a draft';
+COMMENT ON COLUMN semantic_model_version_info.published_at IS 'publication time in epoch millis, 0 for a draft';
COMMENT ON COLUMN semantic_model_version_info.semantic_model_comment IS 'semantic model comment snapshot';
COMMENT ON COLUMN semantic_model_version_info.datasets IS 'dataset definitions snapshot (JSON)';
COMMENT ON COLUMN semantic_model_version_info.relationships IS 'relationship definitions snapshot (JSON)';
@@ -1355,18 +1361,22 @@ CREATE TABLE IF NOT EXISTS semantic_model_source_rel (
dataset_name TEXT NOT NULL,
source_type VARCHAR(64) NOT NULL,
source_id BIGINT NOT NULL,
+ from_version INT NOT NULL,
+ to_version INT NOT NULL DEFAULT 0,
deleted_at BIGINT NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_smsr_model ON semantic_model_source_rel (semantic_model_id, deleted_at);
CREATE INDEX IF NOT EXISTS idx_smsr_source ON semantic_model_source_rel (metalake_id, source_type, source_id, deleted_at);
CREATE INDEX IF NOT EXISTS idx_smsr_deleted_at ON semantic_model_source_rel (deleted_at);
-COMMENT ON TABLE semantic_model_source_rel IS 'current semantic model dataset source associations';
+COMMENT ON TABLE semantic_model_source_rel IS 'versioned semantic model dataset source associations';
COMMENT ON COLUMN semantic_model_source_rel.id IS 'auto increment id';
COMMENT ON COLUMN semantic_model_source_rel.metalake_id IS 'containing metalake id';
COMMENT ON COLUMN semantic_model_source_rel.semantic_model_id IS 'containing semantic model id';
-COMMENT ON COLUMN semantic_model_source_rel.dataset_name IS 'exact dataset name in the current definition';
+COMMENT ON COLUMN semantic_model_source_rel.dataset_name IS 'exact dataset name in the associated revisions';
COMMENT ON COLUMN semantic_model_source_rel.source_type IS 'TABLE or VIEW';
COMMENT ON COLUMN semantic_model_source_rel.source_id IS 'resolved source object id';
+COMMENT ON COLUMN semantic_model_source_rel.from_version IS 'first revision containing this association';
+COMMENT ON COLUMN semantic_model_source_rel.to_version IS 'first revision without it, 0 if open';
COMMENT ON COLUMN semantic_model_source_rel.deleted_at IS 'association retired at';
CREATE TABLE IF NOT EXISTS domain_meta (
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 c25371856b..b29b9719b1 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
@@ -118,6 +118,7 @@ CREATE TABLE IF NOT EXISTS semantic_model_meta (
schema_id BIGINT NOT NULL,
audit_info TEXT NOT NULL,
current_version INT NOT NULL DEFAULT 1,
+ active_version INT NOT NULL DEFAULT 0,
last_version INT NOT NULL DEFAULT 1,
deleted_at BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (semantic_model_id),
@@ -135,6 +136,7 @@ COMMENT ON COLUMN semantic_model_meta.catalog_id IS 'catalog id';
COMMENT ON COLUMN semantic_model_meta.schema_id IS 'schema id';
COMMENT ON COLUMN semantic_model_meta.audit_info IS 'semantic model identity audit info';
COMMENT ON COLUMN semantic_model_meta.current_version IS 'current version';
+COMMENT ON COLUMN semantic_model_meta.active_version IS 'published revision, 0 if none';
COMMENT ON COLUMN semantic_model_meta.last_version IS 'last allocated version';
COMMENT ON COLUMN semantic_model_meta.deleted_at IS 'semantic model deleted at';
@@ -145,7 +147,9 @@ CREATE TABLE IF NOT EXISTS semantic_model_version_info (
schema_id BIGINT NOT NULL,
semantic_model_id BIGINT NOT NULL,
version INT NOT NULL,
- semantic_model_name VARCHAR(128) NOT NULL,
+ publication_status VARCHAR(32) NOT NULL DEFAULT 'DRAFT',
+ published_by VARCHAR(128) NOT NULL DEFAULT '',
+ published_at BIGINT NOT NULL DEFAULT 0,
semantic_model_comment TEXT DEFAULT NULL,
datasets TEXT NOT NULL,
relationships TEXT DEFAULT NULL,
@@ -170,7 +174,9 @@ COMMENT ON COLUMN semantic_model_version_info.catalog_id IS 'catalog id';
COMMENT ON COLUMN semantic_model_version_info.schema_id IS 'schema id';
COMMENT ON COLUMN semantic_model_version_info.semantic_model_id IS 'semantic model id';
COMMENT ON COLUMN semantic_model_version_info.version IS 'semantic model version';
-COMMENT ON COLUMN semantic_model_version_info.semantic_model_name IS 'semantic model name snapshot';
+COMMENT ON COLUMN semantic_model_version_info.publication_status IS 'publication status of the revision';
+COMMENT ON COLUMN semantic_model_version_info.published_by IS 'publishing principal, empty for a draft';
+COMMENT ON COLUMN semantic_model_version_info.published_at IS 'publication time in epoch millis, 0 for a draft';
COMMENT ON COLUMN semantic_model_version_info.semantic_model_comment IS 'semantic model comment snapshot';
COMMENT ON COLUMN semantic_model_version_info.datasets IS 'dataset definitions snapshot (JSON)';
COMMENT ON COLUMN semantic_model_version_info.relationships IS 'relationship definitions snapshot (JSON)';
@@ -371,18 +377,22 @@ CREATE TABLE IF NOT EXISTS semantic_model_source_rel (
dataset_name TEXT NOT NULL,
source_type VARCHAR(64) NOT NULL,
source_id BIGINT NOT NULL,
+ from_version INT NOT NULL,
+ to_version INT NOT NULL DEFAULT 0,
deleted_at BIGINT NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_smsr_model ON semantic_model_source_rel (semantic_model_id, deleted_at);
CREATE INDEX IF NOT EXISTS idx_smsr_source ON semantic_model_source_rel (metalake_id, source_type, source_id, deleted_at);
CREATE INDEX IF NOT EXISTS idx_smsr_deleted_at ON semantic_model_source_rel (deleted_at);
-COMMENT ON TABLE semantic_model_source_rel IS 'current semantic model dataset source associations';
+COMMENT ON TABLE semantic_model_source_rel IS 'versioned semantic model dataset source associations';
COMMENT ON COLUMN semantic_model_source_rel.id IS 'auto increment id';
COMMENT ON COLUMN semantic_model_source_rel.metalake_id IS 'containing metalake id';
COMMENT ON COLUMN semantic_model_source_rel.semantic_model_id IS 'containing semantic model id';
-COMMENT ON COLUMN semantic_model_source_rel.dataset_name IS 'exact dataset name in the current definition';
+COMMENT ON COLUMN semantic_model_source_rel.dataset_name IS 'exact dataset name in the associated revisions';
COMMENT ON COLUMN semantic_model_source_rel.source_type IS 'TABLE or VIEW';
COMMENT ON COLUMN semantic_model_source_rel.source_id IS 'resolved source object id';
+COMMENT ON COLUMN semantic_model_source_rel.from_version IS 'first revision containing this association';
+COMMENT ON COLUMN semantic_model_source_rel.to_version IS 'first revision without it, 0 if open';
COMMENT ON COLUMN semantic_model_source_rel.deleted_at IS 'association retired at';
-- Clear governance attached to retired external registrations before their IDs can be reused.