Skip to content

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

[#14683] feat(core): Maintain source associations on Semantic Model writes (#14684)

mchades537d31d54317
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 0ee792b161..477a1e191b 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/ManagedSemanticModelOperations.java
@@ -41,15 +41,15 @@ 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.SemanticModelCatalog;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.semantic.SemanticModelMetric;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.utils.PrincipalUtils;
/** EntityStore-backed operations for Gravitino-managed Semantic Models. */
-public class ManagedSemanticModelOperations implements SemanticModelCatalog {
+public class ManagedSemanticModelOperations {
private final EntityStore store;
private final IdGenerator idGenerator;
@@ -74,7 +74,13 @@ public class ManagedSemanticModelOperations implements SemanticModelCatalog {
this.writeValidator = writeValidator;
}
- @Override
+ /**
+ * Lists current model identifiers.
+ *
+ * @param namespace The schema namespace.
+ * @return The model identifiers in the schema.
+ * @throws NoSuchSchemaException If the schema does not exist.
+ */
public NameIdentifier[] listSemanticModels(Namespace namespace) throws NoSuchSchemaException {
try {
List<SemanticModelEntity> models =
@@ -89,7 +95,13 @@ public class ManagedSemanticModelOperations implements SemanticModelCatalog {
}
}
- @Override
+ /**
+ * Lists metric identifiers in structured name order.
+ *
+ * @param namespace The schema namespace.
+ * @return Metric identifiers ordered by model identifier and case-sensitive metric name.
+ * @throws NoSuchSchemaException If the schema does not exist.
+ */
public NameIdentifier[] listMetrics(Namespace namespace) throws NoSuchSchemaException {
try {
return store.listSemanticModelMetrics(namespace).stream()
@@ -106,7 +118,13 @@ public class ManagedSemanticModelOperations implements SemanticModelCatalog {
}
}
- @Override
+ /**
+ * Lists complete metrics in structured name order.
+ *
+ * @param namespace The schema namespace.
+ * @return Metrics ordered by model identifier and case-sensitive metric name.
+ * @throws NoSuchSchemaException If the schema does not exist.
+ */
public SemanticModelMetric[] listMetricInfos(Namespace namespace) throws NoSuchSchemaException {
try {
return store.listSemanticModelMetricInfos(namespace).stream()
@@ -123,7 +141,13 @@ public class ManagedSemanticModelOperations implements SemanticModelCatalog {
}
}
- @Override
+ /**
+ * Loads a current model.
+ *
+ * @param ident The model identifier.
+ * @return The loaded model.
+ * @throws NoSuchSemanticModelException If the model does not exist.
+ */
public SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException {
try {
return store.get(ident, Entity.EntityType.SEMANTIC_MODEL, SemanticModelEntity.class);
@@ -134,17 +158,33 @@ public class ManagedSemanticModelOperations implements SemanticModelCatalog {
}
}
- @Override
+ /**
+ * Creates a model with its validated source associations.
+ *
+ * @param ident The model identifier.
+ * @param comment The model comment, or {@code null}.
+ * @param definition The complete model definition.
+ * @param properties The model properties.
+ * @param sourceUpdate The resolved associations for every dataset in the definition.
+ * @return The created model.
+ * @throws NoSuchSchemaException If the schema does not exist.
+ * @throws SemanticModelAlreadyExistsException If the model already exists.
+ * @throws IllegalSemanticModelException If the definition is invalid.
+ */
public SemanticModel createSemanticModel(
NameIdentifier ident,
@Nullable String comment,
SemanticModelDefinition definition,
- Map<String, String> properties)
+ Map<String, String> properties,
+ SemanticModelSourceUpdate sourceUpdate)
throws NoSuchSchemaException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException {
Preconditions.checkArgument(properties != null, "Properties must not be null");
+ Preconditions.checkArgument(
+ sourceUpdate.replacesSources(), "Creation requires resolved source associations");
writeValidator.accept(ident, definition);
+ sourceUpdate.validate(definition);
Instant now = Instant.now();
SemanticModelEntity entity =
@@ -154,6 +194,7 @@ public class ManagedSemanticModelOperations implements SemanticModelCatalog {
.withNamespace(ident.namespace())
.withComment(comment)
.withDefinition(definition)
+ .withSourceUpdate(sourceUpdate)
.withProperties(properties)
.withAuditInfo(
AuditInfo.builder()
@@ -174,11 +215,25 @@ public class ManagedSemanticModelOperations implements SemanticModelCatalog {
}
}
- @Override
- public SemanticModel alterSemanticModel(NameIdentifier ident, SemanticModelChange... changes)
+ /**
+ * Applies model changes and source association updates atomically.
+ *
+ * @param ident The model identifier.
+ * @param sourceUpdate A replacement set for definition writes, or preserve for metadata changes.
+ * @param changes The ordered changes to apply.
+ * @return The updated model.
+ * @throws NoSuchSemanticModelException If the model does not exist.
+ * @throws SemanticModelAlreadyExistsException If a rename conflicts with an existing model.
+ * @throws IllegalSemanticModelException If the changes or resulting definition are invalid.
+ */
+ public SemanticModel alterSemanticModel(
+ NameIdentifier ident, SemanticModelSourceUpdate sourceUpdate, SemanticModelChange... changes)
throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException {
boolean validateForWrite = requiresWriteValidation(changes);
+ Preconditions.checkArgument(
+ validateForWrite == sourceUpdate.replacesSources(),
+ "Definition replacement must replace sources; metadata-only changes must preserve sources");
try {
return store.update(
@@ -186,12 +241,13 @@ public class ManagedSemanticModelOperations implements SemanticModelCatalog {
SemanticModelEntity.class,
Entity.EntityType.SEMANTIC_MODEL,
oldEntity -> {
- SemanticModelEntity candidate = applyChanges(oldEntity, changes);
+ SemanticModelEntity candidate = applyChanges(oldEntity, sourceUpdate, changes);
if (validateForWrite) {
writeValidator.accept(
NameIdentifier.of(candidate.namespace(), candidate.name()),
candidate.definition());
}
+ sourceUpdate.validate(candidate.definition());
return candidate;
});
} catch (NoSuchEntityException e) {
@@ -204,7 +260,12 @@ public class ManagedSemanticModelOperations implements SemanticModelCatalog {
}
}
- @Override
+ /**
+ * Deletes a model and retires its source associations.
+ *
+ * @param ident The model identifier.
+ * @return Whether the model was deleted.
+ */
public boolean dropSemanticModel(NameIdentifier ident) {
try {
return store.delete(ident, Entity.EntityType.SEMANTIC_MODEL);
@@ -242,7 +303,9 @@ public class ManagedSemanticModelOperations implements SemanticModelCatalog {
}
private static SemanticModelEntity applyChanges(
- SemanticModelEntity oldEntity, SemanticModelChange[] changes) {
+ SemanticModelEntity oldEntity,
+ SemanticModelSourceUpdate sourceUpdate,
+ SemanticModelChange[] changes) {
String newName = oldEntity.name();
String newComment = oldEntity.comment();
Map<String, String> newProperties = new HashMap<>(oldEntity.properties());
@@ -270,6 +333,7 @@ public class ManagedSemanticModelOperations implements SemanticModelCatalog {
.withNamespace(oldEntity.namespace())
.withComment(newComment)
.withDefinition(newDefinition)
+ .withSourceUpdate(sourceUpdate)
.withProperties(newProperties)
.withAuditInfo(
AuditInfo.builder()
diff --git a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java
index 70f35bba18..2836f0bd89 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java
@@ -18,9 +18,10 @@
*/
package org.apache.gravitino.catalog;
+import com.google.common.base.Preconditions;
import java.util.Map;
import java.util.Objects;
-import java.util.function.Consumer;
+import java.util.function.Function;
import javax.annotation.Nullable;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
@@ -36,6 +37,7 @@ import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.semantic.SemanticModelMetric;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
/** Dispatches schema-scoped Semantic Model operations through the server pipeline. */
public interface SemanticModelDispatcher {
@@ -98,6 +100,7 @@ public interface SemanticModelDispatcher {
* @param comment The Semantic Model comment, or {@code null} if it has no comment.
* @param definition The complete Semantic Model definition.
* @param properties The Gravitino-specific Semantic Model properties.
+ * @param sourceUpdate The validated complete dataset source associations.
* @return The created Semantic Model.
* @throws NoSuchSchemaException If the schema does not exist.
* @throws SemanticModelAlreadyExistsException If the Semantic Model already exists.
@@ -107,7 +110,8 @@ public interface SemanticModelDispatcher {
NameIdentifier ident,
@Nullable String comment,
SemanticModelDefinition definition,
- Map<String, String> properties)
+ Map<String, String> properties,
+ SemanticModelSourceUpdate sourceUpdate)
throws NoSuchSchemaException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException;
@@ -120,28 +124,32 @@ public interface SemanticModelDispatcher {
*
* @param namespace The destination schema namespace.
* @param document The document to import.
- * @param sourceValidator The required caller-specific source validator.
+ * @param sourceValidator The required caller-specific source validator, which must return a
+ * non-null source update.
* @return The imported Semantic Model.
+ * @throws IllegalArgumentException If the source validator returns {@code null}.
*/
default SemanticModel importOssieDocument(
Namespace namespace,
OssieDocument document,
- Consumer<SemanticModelDefinition> sourceValidator) {
+ Function<SemanticModelDefinition, SemanticModelSourceUpdate> sourceValidator) {
Objects.requireNonNull(sourceValidator, "sourceValidator must not be null");
ParsedSemanticModel model = OssieDocumentConverter.importDocument(document);
- sourceValidator.accept(model.definition());
+ SemanticModelSourceUpdate sourceUpdate = sourceValidator.apply(model.definition());
+ Preconditions.checkArgument(sourceUpdate != null, "sourceValidator must not return null");
return importSemanticModel(
NameIdentifier.of(namespace, model.name()),
model.comment(),
model.definition(),
- model.properties());
+ model.properties(),
+ sourceUpdate);
}
/**
* Dispatches a parsed import through normalization and import-specific hooks.
*
* <p>This internal entry point is used by {@link #importOssieDocument(Namespace, OssieDocument,
- * Consumer)} after parsing and source validation. Each decorator implements it separately from
+ * Function)} after parsing and source validation. Each decorator implements it separately from
* create; only the operation dispatcher reuses the underlying create implementation. The
* top-level event dispatcher rejects direct calls to this internal entry point.
*
@@ -149,6 +157,7 @@ public interface SemanticModelDispatcher {
* @param comment The model comment, or {@code null} if it has no comment.
* @param definition The parsed native definition whose sources have been validated.
* @param properties The Gravitino-specific model properties.
+ * @param sourceUpdate The validated complete dataset source associations.
* @return The imported Semantic Model.
* @throws UnsupportedOperationException If called directly on the top-level event dispatcher.
*/
@@ -156,7 +165,8 @@ public interface SemanticModelDispatcher {
NameIdentifier ident,
@Nullable String comment,
SemanticModelDefinition definition,
- Map<String, String> properties);
+ Map<String, String> properties,
+ SemanticModelSourceUpdate sourceUpdate);
/**
* Exports a Semantic Model as a standalone Apache Ossie document.
@@ -176,6 +186,8 @@ public interface SemanticModelDispatcher {
* Applies changes atomically to a Semantic Model.
*
* @param ident The Semantic Model identifier.
+ * @param sourceUpdate Replace associations for a definition write, or preserve them for metadata
+ * changes.
* @param changes The changes to apply.
* @return The altered Semantic Model.
* @throws NoSuchSemanticModelException If the Semantic Model does not exist.
@@ -183,7 +195,8 @@ public interface SemanticModelDispatcher {
* Model.
* @throws IllegalSemanticModelException If a change or the resulting Semantic Model is invalid.
*/
- SemanticModel alterSemanticModel(NameIdentifier ident, SemanticModelChange... changes)
+ SemanticModel alterSemanticModel(
+ NameIdentifier ident, SemanticModelSourceUpdate sourceUpdate, SemanticModelChange... changes)
throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException;
diff --git a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java
index efad41cba1..8866f80ab3 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java
@@ -40,6 +40,7 @@ import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.semantic.SemanticModelMetric;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
/** Normalizes Semantic Model parents while retaining Gravitino-owned model naming rules. */
public class SemanticModelNormalizeDispatcher implements SemanticModelDispatcher {
@@ -89,11 +90,12 @@ public class SemanticModelNormalizeDispatcher implements SemanticModelDispatcher
NameIdentifier ident,
@Nullable String comment,
SemanticModelDefinition definition,
- Map<String, String> properties)
+ Map<String, String> properties,
+ SemanticModelSourceUpdate sourceUpdate)
throws NoSuchSchemaException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException {
return dispatcher.createSemanticModel(
- normalizeForCreate(ident), comment, definition, properties);
+ normalizeForCreate(ident), comment, definition, properties, sourceUpdate);
}
@Override
@@ -101,9 +103,10 @@ public class SemanticModelNormalizeDispatcher implements SemanticModelDispatcher
NameIdentifier ident,
@Nullable String comment,
SemanticModelDefinition definition,
- Map<String, String> properties) {
+ Map<String, String> properties,
+ SemanticModelSourceUpdate sourceUpdate) {
return dispatcher.importSemanticModel(
- normalizeForCreate(ident), comment, definition, properties);
+ normalizeForCreate(ident), comment, definition, properties, sourceUpdate);
}
@Override
@@ -112,14 +115,16 @@ public class SemanticModelNormalizeDispatcher implements SemanticModelDispatcher
}
@Override
- public SemanticModel alterSemanticModel(NameIdentifier ident, SemanticModelChange... changes)
+ public SemanticModel alterSemanticModel(
+ NameIdentifier ident, SemanticModelSourceUpdate sourceUpdate, SemanticModelChange... changes)
throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException {
Preconditions.checkArgument(
changes != null && changes.length > 0, "At least one change is required");
SemanticModelChange[] normalizedChanges =
Arrays.stream(changes).map(this::normalizeChange).toArray(SemanticModelChange[]::new);
- return dispatcher.alterSemanticModel(normalizeForLookup(ident), normalizedChanges);
+ return dispatcher.alterSemanticModel(
+ normalizeForLookup(ident), sourceUpdate, normalizedChanges);
}
@Override
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 1457751a06..ed6918d834 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java
@@ -43,6 +43,7 @@ import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.semantic.SemanticModelMetric;
import org.apache.gravitino.semantic.SemanticModelPropertiesMetadata;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.storage.IdGenerator;
/** Dispatches always-managed Semantic Model operations to Gravitino's EntityStore. */
@@ -117,7 +118,8 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher
NameIdentifier ident,
@Nullable String comment,
SemanticModelDefinition definition,
- Map<String, String> properties)
+ Map<String, String> properties,
+ SemanticModelSourceUpdate sourceUpdate)
throws NoSuchSchemaException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException {
Preconditions.checkArgument(properties != null, "Properties must not be null");
@@ -130,7 +132,8 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher
checkRelationalCatalog(ident.namespace());
NameIdentifier schemaIdent = schemaIdentifier(ident);
schemaDispatcher.loadSchema(schemaIdent);
- return managedOperations.createSemanticModel(ident, comment, definition, effectiveProperties);
+ return managedOperations.createSemanticModel(
+ ident, comment, definition, effectiveProperties, sourceUpdate);
}
@Override
@@ -138,8 +141,9 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher
NameIdentifier ident,
@Nullable String comment,
SemanticModelDefinition definition,
- Map<String, String> properties) {
- return createSemanticModel(ident, comment, definition, properties);
+ Map<String, String> properties,
+ SemanticModelSourceUpdate sourceUpdate) {
+ return createSemanticModel(ident, comment, definition, properties, sourceUpdate);
}
/** {@inheritDoc} */
@@ -149,7 +153,8 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher
}
@Override
- public SemanticModel alterSemanticModel(NameIdentifier ident, SemanticModelChange... changes)
+ public SemanticModel alterSemanticModel(
+ NameIdentifier ident, SemanticModelSourceUpdate sourceUpdate, SemanticModelChange... changes)
throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException {
if (changes == null || changes.length == 0) {
@@ -161,7 +166,7 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher
if (!schemaDispatcher.schemaExists(schemaIdent)) {
throw new NoSuchSemanticModelException("Semantic Model %s does not exist", ident);
}
- return managedOperations.alterSemanticModel(ident, changes);
+ return managedOperations.alterSemanticModel(ident, sourceUpdate, changes);
}
@Override
diff --git a/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.java
index 7cc805b223..f69b58c1d6 100644
--- a/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.java
@@ -39,6 +39,7 @@ import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.semantic.SemanticModelMetric;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.PrincipalUtils;
@@ -94,11 +95,12 @@ public class SemanticModelHookDispatcher implements SemanticModelDispatcher {
NameIdentifier ident,
@Nullable String comment,
SemanticModelDefinition definition,
- Map<String, String> properties)
+ Map<String, String> properties,
+ SemanticModelSourceUpdate sourceUpdate)
throws NoSuchSchemaException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException {
SemanticModel semanticModel =
- dispatcher.createSemanticModel(ident, comment, definition, properties);
+ dispatcher.createSemanticModel(ident, comment, definition, properties, sourceUpdate);
setCreatorAsOwner(ident);
return semanticModel;
}
@@ -108,9 +110,10 @@ public class SemanticModelHookDispatcher implements SemanticModelDispatcher {
NameIdentifier ident,
@Nullable String comment,
SemanticModelDefinition definition,
- Map<String, String> properties) {
+ Map<String, String> properties,
+ SemanticModelSourceUpdate sourceUpdate) {
SemanticModel semanticModel =
- dispatcher.importSemanticModel(ident, comment, definition, properties);
+ dispatcher.importSemanticModel(ident, comment, definition, properties, sourceUpdate);
setCreatorAsOwner(ident);
return semanticModel;
}
@@ -121,10 +124,11 @@ public class SemanticModelHookDispatcher implements SemanticModelDispatcher {
}
@Override
- public SemanticModel alterSemanticModel(NameIdentifier ident, SemanticModelChange... changes)
+ public SemanticModel alterSemanticModel(
+ NameIdentifier ident, SemanticModelSourceUpdate sourceUpdate, SemanticModelChange... changes)
throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException {
- SemanticModel model = dispatcher.alterSemanticModel(ident, changes);
+ SemanticModel model = dispatcher.alterSemanticModel(ident, sourceUpdate, changes);
for (SemanticModelChange change : changes) {
if (change instanceof SemanticModelChange.RenameSemanticModel) {
AuthorizationUtils.notifyEntityNameIdMappingChange(ident, Entity.EntityType.SEMANTIC_MODEL);
diff --git a/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.java b/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.java
index 71caf9c974..9de6ffd2a9 100644
--- a/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.java
@@ -20,7 +20,7 @@
package org.apache.gravitino.listener;
import java.util.Map;
-import java.util.function.Consumer;
+import java.util.function.Function;
import javax.annotation.Nullable;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
@@ -64,6 +64,7 @@ import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.semantic.SemanticModelMetric;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.utils.PrincipalUtils;
/**
@@ -159,7 +160,8 @@ public class SemanticModelEventDispatcher implements SemanticModelDispatcher {
NameIdentifier ident,
@Nullable String comment,
SemanticModelDefinition definition,
- Map<String, String> properties)
+ Map<String, String> properties,
+ SemanticModelSourceUpdate sourceUpdate)
throws NoSuchSchemaException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException {
String user = PrincipalUtils.getCurrentUserName();
@@ -168,7 +170,7 @@ public class SemanticModelEventDispatcher implements SemanticModelDispatcher {
eventBus.dispatchEvent(new CreateSemanticModelPreEvent(user, ident, createRequest));
try {
SemanticModel semanticModel =
- dispatcher.createSemanticModel(ident, comment, definition, properties);
+ dispatcher.createSemanticModel(ident, comment, definition, properties, sourceUpdate);
eventBus.dispatchEvent(
new CreateSemanticModelEvent(user, ident, new SemanticModelInfo(semanticModel)));
return semanticModel;
@@ -182,7 +184,7 @@ public class SemanticModelEventDispatcher implements SemanticModelDispatcher {
public SemanticModel importOssieDocument(
Namespace namespace,
OssieDocument document,
- Consumer<SemanticModelDefinition> sourceValidator) {
+ Function<SemanticModelDefinition, SemanticModelSourceUpdate> sourceValidator) {
String user = PrincipalUtils.getCurrentUserName();
OssieFormat format = document == null ? null : document.format();
try {
@@ -207,7 +209,8 @@ public class SemanticModelEventDispatcher implements SemanticModelDispatcher {
NameIdentifier ident,
@Nullable String comment,
SemanticModelDefinition definition,
- Map<String, String> properties) {
+ Map<String, String> properties,
+ SemanticModelSourceUpdate sourceUpdate) {
throw new UnsupportedOperationException(
"Parsed imports are internal; use importOssieDocument with a source validator");
}
@@ -227,13 +230,14 @@ public class SemanticModelEventDispatcher implements SemanticModelDispatcher {
}
@Override
- public SemanticModel alterSemanticModel(NameIdentifier ident, SemanticModelChange... changes)
+ public SemanticModel alterSemanticModel(
+ NameIdentifier ident, SemanticModelSourceUpdate sourceUpdate, SemanticModelChange... changes)
throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,
IllegalSemanticModelException {
String user = PrincipalUtils.getCurrentUserName();
eventBus.dispatchEvent(new AlterSemanticModelPreEvent(user, ident, changes));
try {
- SemanticModel semanticModel = dispatcher.alterSemanticModel(ident, changes);
+ SemanticModel semanticModel = dispatcher.alterSemanticModel(ident, sourceUpdate, changes);
eventBus.dispatchEvent(
new AlterSemanticModelEvent(user, ident, changes, new SemanticModelInfo(semanticModel)));
return semanticModel;
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperations.java b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperations.java
index 0f2745bd03..7d8f9f6444 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperations.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperations.java
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.catalog;
+import static org.apache.gravitino.semantic.SemanticModelTestUtils.sources;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
@@ -35,6 +36,7 @@ import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.io.IOException;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
@@ -56,6 +58,7 @@ import org.apache.gravitino.semantic.Dataset;
import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.storage.IdGenerator;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.storage.memory.TestMemoryEntityStore.InMemoryEntityStore;
@@ -76,7 +79,11 @@ public class TestManagedSemanticModelOperations {
SemanticModel created =
operations.createSemanticModel(
- IDENT, "Sales model", definition("orders"), Map.of("domain", "sales"));
+ IDENT,
+ "Sales model",
+ definition("orders"),
+ Map.of("domain", "sales"),
+ sources(definition("orders")));
SemanticModel loaded = operations.loadSemanticModel(IDENT);
assertSame(created, loaded);
@@ -100,13 +107,43 @@ public class TestManagedSemanticModelOperations {
SemanticModelDefinition definition = definition("orders");
SemanticModel created =
- operations.createSemanticModel(IDENT, null, definition, Map.of("key", "value"));
+ operations.createSemanticModel(
+ IDENT, null, definition, Map.of("key", "value"), sources(definition));
InOrder order = inOrder(writeValidator, idGenerator, store);
order.verify(writeValidator).accept(IDENT, definition);
order.verify(idGenerator).nextId();
order.verify(store).put(any(SemanticModelEntity.class), eq(false));
assertEquals(7L, ((SemanticModelEntity) created).id());
+ assertEquals(sources(definition), ((SemanticModelEntity) created).sourceUpdate());
+ }
+
+ @Test
+ public void testAssociationNamesMustMatchTheDefinitionBeforePersistence() {
+ InMemoryEntityStore store = new InMemoryEntityStore();
+ ManagedSemanticModelOperations operations =
+ new ManagedSemanticModelOperations(
+ store, RandomIdGenerator.INSTANCE, (ident, definition) -> {});
+ SemanticModelDefinition definition = definition("orders");
+ SemanticModelSourceUpdate missing = SemanticModelSourceUpdate.replace(List.of());
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> operations.createSemanticModel(IDENT, null, definition, Map.of(), missing));
+ assertThrows(NoSuchSemanticModelException.class, () -> operations.loadSemanticModel(IDENT));
+
+ SemanticModel original =
+ operations.createSemanticModel(
+ IDENT, "Original", definition, Map.of(), sources(definition));
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ operations.alterSemanticModel(
+ IDENT,
+ missing,
+ SemanticModelChange.updateComment("Must not persist"),
+ SemanticModelChange.replaceDefinition(definition)));
+ assertSame(original, operations.loadSemanticModel(IDENT));
}
@Test
@@ -125,7 +162,9 @@ public class TestManagedSemanticModelOperations {
failure,
assertThrows(
IllegalSemanticModelException.class,
- () -> operations.createSemanticModel(IDENT, null, definition("orders"), Map.of())));
+ () ->
+ operations.createSemanticModel(
+ IDENT, null, definition("orders"), Map.of(), sources(definition("orders")))));
verifyNoInteractions(idGenerator, store);
}
@@ -188,15 +227,21 @@ public class TestManagedSemanticModelOperations {
(ident, definition) -> writeValidationCount.incrementAndGet());
SemanticModel first =
operations.createSemanticModel(
- IDENT, "Original", definition("orders"), Map.of("domain", "sales"));
+ IDENT,
+ "Original",
+ definition("orders"),
+ Map.of("domain", "sales"),
+ sources(definition("orders")));
NameIdentifier secondIdent = NameIdentifier.of(NAMESPACE, "inventory_model");
- operations.createSemanticModel(secondIdent, null, definition("inventory"), Map.of());
+ operations.createSemanticModel(
+ secondIdent, null, definition("inventory"), Map.of(), sources(definition("inventory")));
NameIdentifier renamedIdent = NameIdentifier.of(NAMESPACE, "renamed_sales_model");
SemanticModelDefinition replacement = definition("invoices");
SemanticModel altered =
operations.alterSemanticModel(
IDENT,
+ sources(replacement),
SemanticModelChange.rename(renamedIdent.name()),
SemanticModelChange.updateComment("Updated"),
SemanticModelChange.setProperty("tier", "gold"),
@@ -238,14 +283,22 @@ public class TestManagedSemanticModelOperations {
throw sourceFailure;
}
});
- operations.createSemanticModel(IDENT, "Original", definition("orders"), Map.of());
-
- operations.alterSemanticModel(IDENT, SemanticModelChange.setProperty("owner", "analytics"));
- operations.alterSemanticModel(IDENT, SemanticModelChange.updateComment("Comment only"));
+ operations.createSemanticModel(
+ IDENT, "Original", definition("orders"), Map.of(), sources(definition("orders")));
+
+ operations.alterSemanticModel(
+ IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.setProperty("owner", "analytics"));
+ operations.alterSemanticModel(
+ IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.updateComment("Comment only"));
assertEquals(1, writeValidationCount.get());
SemanticModelDefinition accepted = definition("accepted");
- operations.alterSemanticModel(IDENT, SemanticModelChange.replaceDefinition(accepted));
+ operations.alterSemanticModel(
+ IDENT, sources(accepted), SemanticModelChange.replaceDefinition(accepted));
assertEquals(2, writeValidationCount.get());
SemanticModelDefinition duplicateDatasets =
@@ -256,7 +309,9 @@ public class TestManagedSemanticModelOperations {
IllegalSemanticModelException.class,
() ->
operations.alterSemanticModel(
- IDENT, SemanticModelChange.replaceDefinition(duplicateDatasets)));
+ IDENT,
+ sources(duplicateDatasets),
+ SemanticModelChange.replaceDefinition(duplicateDatasets)));
assertEquals(2, writeValidationCount.get());
assertEquals(accepted, operations.loadSemanticModel(IDENT).definition());
@@ -266,7 +321,9 @@ public class TestManagedSemanticModelOperations {
IllegalSemanticModelException.class,
() ->
operations.alterSemanticModel(
- IDENT, SemanticModelChange.replaceDefinition(definition("blocked")))));
+ IDENT,
+ sources(definition("blocked")),
+ SemanticModelChange.replaceDefinition(definition("blocked")))));
assertEquals(3, writeValidationCount.get());
assertEquals(accepted, operations.loadSemanticModel(IDENT).definition());
}
@@ -285,29 +342,38 @@ public class TestManagedSemanticModelOperations {
IDENT,
"Initial comment",
definition("orders"),
- Map.of("overwrite", "old", "remove", "present"));
+ Map.of("overwrite", "old", "remove", "present"),
+ sources(definition("orders")));
SemanticModel propertyUpdated =
- operations.alterSemanticModel(IDENT, SemanticModelChange.setProperty("overwrite", "new"));
+ operations.alterSemanticModel(
+ IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.setProperty("overwrite", "new"));
assertEquals(Map.of("overwrite", "new", "remove", "present"), propertyUpdated.properties());
assertCreationAuditPreserved(original, propertyUpdated);
SemanticModel propertiesRemoved =
operations.alterSemanticModel(
IDENT,
+ SemanticModelSourceUpdate.preserve(),
SemanticModelChange.removeProperty("remove"),
SemanticModelChange.removeProperty("absent"));
assertEquals(Map.of("overwrite", "new"), propertiesRemoved.properties());
assertCreationAuditPreserved(original, propertiesRemoved);
SemanticModel commentRemoved =
- operations.alterSemanticModel(IDENT, SemanticModelChange.updateComment(null));
+ operations.alterSemanticModel(
+ IDENT, SemanticModelSourceUpdate.preserve(), SemanticModelChange.updateComment(null));
assertNull(commentRemoved.comment());
assertCreationAuditPreserved(original, commentRemoved);
NameIdentifier renamedIdent = NameIdentifier.of(NAMESPACE, "individually_renamed");
SemanticModel renamed =
- operations.alterSemanticModel(IDENT, SemanticModelChange.rename(renamedIdent.name()));
+ operations.alterSemanticModel(
+ IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.rename(renamedIdent.name()));
assertEquals(renamedIdent.name(), renamed.name());
assertEquals(((SemanticModelEntity) original).id(), ((SemanticModelEntity) renamed).id());
assertCreationAuditPreserved(original, renamed);
@@ -330,13 +396,15 @@ public class TestManagedSemanticModelOperations {
validatedIdent.set(ident);
validatedDefinition.set(definition);
});
- operations.createSemanticModel(IDENT, "Original", definition("orders"), Map.of());
+ operations.createSemanticModel(
+ IDENT, "Original", definition("orders"), Map.of(), sources(definition("orders")));
SemanticModelDefinition replacement = definition("invoices");
NameIdentifier renamedIdent = NameIdentifier.of(NAMESPACE, "validated_after_replace");
SemanticModel altered =
operations.alterSemanticModel(
IDENT,
+ sources(replacement),
SemanticModelChange.replaceDefinition(replacement),
SemanticModelChange.setProperty("owner", "analytics"),
SemanticModelChange.updateComment("Updated after replacement"),
@@ -357,13 +425,15 @@ public class TestManagedSemanticModelOperations {
new ManagedSemanticModelOperations(
store, new RandomIdGenerator(), (ident, definition) -> {});
SemanticModel original =
- operations.createSemanticModel(IDENT, null, definition("orders"), Map.of("key", "old"));
+ operations.createSemanticModel(
+ IDENT, null, definition("orders"), Map.of("key", "old"), sources(definition("orders")));
assertThrows(
IllegalSemanticModelException.class,
() ->
operations.alterSemanticModel(
IDENT,
+ SemanticModelSourceUpdate.preserve(),
SemanticModelChange.setProperty("key", "must-not-persist"),
(SemanticModelChange) null));
@@ -382,16 +452,25 @@ public class TestManagedSemanticModelOperations {
new ManagedSemanticModelOperations(store, new RandomIdGenerator(), writeValidator);
SemanticModel propertyUpdated =
- operations.alterSemanticModel(IDENT, SemanticModelChange.setProperty("safe", "true"));
+ operations.alterSemanticModel(
+ IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.setProperty("safe", "true"));
assertEquals(Map.of("safe", "true"), propertyUpdated.properties());
SemanticModel commentUpdated =
- operations.alterSemanticModel(IDENT, SemanticModelChange.updateComment("Metadata only"));
+ operations.alterSemanticModel(
+ IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.updateComment("Metadata only"));
assertEquals("Metadata only", commentUpdated.comment());
NameIdentifier renamedIdent = NameIdentifier.of(NAMESPACE, "metadata_only_rename");
SemanticModel renamed =
- operations.alterSemanticModel(IDENT, SemanticModelChange.rename(renamedIdent.name()));
+ operations.alterSemanticModel(
+ IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.rename(renamedIdent.name()));
assertEquals(renamedIdent.name(), renamed.name());
assertEquals(malformedDefinition, renamed.definition());
assertThrows(NoSuchSemanticModelException.class, () -> operations.loadSemanticModel(IDENT));
@@ -409,14 +488,22 @@ public class TestManagedSemanticModelOperations {
assertThrows(
IllegalSemanticModelException.class,
- () -> operations.alterSemanticModel(IDENT, (SemanticModelChange[]) null));
- assertThrows(IllegalSemanticModelException.class, () -> operations.alterSemanticModel(IDENT));
+ () ->
+ operations.alterSemanticModel(
+ IDENT, SemanticModelSourceUpdate.preserve(), (SemanticModelChange[]) null));
assertThrows(
IllegalSemanticModelException.class,
- () -> operations.alterSemanticModel(IDENT, (SemanticModelChange) null));
+ () -> operations.alterSemanticModel(IDENT, SemanticModelSourceUpdate.preserve()));
assertThrows(
IllegalSemanticModelException.class,
- () -> operations.alterSemanticModel(IDENT, unsupported));
+ () ->
+ operations.alterSemanticModel(
+ IDENT, SemanticModelSourceUpdate.preserve(), (SemanticModelChange) null));
+ assertThrows(
+ IllegalSemanticModelException.class,
+ () ->
+ operations.alterSemanticModel(
+ IDENT, SemanticModelSourceUpdate.preserve(), unsupported));
verifyNoInteractions(store);
}
@@ -446,14 +533,21 @@ public class TestManagedSemanticModelOperations {
assertThrows(
NoSuchSemanticModelException.class,
() ->
- operations.alterSemanticModel(IDENT, SemanticModelChange.setProperty("key", "value")));
+ operations.alterSemanticModel(
+ IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.setProperty("key", "value")));
doThrow(new EntityAlreadyExistsException("Rename conflict"))
.when(store)
.update(
eq(IDENT), eq(SemanticModelEntity.class), eq(Entity.EntityType.SEMANTIC_MODEL), any());
assertThrows(
SemanticModelAlreadyExistsException.class,
- () -> operations.alterSemanticModel(IDENT, SemanticModelChange.rename("conflict")));
+ () ->
+ operations.alterSemanticModel(
+ IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.rename("conflict")));
IOException updateFailure = new IOException("Update failed");
doThrow(updateFailure)
.when(store)
@@ -464,7 +558,10 @@ public class TestManagedSemanticModelOperations {
assertThrows(
RuntimeException.class,
() ->
- operations.alterSemanticModel(IDENT, SemanticModelChange.removeProperty("key")))
+ operations.alterSemanticModel(
+ IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.removeProperty("key")))
.getCause());
when(store.delete(IDENT, Entity.EntityType.SEMANTIC_MODEL))
@@ -487,7 +584,9 @@ public class TestManagedSemanticModelOperations {
RuntimeException thrown =
assertThrows(
RuntimeException.class,
- () -> operations.createSemanticModel(IDENT, null, definition("orders"), Map.of()));
+ () ->
+ operations.createSemanticModel(
+ IDENT, null, definition("orders"), Map.of(), sources(definition("orders"))));
assertInstanceOf(expectedType, thrown);
return thrown;
}
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 01871a9d1b..4c684a9a39 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestManagedSemanticModelOperationsJDBC.java
@@ -18,15 +18,21 @@
*/
package org.apache.gravitino.catalog;
+import static org.apache.gravitino.semantic.SemanticModelTestUtils.sources;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.reflect.FieldUtils;
@@ -39,6 +45,8 @@ import org.apache.gravitino.Namespace;
import org.apache.gravitino.cache.NoOpsCache;
import org.apache.gravitino.exceptions.IllegalSemanticModelException;
import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.semantic.CustomExtension;
import org.apache.gravitino.semantic.Dataset;
import org.apache.gravitino.semantic.Metric;
@@ -46,10 +54,14 @@ import org.apache.gravitino.semantic.Relationship;
import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelSource;
+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.session.SqlSessionFactoryHelper;
import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
@@ -104,12 +116,16 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {
}
@TestTemplate
- public void testCreateThenLoadRoundTrip() throws IOException {
+ public void testCreateThenLoadRoundTrip() throws Exception {
SemanticModelDefinition definition = definition("orders");
SemanticModel created =
operations.createSemanticModel(
- modelIdent, "Persisted model", definition, Map.of("domain", "sales"));
+ modelIdent,
+ "Persisted model",
+ definition,
+ Map.of("domain", "sales"),
+ sources(definition));
SemanticModel loaded = operations.loadSemanticModel(modelIdent);
assertNotSame(created, loaded);
@@ -117,19 +133,30 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {
assertEquals(definition, loaded.definition());
assertEquals(1, writeValidationCount.get());
assertTrue(backend.exists(modelIdent, Entity.EntityType.SEMANTIC_MODEL));
+ assertEquals(
+ sources(definition).sources(),
+ liveAssociations(((SemanticModelEntity) created).id()).stream()
+ .map(Association::source)
+ .toList());
+ assertFalse(((SemanticModelEntity) loaded).sourceUpdate().replacesSources());
}
@TestTemplate
- public void testListAlterAndDropRoundTrip() throws IOException {
+ public void testListAlterAndDropRoundTrip() throws Exception {
SemanticModel created =
operations.createSemanticModel(
- modelIdent, "Original", definition("orders"), Map.of("domain", "sales"));
+ modelIdent,
+ "Original",
+ definition("orders"),
+ Map.of("domain", "sales"),
+ sources(definition("orders")));
NameIdentifier renamedIdent = NameIdentifier.of(modelIdent.namespace(), "renamed_sales_model");
SemanticModelDefinition replacement = definition("invoices");
SemanticModel altered =
operations.alterSemanticModel(
modelIdent,
+ sources(replacement),
SemanticModelChange.rename(renamedIdent.name()),
SemanticModelChange.updateComment("Updated"),
SemanticModelChange.removeProperty("domain"),
@@ -150,17 +177,29 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {
assertFalse(backend.exists(modelIdent, Entity.EntityType.SEMANTIC_MODEL));
assertTrue(backend.exists(renamedIdent, Entity.EntityType.SEMANTIC_MODEL));
assertEquals(altered, operations.loadSemanticModel(renamedIdent));
+ long modelId = ((SemanticModelEntity) created).id();
+ assertEquals(
+ sources(replacement).sources(),
+ liveAssociations(modelId).stream().map(Association::source).toList());
assertTrue(operations.dropSemanticModel(renamedIdent));
+ assertTrue(liveAssociations(modelId).isEmpty());
assertFalse(operations.dropSemanticModel(renamedIdent));
}
@TestTemplate
- public void testRejectedAlterIsAtomicAndRenameConflictIsTyped() {
+ public void testRejectedAlterIsAtomicAndRenameConflictIsTyped() throws Exception {
SemanticModel original =
operations.createSemanticModel(
- modelIdent, "Original", definition("orders"), Map.of("owner", "sales"));
+ modelIdent,
+ "Original",
+ definition("orders"),
+ Map.of("owner", "sales"),
+ sources(definition("orders")));
+ List<Association> originalAssociations =
+ liveAssociations(((SemanticModelEntity) original).id());
NameIdentifier existingIdent = NameIdentifier.of(modelIdent.namespace(), "existing_model");
- operations.createSemanticModel(existingIdent, null, definition("customers"), Map.of());
+ operations.createSemanticModel(
+ existingIdent, null, definition("customers"), Map.of(), sources(definition("customers")));
SemanticModelDefinition duplicateDatasets =
SemanticModelDefinition.builder()
.withDatasets(
@@ -174,6 +213,7 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {
() ->
operations.alterSemanticModel(
modelIdent,
+ sources(duplicateDatasets),
SemanticModelChange.updateComment("Must not persist"),
SemanticModelChange.setProperty("owner", "changed"),
SemanticModelChange.replaceDefinition(duplicateDatasets)));
@@ -181,19 +221,171 @@ public class TestManagedSemanticModelOperationsJDBC extends TestJDBCBackend {
SemanticModelAlreadyExistsException.class,
() ->
operations.alterSemanticModel(
- modelIdent, SemanticModelChange.rename(existingIdent.name())));
+ modelIdent,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.rename(existingIdent.name())));
SemanticModel loaded = operations.loadSemanticModel(modelIdent);
assertEquals(original, loaded);
+ assertEquals(originalAssociations, liveAssociations(((SemanticModelEntity) loaded).id()));
assertEquals("existing_model", operations.loadSemanticModel(existingIdent).name());
assertEquals(2, writeValidationCount.get());
}
+ @TestTemplate
+ public void testExplicitRebindingAndMetadataPreservationThroughEntityStore() throws Exception {
+ TableEntity source = createAndInsertTableEntity(modelIdent.namespace(), "orders");
+ SemanticModelDefinition definition =
+ SemanticModelDefinition.builder()
+ .withDatasets(
+ new Dataset[] {
+ Dataset.builder()
+ .withName("orders")
+ .withSource(
+ NameIdentifier.of(
+ modelIdent.namespace().level(1),
+ modelIdent.namespace().level(2),
+ source.name()))
+ .build()
+ })
+ .build();
+ SemanticModelSourceUpdate initial =
+ SemanticModelSourceUpdate.replace(
+ List.of(new SemanticModelSource("orders", Entity.EntityType.TABLE, source.id())));
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ operations.createSemanticModel(
+ modelIdent, null, definition, Map.of(), SemanticModelSourceUpdate.preserve()));
+ SemanticModelEntity created =
+ (SemanticModelEntity)
+ operations.createSemanticModel(modelIdent, null, definition, Map.of(), initial);
+ List<Association> original = liveAssociations(created.id());
+ assertEquals(initial.sources(), original.stream().map(Association::source).toList());
+
+ backend.delete(source.nameIdentifier(), source.type(), false);
+ NameIdentifier renamedIdent = NameIdentifier.of(modelIdent.namespace(), "renamed_model");
+ operations.alterSemanticModel(
+ modelIdent,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.rename(renamedIdent.name()),
+ SemanticModelChange.updateComment("updated after deletion"),
+ SemanticModelChange.setProperty("owner", "analytics"));
+ assertEquals(original, liveAssociations(created.id()));
+ assertEquals(1, writeValidationCount.get());
+
+ TableEntity recreated = createAndInsertTableEntity(modelIdent.namespace(), "orders");
+ SemanticModelSourceUpdate rebound =
+ SemanticModelSourceUpdate.replace(
+ List.of(new SemanticModelSource("orders", Entity.EntityType.TABLE, recreated.id())));
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ operations.alterSemanticModel(
+ renamedIdent,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.replaceDefinition(definition)));
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ operations.alterSemanticModel(
+ renamedIdent, rebound, SemanticModelChange.updateComment("invalid intent")));
+ assertEquals(original, liveAssociations(created.id()));
+
+ // Explicit replacement rebinds the source even though the definition is unchanged.
+ operations.alterSemanticModel(
+ renamedIdent, rebound, SemanticModelChange.replaceDefinition(definition));
+ assertEquals(
+ rebound.sources(),
+ liveAssociations(created.id()).stream().map(Association::source).toList());
+ assertEquals(definition, operations.loadSemanticModel(renamedIdent).definition());
+ assertEquals(2, writeValidationCount.get());
+ }
+
+ /**
+ * Verifies that a replacement retains the resolved source ID if the source is recreated before
+ * the model write.
+ *
+ * @throws Exception if persistence fails
+ */
+ @TestTemplate
+ public void testReplacementRetainsResolvedIdAfterSourceRecreation() throws Exception {
+ TableEntity source = createAndInsertTableEntity(modelIdent.namespace(), "orders");
+ NameIdentifier sourceIdent =
+ NameIdentifier.of(
+ modelIdent.namespace().level(1), modelIdent.namespace().level(2), source.name());
+ SemanticModelDefinition initialDefinition = definition("orders", sourceIdent);
+ SemanticModelEntity created =
+ (SemanticModelEntity)
+ operations.createSemanticModel(
+ modelIdent,
+ null,
+ initialDefinition,
+ Map.of(),
+ SemanticModelSourceUpdate.replace(
+ List.of(
+ new SemanticModelSource("orders", Entity.EntityType.TABLE, source.id()))));
+
+ SemanticModelDefinition replacementDefinition = definition("recent_orders", sourceIdent);
+ SemanticModelSourceUpdate resolvedUpdate =
+ SemanticModelSourceUpdate.replace(
+ List.of(
+ new SemanticModelSource("recent_orders", Entity.EntityType.TABLE, source.id())));
+
+ // Reproduce source recreation after validation has resolved the ID, but before the model write.
+ assertTrue(backend.delete(source.nameIdentifier(), source.type(), false));
+ TableEntity recreated = createAndInsertTableEntity(modelIdent.namespace(), source.name());
+ assertNotEquals(source.id(), recreated.id());
+
+ operations.alterSemanticModel(
+ modelIdent, resolvedUpdate, SemanticModelChange.replaceDefinition(replacementDefinition));
+
+ assertEquals(replacementDefinition, operations.loadSemanticModel(modelIdent).definition());
+ assertEquals(
+ resolvedUpdate.sources(),
+ liveAssociations(created.id()).stream().map(Association::source).toList());
+ assertEquals(2, writeValidationCount.get());
+ }
+
+ private List<Association> liveAssociations(long modelId) throws Exception {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+ PreparedStatement statement =
+ session
+ .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")) {
+ statement.setLong(1, modelId);
+ try (ResultSet result = statement.executeQuery()) {
+ List<Association> rows = new ArrayList<>();
+ while (result.next()) {
+ rows.add(
+ new Association(
+ result.getLong(1),
+ new SemanticModelSource(
+ result.getString(2),
+ Entity.EntityType.valueOf(result.getString(3)),
+ result.getLong(4))));
+ }
+ return rows;
+ }
+ }
+ }
+
+ @SuppressWarnings("UnusedVariable") // Error Prone does not recognize record component accessors.
+ private record Association(long id, SemanticModelSource source) {}
+
private static SemanticModelDefinition definition(String datasetName) {
+ return definition(
+ datasetName, NameIdentifier.of("source_catalog", "source_schema", datasetName));
+ }
+
+ private static SemanticModelDefinition definition(String datasetName, NameIdentifier source) {
Dataset dataset =
Dataset.builder()
.withName(datasetName)
- .withSource(NameIdentifier.of("source_catalog", "source_schema", datasetName))
+ .withSource(source)
.withPrimaryKey(new String[0])
.withUniqueKeys(new String[0][])
.withCustomExtensions(new CustomExtension[0])
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelDispatcher.java
index 96e001c425..b0c09b2e46 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelDispatcher.java
@@ -35,6 +35,7 @@ import org.apache.gravitino.semantic.OssieFormat;
import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelCatalog;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.junit.jupiter.api.Test;
/** Tests the Core Semantic Model dispatcher contract. */
@@ -59,7 +60,8 @@ public class TestSemanticModelDispatcher {
NameIdentifier.class,
String.class,
SemanticModelDefinition.class,
- Map.class)
+ Map.class,
+ SemanticModelSourceUpdate.class)
.isDefault());
}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java
index 911198b435..e2034a33d4 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.catalog;
import static org.apache.gravitino.semantic.OssieVersion.DEFAULT_VERSION;
import static org.apache.gravitino.semantic.SemanticModel.PROPERTY_OSSIE_VERSION;
+import static org.apache.gravitino.semantic.SemanticModelTestUtils.sources;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -47,6 +48,7 @@ import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.semantic.SemanticModelMetric;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -94,7 +96,8 @@ public class TestSemanticModelNormalizeDispatcher {
public void testParentUsesCatalogCapabilityButModelUsesStableRules() {
SemanticModelDefinition definition = definition();
SemanticModel model = mock(SemanticModel.class);
- when(delegate.createSemanticModel(NORMALIZED_IDENT, "comment", definition, Map.of()))
+ when(delegate.createSemanticModel(
+ NORMALIZED_IDENT, "comment", definition, Map.of(), sources(definition)))
.thenReturn(model);
when(delegate.loadSemanticModel(NORMALIZED_IDENT)).thenReturn(model);
when(delegate.semanticModelExists(NORMALIZED_IDENT)).thenReturn(true);
@@ -103,13 +106,17 @@ public class TestSemanticModelNormalizeDispatcher {
when(delegate.dropSemanticModel(NORMALIZED_IDENT)).thenReturn(true);
assertEquals(
- model, dispatcher.createSemanticModel(INPUT_IDENT, "comment", definition, Map.of()));
+ model,
+ dispatcher.createSemanticModel(
+ INPUT_IDENT, "comment", definition, Map.of(), sources(definition)));
assertEquals(model, dispatcher.loadSemanticModel(INPUT_IDENT));
assertTrue(dispatcher.semanticModelExists(INPUT_IDENT));
assertEquals(NORMALIZED_IDENT, dispatcher.listSemanticModels(INPUT_NAMESPACE)[0]);
assertTrue(dispatcher.dropSemanticModel(INPUT_IDENT));
- verify(delegate).createSemanticModel(NORMALIZED_IDENT, "comment", definition, Map.of());
+ verify(delegate)
+ .createSemanticModel(
+ NORMALIZED_IDENT, "comment", definition, Map.of(), sources(definition));
verify(delegate).loadSemanticModel(NORMALIZED_IDENT);
verify(delegate).semanticModelExists(NORMALIZED_IDENT);
verify(delegate).listSemanticModels(NORMALIZED_NAMESPACE);
@@ -120,23 +127,34 @@ public class TestSemanticModelNormalizeDispatcher {
public void testRenameUsesStableSemanticModelRules() {
SemanticModel model = mock(SemanticModel.class);
SemanticModelChange rename = SemanticModelChange.rename("RevenueModel");
- when(delegate.alterSemanticModel(NORMALIZED_IDENT, rename)).thenReturn(model);
+ when(delegate.alterSemanticModel(
+ NORMALIZED_IDENT, SemanticModelSourceUpdate.preserve(), rename))
+ .thenReturn(model);
- assertEquals(model, dispatcher.alterSemanticModel(INPUT_IDENT, rename));
- verify(delegate).alterSemanticModel(NORMALIZED_IDENT, rename);
+ assertEquals(
+ model,
+ dispatcher.alterSemanticModel(INPUT_IDENT, SemanticModelSourceUpdate.preserve(), rename));
+ verify(delegate)
+ .alterSemanticModel(NORMALIZED_IDENT, SemanticModelSourceUpdate.preserve(), rename);
NameIdentifier invalidIdent = NameIdentifier.of(INPUT_NAMESPACE, "invalid model");
assertThrows(
IllegalArgumentException.class,
- () -> dispatcher.createSemanticModel(invalidIdent, null, definition(), Map.of()));
+ () ->
+ dispatcher.createSemanticModel(
+ invalidIdent, null, definition(), Map.of(), sources(definition())));
assertThrows(
IllegalArgumentException.class,
() ->
dispatcher.alterSemanticModel(
- INPUT_IDENT, SemanticModelChange.rename("invalid model")));
+ INPUT_IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.rename("invalid model")));
assertThrows(
IllegalArgumentException.class,
- () -> dispatcher.alterSemanticModel(INPUT_IDENT, new SemanticModelChange[0]));
+ () ->
+ dispatcher.alterSemanticModel(
+ INPUT_IDENT, SemanticModelSourceUpdate.preserve(), new SemanticModelChange[0]));
}
@Test
@@ -144,18 +162,25 @@ public class TestSemanticModelNormalizeDispatcher {
SemanticModel model = mock(SemanticModel.class);
Map<String, String> properties = Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION);
when(delegate.importSemanticModel(
- eq(NORMALIZED_IDENT), isNull(), any(SemanticModelDefinition.class), eq(properties)))
+ eq(NORMALIZED_IDENT),
+ isNull(),
+ any(SemanticModelDefinition.class),
+ eq(properties),
+ any()))
.thenReturn(model);
assertEquals(
model,
dispatcher.importOssieDocument(
- INPUT_NAMESPACE, ossieDocument("SalesModel"), definitionToValidate -> {}));
+ INPUT_NAMESPACE,
+ ossieDocument("SalesModel"),
+ definitionToValidate -> sources(definitionToValidate)));
ArgumentCaptor<SemanticModelDefinition> definition =
ArgumentCaptor.forClass(SemanticModelDefinition.class);
verify(delegate)
- .importSemanticModel(eq(NORMALIZED_IDENT), isNull(), definition.capture(), eq(properties));
+ .importSemanticModel(
+ eq(NORMALIZED_IDENT), isNull(), definition.capture(), eq(properties), any());
assertEquals(definition(), definition.getValue());
verifyNoMoreInteractions(delegate);
}
@@ -166,7 +191,9 @@ public class TestSemanticModelNormalizeDispatcher {
IllegalArgumentException.class,
() ->
dispatcher.importOssieDocument(
- INPUT_NAMESPACE, ossieDocument("invalid model"), definition -> {}));
+ INPUT_NAMESPACE,
+ ossieDocument("invalid model"),
+ definition -> sources(definition)));
verifyNoInteractions(delegate);
}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java
index 59c0eb7f1a..bc80fef2da 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelOperationDispatcher.java
@@ -24,6 +24,7 @@ import static org.apache.gravitino.Configs.TREE_LOCK_MIN_NODE_IN_MEMORY;
import static org.apache.gravitino.semantic.CustomExtension.GRAVITINO_PROPERTIES_VENDOR;
import static org.apache.gravitino.semantic.OssieVersion.DEFAULT_VERSION;
import static org.apache.gravitino.semantic.SemanticModel.PROPERTY_OSSIE_VERSION;
+import static org.apache.gravitino.semantic.SemanticModelTestUtils.sources;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -60,6 +61,7 @@ import org.apache.gravitino.semantic.Relationship;
import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.storage.RandomIdGenerator;
import org.apache.gravitino.storage.memory.TestMemoryEntityStore.InMemoryEntityStore;
import org.junit.jupiter.api.BeforeAll;
@@ -116,7 +118,8 @@ public class TestSemanticModelOperationDispatcher {
@Test
public void testCreateThenLoadWithoutCatalogBackedSourceValidation() {
SemanticModel created =
- dispatcher.createSemanticModel(MODEL_IDENT, "Sales", validDefinition(), Map.of());
+ dispatcher.createSemanticModel(
+ MODEL_IDENT, "Sales", validDefinition(), Map.of(), sources(validDefinition()));
assertEquals("sales_model", created.name());
assertEquals(2, created.definition().datasets().length);
@@ -131,7 +134,8 @@ public class TestSemanticModelOperationDispatcher {
MODEL_IDENT,
"Sales",
validDefinition(),
- Map.of(PROPERTY_OSSIE_VERSION, "future-version"));
+ Map.of(PROPERTY_OSSIE_VERSION, "future-version"),
+ sources(validDefinition()));
assertEquals("future-version", created.properties().get(PROPERTY_OSSIE_VERSION));
}
@@ -142,7 +146,11 @@ public class TestSemanticModelOperationDispatcher {
IllegalArgumentException.class,
() ->
dispatcher.createSemanticModel(
- MODEL_IDENT, null, validDefinition(), Map.of(PROPERTY_OSSIE_VERSION, " ")));
+ MODEL_IDENT,
+ null,
+ validDefinition(),
+ Map.of(PROPERTY_OSSIE_VERSION, " "),
+ sources(validDefinition())));
verify(catalogManager, never()).loadCatalog(METADATA_CATALOG_IDENT);
}
@@ -153,7 +161,11 @@ public class TestSemanticModelOperationDispatcher {
IllegalSemanticModelException.class,
() ->
dispatcher.createSemanticModel(
- MODEL_IDENT, "Sales", definitionWithReservedExtension(), Map.of()));
+ MODEL_IDENT,
+ "Sales",
+ definitionWithReservedExtension(),
+ Map.of(),
+ sources(definitionWithReservedExtension())));
assertTrue(exception.getMessage().contains("reserved for Gravitino properties"));
assertFalse(dispatcher.semanticModelExists(MODEL_IDENT));
@@ -163,7 +175,11 @@ public class TestSemanticModelOperationDispatcher {
public void testReplaceRejectsReservedPropertiesExtensionWithoutPersistingOtherChanges() {
SemanticModel original =
dispatcher.createSemanticModel(
- MODEL_IDENT, "Original", validDefinition(), Map.of("owner", "sales"));
+ MODEL_IDENT,
+ "Original",
+ validDefinition(),
+ Map.of("owner", "sales"),
+ sources(validDefinition()));
IllegalSemanticModelException exception =
assertThrows(
@@ -171,6 +187,7 @@ public class TestSemanticModelOperationDispatcher {
() ->
dispatcher.alterSemanticModel(
MODEL_IDENT,
+ sources(definitionWithReservedExtension()),
SemanticModelChange.updateComment("Must not persist"),
SemanticModelChange.setProperty("owner", "changed"),
SemanticModelChange.replaceDefinition(definitionWithReservedExtension())));
@@ -188,18 +205,26 @@ public class TestSemanticModelOperationDispatcher {
IllegalArgumentException.class,
() ->
dispatcher.alterSemanticModel(
- MODEL_IDENT, SemanticModelChange.setProperty(PROPERTY_OSSIE_VERSION, " ")));
+ MODEL_IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.setProperty(PROPERTY_OSSIE_VERSION, " ")));
verify(catalogManager, never()).loadCatalog(METADATA_CATALOG_IDENT);
}
@Test
public void testAlterCanRemoveOssieVersion() {
dispatcher.createSemanticModel(
- MODEL_IDENT, "Sales", validDefinition(), Map.of(PROPERTY_OSSIE_VERSION, "future-version"));
+ MODEL_IDENT,
+ "Sales",
+ validDefinition(),
+ Map.of(PROPERTY_OSSIE_VERSION, "future-version"),
+ sources(validDefinition()));
SemanticModel altered =
dispatcher.alterSemanticModel(
- MODEL_IDENT, SemanticModelChange.removeProperty(PROPERTY_OSSIE_VERSION));
+ MODEL_IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.removeProperty(PROPERTY_OSSIE_VERSION));
assertFalse(altered.properties().containsKey(PROPERTY_OSSIE_VERSION));
}
@@ -210,7 +235,9 @@ public class TestSemanticModelOperationDispatcher {
.thenThrow(new NoSuchSchemaException("Schema does not exist"));
assertThrows(
NoSuchSchemaException.class,
- () -> dispatcher.createSemanticModel(MODEL_IDENT, null, validDefinition(), Map.of()));
+ () ->
+ dispatcher.createSemanticModel(
+ MODEL_IDENT, null, validDefinition(), Map.of(), sources(validDefinition())));
assertFalse(dispatcher.semanticModelExists(MODEL_IDENT));
}
@@ -227,14 +254,18 @@ public class TestSemanticModelOperationDispatcher {
@Test
public void testListAlterAndDropLifecycleWithDefinitionValidation() {
- dispatcher.createSemanticModel(MODEL_IDENT, "Original", validDefinition(), Map.of());
+ dispatcher.createSemanticModel(
+ MODEL_IDENT, "Original", validDefinition(), Map.of(), sources(validDefinition()));
SemanticModel propertyUpdated =
dispatcher.alterSemanticModel(
- MODEL_IDENT, SemanticModelChange.setProperty("owner", "analytics"));
+ MODEL_IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.setProperty("owner", "analytics"));
SemanticModel renamed =
dispatcher.alterSemanticModel(
MODEL_IDENT,
+ SemanticModelSourceUpdate.preserve(),
SemanticModelChange.rename("renamed_sales_model"),
SemanticModelChange.updateComment("Updated"));
NameIdentifier renamedIdent = NameIdentifier.of(NAMESPACE, renamed.name());
@@ -245,7 +276,9 @@ public class TestSemanticModelOperationDispatcher {
SemanticModel replaced =
dispatcher.alterSemanticModel(
- renamedIdent, SemanticModelChange.replaceDefinition(validDefinition()));
+ renamedIdent,
+ sources(validDefinition()),
+ SemanticModelChange.replaceDefinition(validDefinition()));
assertEquals(2, replaced.definition().datasets().length);
assertArrayEquals(
new NameIdentifier[] {renamedIdent}, dispatcher.listSemanticModels(NAMESPACE));
@@ -257,7 +290,11 @@ public class TestSemanticModelOperationDispatcher {
public void testRejectedDefinitionReplacementDoesNotPersistOtherChanges() {
SemanticModel original =
dispatcher.createSemanticModel(
- MODEL_IDENT, "Original", validDefinition(), Map.of("owner", "sales"));
+ MODEL_IDENT,
+ "Original",
+ validDefinition(),
+ Map.of("owner", "sales"),
+ sources(validDefinition()));
SemanticModelDefinition invalidReplacement =
SemanticModelDefinition.builder()
@@ -274,6 +311,7 @@ public class TestSemanticModelOperationDispatcher {
() ->
dispatcher.alterSemanticModel(
MODEL_IDENT,
+ sources(invalidReplacement),
SemanticModelChange.rename("must_not_persist"),
SemanticModelChange.updateComment("Must not persist"),
SemanticModelChange.setProperty("owner", "changed"),
@@ -291,9 +329,12 @@ public class TestSemanticModelOperationDispatcher {
public void testLifecycleMissingParentAndInvalidChangeSemantics() {
assertThrows(
IllegalSemanticModelException.class,
- () -> dispatcher.alterSemanticModel(MODEL_IDENT, (SemanticModelChange[]) null));
+ () ->
+ dispatcher.alterSemanticModel(
+ MODEL_IDENT, SemanticModelSourceUpdate.preserve(), (SemanticModelChange[]) null));
assertThrows(
- IllegalSemanticModelException.class, () -> dispatcher.alterSemanticModel(MODEL_IDENT));
+ IllegalSemanticModelException.class,
+ () -> dispatcher.alterSemanticModel(MODEL_IDENT, SemanticModelSourceUpdate.preserve()));
when(schemaDispatcher.loadSchema(SCHEMA_IDENT))
.thenThrow(new NoSuchSchemaException("Schema does not exist"));
@@ -303,7 +344,9 @@ public class TestSemanticModelOperationDispatcher {
NoSuchSemanticModelException.class,
() ->
dispatcher.alterSemanticModel(
- MODEL_IDENT, SemanticModelChange.updateComment("Missing")));
+ MODEL_IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.updateComment("Missing")));
assertFalse(dispatcher.dropSemanticModel(MODEL_IDENT));
}
@@ -311,7 +354,7 @@ public class TestSemanticModelOperationDispatcher {
public void testNullDefinitionIsRejectedByValidator() {
assertThrows(
IllegalSemanticModelException.class,
- () -> dispatcher.createSemanticModel(MODEL_IDENT, null, null, Map.of()));
+ () -> dispatcher.createSemanticModel(MODEL_IDENT, null, null, Map.of(), sources(null)));
assertFalse(dispatcher.semanticModelExists(MODEL_IDENT));
}
@@ -319,7 +362,9 @@ public class TestSemanticModelOperationDispatcher {
public void testNullPropertiesAreRejectedBeforeCatalogLookup() {
assertThrows(
IllegalArgumentException.class,
- () -> dispatcher.createSemanticModel(MODEL_IDENT, null, validDefinition(), null));
+ () ->
+ dispatcher.createSemanticModel(
+ MODEL_IDENT, null, validDefinition(), null, sources(validDefinition())));
verify(catalogManager, never()).loadCatalog(METADATA_CATALOG_IDENT);
}
@@ -343,18 +388,22 @@ public class TestSemanticModelOperationDispatcher {
MODEL_IDENT,
"Sales",
definition,
- Map.of("domain", "sales", PROPERTY_OSSIE_VERSION, "future-version"));
+ Map.of("domain", "sales", PROPERTY_OSSIE_VERSION, "future-version"),
+ sources(definition));
OssieDocument document = dispatcher.exportOssieDocument(MODEL_IDENT, format);
assertEquals(format, document.format());
assertThrows(
SemanticModelAlreadyExistsException.class,
- () -> dispatcher.importOssieDocument(NAMESPACE, document, definitionToValidate -> {}));
+ () ->
+ dispatcher.importOssieDocument(
+ NAMESPACE, document, definitionToValidate -> sources(definitionToValidate)));
assertSame(original, dispatcher.loadSemanticModel(MODEL_IDENT));
assertTrue(dispatcher.dropSemanticModel(MODEL_IDENT));
SemanticModel imported =
- dispatcher.importOssieDocument(NAMESPACE, document, definitionToValidate -> {});
+ dispatcher.importOssieDocument(
+ NAMESPACE, document, definitionToValidate -> sources(definitionToValidate));
assertEquals(original.name(), imported.name());
assertEquals(original.comment(), imported.comment());
assertEquals(original.definition(), imported.definition());
@@ -366,7 +415,8 @@ public class TestSemanticModelOperationDispatcher {
public void testParsedImportCreatesModelFromNativeValues() {
SemanticModelDefinition definition = validDefinition();
SemanticModel imported =
- dispatcher.importSemanticModel(MODEL_IDENT, "Sales", definition, Map.of("domain", "sales"));
+ dispatcher.importSemanticModel(
+ MODEL_IDENT, "Sales", definition, Map.of("domain", "sales"), sources(definition));
assertEquals(MODEL_IDENT.name(), imported.name());
assertEquals("Sales", imported.comment());
@@ -376,7 +426,9 @@ public class TestSemanticModelOperationDispatcher {
assertSame(imported, dispatcher.loadSemanticModel(MODEL_IDENT));
assertThrows(
SemanticModelAlreadyExistsException.class,
- () -> dispatcher.importSemanticModel(MODEL_IDENT, null, definition, Map.of()));
+ () ->
+ dispatcher.importSemanticModel(
+ MODEL_IDENT, null, definition, Map.of(), sources(definition)));
}
@Test
@@ -399,7 +451,8 @@ public class TestSemanticModelOperationDispatcher {
assertThrows(
IllegalSemanticModelException.class,
- () -> dispatcher.importOssieDocument(NAMESPACE, invalid, definition -> {}));
+ () ->
+ dispatcher.importOssieDocument(NAMESPACE, invalid, definition -> sources(definition)));
assertFalse(dispatcher.semanticModelExists(MODEL_IDENT));
}
@@ -414,6 +467,7 @@ public class TestSemanticModelOperationDispatcher {
assertEquals("orders", definition.datasets()[0].name());
assertFalse(dispatcher.semanticModelExists(MODEL_IDENT));
validations.incrementAndGet();
+ return sources(definition);
});
assertEquals(1, validations.get());
assertSame(imported, dispatcher.loadSemanticModel(MODEL_IDENT));
@@ -443,7 +497,9 @@ public class TestSemanticModelOperationDispatcher {
IllegalSemanticModelException.class,
() ->
dispatcher.importOssieDocument(
- NAMESPACE, OssieDocument.json(ossieDocument().content()), definition -> {}));
+ NAMESPACE,
+ OssieDocument.json(ossieDocument().content()),
+ definition -> sources(definition)));
verify(catalogManager, never()).loadCatalog(METADATA_CATALOG_IDENT);
}
@@ -456,7 +512,9 @@ public class TestSemanticModelOperationDispatcher {
.thenThrow(new NoSuchSchemaException("Schema does not exist"));
assertThrows(
NoSuchSchemaException.class,
- () -> dispatcher.importOssieDocument(NAMESPACE, ossieDocument(), definition -> {}));
+ () ->
+ dispatcher.importOssieDocument(
+ NAMESPACE, ossieDocument(), definition -> sources(definition)));
}
private static OssieDocument ossieDocument() {
diff --git a/core/src/test/java/org/apache/gravitino/hook/TestSemanticModelHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestSemanticModelHookDispatcher.java
index 4c33fe169f..287ae2217a 100644
--- a/core/src/test/java/org/apache/gravitino/hook/TestSemanticModelHookDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/hook/TestSemanticModelHookDispatcher.java
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.hook;
+import static org.apache.gravitino.semantic.SemanticModelTestUtils.sources;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
@@ -47,6 +48,7 @@ import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.semantic.SemanticModelMetric;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
@@ -91,7 +93,8 @@ public class TestSemanticModelHookDispatcher {
SemanticModelDefinition definition = Mockito.mock(SemanticModelDefinition.class);
SemanticModel created = Mockito.mock(SemanticModel.class);
Mockito.when(created.name()).thenReturn("sales_model");
- Mockito.when(dispatcher.createSemanticModel(eq(IDENT), eq("comment"), eq(definition), any()))
+ Mockito.when(
+ dispatcher.createSemanticModel(eq(IDENT), eq("comment"), eq(definition), any(), any()))
.thenReturn(created);
OwnerDispatcher ownerDispatcher = Mockito.mock(OwnerDispatcher.class);
@@ -102,7 +105,8 @@ public class TestSemanticModelHookDispatcher {
SemanticModelHookDispatcher hook =
new SemanticModelHookDispatcher(dispatcher, env::ownerDispatcher);
SemanticModel result =
- hook.createSemanticModel(IDENT, "comment", definition, ImmutableMap.of());
+ hook.createSemanticModel(
+ IDENT, "comment", definition, ImmutableMap.of(), sources(definition));
assertSame(created, result);
@@ -127,16 +131,22 @@ public class TestSemanticModelHookDispatcher {
SemanticModelDefinition definition = Mockito.mock(SemanticModelDefinition.class);
SemanticModel imported = Mockito.mock(SemanticModel.class);
ImmutableMap<String, String> properties = ImmutableMap.of("domain", "sales");
- Mockito.when(dispatcher.importSemanticModel(IDENT, "comment", definition, properties))
+ Mockito.when(
+ dispatcher.importSemanticModel(
+ IDENT, "comment", definition, properties, sources(definition)))
.thenReturn(imported);
OwnerDispatcher ownerDispatcher = Mockito.mock(OwnerDispatcher.class);
SemanticModelHookDispatcher hook =
new SemanticModelHookDispatcher(dispatcher, () -> ownerDispatcher);
- assertSame(imported, hook.importSemanticModel(IDENT, "comment", definition, properties));
+ assertSame(
+ imported,
+ hook.importSemanticModel(IDENT, "comment", definition, properties, sources(definition)));
InOrder order = Mockito.inOrder(dispatcher, ownerDispatcher);
- order.verify(dispatcher).importSemanticModel(IDENT, "comment", definition, properties);
+ order
+ .verify(dispatcher)
+ .importSemanticModel(IDENT, "comment", definition, properties, sources(definition));
ArgumentCaptor<MetadataObject> object = ArgumentCaptor.forClass(MetadataObject.class);
order
.verify(ownerDispatcher)
@@ -164,7 +174,8 @@ public class TestSemanticModelHookDispatcher {
SemanticModelDefinition definition = Mockito.mock(SemanticModelDefinition.class);
SemanticModel created = Mockito.mock(SemanticModel.class);
Mockito.when(created.name()).thenReturn("Sales_Model");
- Mockito.when(dispatcher.createSemanticModel(any(), any(), any(), any())).thenReturn(created);
+ Mockito.when(dispatcher.createSemanticModel(any(), any(), any(), any(), any()))
+ .thenReturn(created);
OwnerDispatcher ownerDispatcher = Mockito.mock(OwnerDispatcher.class);
@@ -175,7 +186,8 @@ public class TestSemanticModelHookDispatcher {
SemanticModelHookDispatcher hook =
new SemanticModelHookDispatcher(dispatcher, env::ownerDispatcher);
new SemanticModelNormalizeDispatcher(hook, env.catalogManager())
- .createSemanticModel(ident, "comment", definition, ImmutableMap.of());
+ .createSemanticModel(
+ ident, "comment", definition, ImmutableMap.of(), sources(definition));
ArgumentCaptor<MetadataObject> captor = ArgumentCaptor.forClass(MetadataObject.class);
Mockito.verify(ownerDispatcher)
@@ -202,18 +214,21 @@ public class TestSemanticModelHookDispatcher {
SemanticModelDispatcher dispatcher = Mockito.mock(SemanticModelDispatcher.class);
SemanticModelDefinition definition = Mockito.mock(SemanticModelDefinition.class);
SemanticModel created = Mockito.mock(SemanticModel.class);
- Mockito.when(dispatcher.createSemanticModel(any(), any(), any(), any())).thenReturn(created);
+ Mockito.when(dispatcher.createSemanticModel(any(), any(), any(), any(), any()))
+ .thenReturn(created);
FieldUtils.writeField(env, "ownerDispatcher", null, true);
try {
SemanticModelHookDispatcher hook =
new SemanticModelHookDispatcher(dispatcher, env::ownerDispatcher);
SemanticModel result =
- hook.createSemanticModel(IDENT, "comment", definition, ImmutableMap.of());
+ hook.createSemanticModel(
+ IDENT, "comment", definition, ImmutableMap.of(), sources(definition));
assertSame(created, result);
Mockito.verify(dispatcher)
- .createSemanticModel(IDENT, "comment", definition, ImmutableMap.of());
+ .createSemanticModel(
+ IDENT, "comment", definition, ImmutableMap.of(), sources(definition));
} finally {
FieldUtils.writeField(env, "ownerDispatcher", originalOwnerDispatcher, true);
}
@@ -234,7 +249,8 @@ public class TestSemanticModelHookDispatcher {
SemanticModelDefinition definition = Mockito.mock(SemanticModelDefinition.class);
SemanticModel created = Mockito.mock(SemanticModel.class);
Mockito.when(created.name()).thenReturn("sales_model");
- Mockito.when(dispatcher.createSemanticModel(any(), any(), any(), any())).thenReturn(created);
+ Mockito.when(dispatcher.createSemanticModel(any(), any(), any(), any(), any()))
+ .thenReturn(created);
FieldUtils.writeField(env, "ownerDispatcher", ownerDispatcher, true);
FieldUtils.writeField(env, "catalogManager", mockCatalogManager(Capability.DEFAULT), true);
@@ -244,7 +260,9 @@ public class TestSemanticModelHookDispatcher {
RuntimeException thrown =
assertThrows(
RuntimeException.class,
- () -> hook.createSemanticModel(IDENT, "comment", definition, ImmutableMap.of()));
+ () ->
+ hook.createSemanticModel(
+ IDENT, "comment", definition, ImmutableMap.of(), sources(definition)));
assertEquals("Set owner failed", thrown.getMessage());
} finally {
FieldUtils.writeField(env, "ownerDispatcher", originalOwnerDispatcher, true);
@@ -267,7 +285,8 @@ public class TestSemanticModelHookDispatcher {
Namespace namespace = Namespace.of("metalake1", "catalog1", "schema1");
Mockito.when(dispatcher.listSemanticModels(namespace)).thenReturn(listed);
Mockito.when(dispatcher.loadSemanticModel(IDENT)).thenReturn(loaded);
- Mockito.when(dispatcher.alterSemanticModel(IDENT, change)).thenReturn(altered);
+ Mockito.when(dispatcher.alterSemanticModel(IDENT, SemanticModelSourceUpdate.preserve(), change))
+ .thenReturn(altered);
Mockito.when(dispatcher.dropSemanticModel(IDENT)).thenReturn(true);
Mockito.when(dispatcher.semanticModelExists(IDENT)).thenReturn(true);
@@ -279,7 +298,8 @@ public class TestSemanticModelHookDispatcher {
assertSame(listed, hook.listSemanticModels(namespace));
assertSame(loaded, hook.loadSemanticModel(IDENT));
- assertSame(altered, hook.alterSemanticModel(IDENT, change));
+ assertSame(
+ altered, hook.alterSemanticModel(IDENT, SemanticModelSourceUpdate.preserve(), change));
assertTrue(hook.dropSemanticModel(IDENT));
assertTrue(hook.semanticModelExists(IDENT));
@@ -296,13 +316,18 @@ public class TestSemanticModelHookDispatcher {
GravitinoEnv env = Mockito.mock(GravitinoEnv.class);
Mockito.when(env.gravitinoAuthorizer()).thenReturn(authorizer);
SemanticModelChange rename = SemanticModelChange.rename("renamed");
- Mockito.when(dispatcher.alterSemanticModel(IDENT, rename))
+ Mockito.when(dispatcher.alterSemanticModel(IDENT, SemanticModelSourceUpdate.preserve(), rename))
.thenThrow(new IllegalArgumentException("rejected"));
try (MockedStatic<GravitinoEnv> mocked = Mockito.mockStatic(GravitinoEnv.class)) {
mocked.when(GravitinoEnv::getInstance).thenReturn(env);
SemanticModelHookDispatcher hook = new SemanticModelHookDispatcher(dispatcher, () -> null);
- assertThrows(IllegalArgumentException.class, () -> hook.alterSemanticModel(IDENT, rename));
- hook.alterSemanticModel(IDENT, SemanticModelChange.setProperty("key", "value"));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> hook.alterSemanticModel(IDENT, SemanticModelSourceUpdate.preserve(), rename));
+ hook.alterSemanticModel(
+ IDENT,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.setProperty("key", "value"));
Mockito.when(dispatcher.dropSemanticModel(IDENT)).thenReturn(false);
assertFalse(hook.dropSemanticModel(IDENT));
Mockito.verifyNoInteractions(authorizer);
diff --git a/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelEvent.java b/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelEvent.java
index b6569dc91f..4d0e30d1d4 100644
--- a/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelEvent.java
+++ b/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelEvent.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.listener.api.event;
+import static org.apache.gravitino.semantic.SemanticModelTestUtils.sources;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
@@ -60,6 +61,7 @@ import org.apache.gravitino.semantic.Dataset;
import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.utils.PrincipalUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
@@ -94,7 +96,8 @@ public class TestSemanticModelEvent {
identifier,
semanticModel.comment(),
semanticModel.definition(),
- semanticModel.properties());
+ semanticModel.properties(),
+ sources(semanticModel.definition()));
Event event = dummyEventListener.popPostEvent();
Assertions.assertEquals(identifier, event.identifier());
@@ -137,7 +140,7 @@ public class TestSemanticModelEvent {
void testAlterSemanticModelEvent() {
NameIdentifier identifier = NameIdentifier.of(NAMESPACE, semanticModel.name());
SemanticModelChange change = SemanticModelChange.setProperty("a", "b");
- dispatcher.alterSemanticModel(identifier, change);
+ dispatcher.alterSemanticModel(identifier, SemanticModelSourceUpdate.preserve(), change);
Event event = dummyEventListener.popPostEvent();
Assertions.assertEquals(identifier, event.identifier());
@@ -209,7 +212,8 @@ public class TestSemanticModelEvent {
identifier,
semanticModel.comment(),
semanticModel.definition(),
- semanticModel.properties()));
+ semanticModel.properties(),
+ sources(semanticModel.definition())));
Event event = dummyEventListener.popPostEvent();
Assertions.assertEquals(identifier, event.identifier());
@@ -245,7 +249,9 @@ public class TestSemanticModelEvent {
SemanticModelChange change = SemanticModelChange.setProperty("a", "b");
Assertions.assertThrowsExactly(
GravitinoRuntimeException.class,
- () -> failureDispatcher.alterSemanticModel(identifier, change));
+ () ->
+ failureDispatcher.alterSemanticModel(
+ identifier, SemanticModelSourceUpdate.preserve(), change));
Event event = dummyEventListener.popPostEvent();
Assertions.assertEquals(identifier, event.identifier());
@@ -416,8 +422,14 @@ public class TestSemanticModelEvent {
Arrays.<Consumer<SemanticModelEventDispatcher>>asList(
d -> d.listSemanticModels(NAMESPACE),
d -> d.loadSemanticModel(identifier),
- d -> d.createSemanticModel(identifier, "comment", definition(), ImmutableMap.of()),
- d -> d.alterSemanticModel(identifier, SemanticModelChange.setProperty("a", "b")),
+ d ->
+ d.createSemanticModel(
+ identifier, "comment", definition(), ImmutableMap.of(), sources(definition())),
+ d ->
+ d.alterSemanticModel(
+ identifier,
+ SemanticModelSourceUpdate.preserve(),
+ SemanticModelChange.setProperty("a", "b")),
d -> d.dropSemanticModel(identifier))) {
DummyEventListener listener = new DummyEventListener();
SemanticModelEventDispatcher eventDispatcher =
@@ -452,7 +464,9 @@ public class TestSemanticModelEvent {
IllegalArgumentException exception =
Assertions.assertThrows(
IllegalArgumentException.class,
- () -> eventDispatcher.alterSemanticModel(identifier, changes));
+ () ->
+ eventDispatcher.alterSemanticModel(
+ identifier, SemanticModelSourceUpdate.preserve(), changes));
Assertions.assertEquals("At least one change is required", exception.getMessage());
Assertions.assertEquals(1, listener.getPreEvents().size());
@@ -528,7 +542,11 @@ public class TestSemanticModelEvent {
private SemanticModelDispatcher mockSemanticModelDispatcher() {
SemanticModelDispatcher d = mock(SemanticModelDispatcher.class);
when(d.createSemanticModel(
- any(NameIdentifier.class), any(), any(SemanticModelDefinition.class), any(Map.class)))
+ any(NameIdentifier.class),
+ any(),
+ any(SemanticModelDefinition.class),
+ any(Map.class),
+ any()))
.thenReturn(semanticModel);
when(d.loadSemanticModel(any(NameIdentifier.class))).thenReturn(semanticModel);
when(d.semanticModelExists(any(NameIdentifier.class))).thenReturn(true);
@@ -538,7 +556,7 @@ public class TestSemanticModelEvent {
new NameIdentifier[] {
NameIdentifier.of(NAMESPACE, "model1"), NameIdentifier.of(NAMESPACE, "model2")
});
- when(d.alterSemanticModel(any(NameIdentifier.class), any(SemanticModelChange.class)))
+ when(d.alterSemanticModel(any(NameIdentifier.class), any(), any(SemanticModelChange.class)))
.thenReturn(semanticModel);
return d;
}
diff --git a/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelImportExportEvent.java b/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelImportExportEvent.java
index 25da8956a5..8356a93f05 100644
--- a/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelImportExportEvent.java
+++ b/core/src/test/java/org/apache/gravitino/listener/api/event/TestSemanticModelImportExportEvent.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.listener.api.event;
import static org.apache.gravitino.semantic.SemanticModel.PROPERTY_OSSIE_VERSION;
+import static org.apache.gravitino.semantic.SemanticModelTestUtils.sources;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -107,13 +108,13 @@ class TestSemanticModelImportExportEvent {
authorizationEnabled = true;
owners = mock(OwnerDispatcher.class);
operation = mock(SemanticModelOperationDispatcher.class);
- doCallRealMethod().when(operation).importSemanticModel(any(), any(), any(), any());
+ doCallRealMethod().when(operation).importSemanticModel(any(), any(), any(), any(), any());
doCallRealMethod().when(operation).exportOssieDocument(any(), any());
model = mock(SemanticModel.class);
when(model.name()).thenReturn(IDENT.name());
when(model.definition()).thenReturn(definition());
when(model.properties()).thenReturn(Map.of());
- when(operation.createSemanticModel(any(), any(), any(), any())).thenReturn(model);
+ when(operation.createSemanticModel(any(), any(), any(), any(), any())).thenReturn(model);
when(operation.loadSemanticModel(NORMALIZED_IDENT)).thenReturn(model);
CatalogManager catalogs = mock(CatalogManager.class);
BaseCatalog<?> catalog = mock(BaseCatalog.class);
@@ -140,15 +141,20 @@ class TestSemanticModelImportExportEvent {
document,
definition -> {
assertEquals(definition(), definition);
- verify(operation, never()).createSemanticModel(any(), any(), any(), any());
+ verify(operation, never()).createSemanticModel(any(), any(), any(), any(), any());
verifyNoInteractions(owners);
validations.incrementAndGet();
+ return sources(definition);
}));
converter.verify(() -> OssieDocumentConverter.importDocument(document));
}
assertEquals(1, validations.get());
- verify(operation).importSemanticModel(eq(NORMALIZED_IDENT), any(), eq(definition()), any());
- verify(operation).createSemanticModel(eq(NORMALIZED_IDENT), any(), eq(definition()), any());
+ verify(operation)
+ .importSemanticModel(
+ eq(NORMALIZED_IDENT), any(), eq(definition()), any(), eq(sources(definition())));
+ verify(operation)
+ .createSemanticModel(
+ eq(NORMALIZED_IDENT), any(), eq(definition()), any(), eq(sources(definition())));
ArgumentCaptor<MetadataObject> object = ArgumentCaptor.forClass(MetadataObject.class);
verify(owners).setOwner(eq("metalake"), object.capture(), any(), eq(Owner.Type.USER));
assertEquals("catalog.mixedschema.SalesModel", object.getValue().fullName());
@@ -173,7 +179,9 @@ class TestSemanticModelImportExportEvent {
UnsupportedOperationException failure =
assertThrows(
UnsupportedOperationException.class,
- () -> dispatcher.importSemanticModel(IDENT, null, definition(), Map.of()));
+ () ->
+ dispatcher.importSemanticModel(
+ IDENT, null, definition(), Map.of(), sources(definition())));
assertTrue(failure.getMessage().contains("importOssieDocument"));
verifyNoInteractions(normalizer, hook, operation, owners);
@@ -186,7 +194,12 @@ class TestSemanticModelImportExportEvent {
authorizationEnabled = false;
AtomicInteger validations = new AtomicInteger();
dispatcher.importOssieDocument(
- NAMESPACE, document(), definition -> validations.incrementAndGet());
+ NAMESPACE,
+ document(),
+ definition -> {
+ validations.incrementAndGet();
+ return sources(definition);
+ });
assertEquals(1, validations.get());
assertEvents(ImportSemanticModelPreEvent.class, ImportSemanticModelEvent.class);
verifyNoInteractions(owners);
@@ -203,7 +216,7 @@ class TestSemanticModelImportExportEvent {
document = OssieDocument.yaml(document.content().replace("SalesModel", "invalid model"));
} else if (stage.equals("create")) {
expected = new SemanticModelAlreadyExistsException("already exists");
- doThrow(expected).when(operation).createSemanticModel(any(), any(), any(), any());
+ doThrow(expected).when(operation).createSemanticModel(any(), any(), any(), any(), any());
} else if (stage.equals("owner")) {
expected = new IllegalStateException("owner assignment failed");
doThrow(expected).when(owners).setOwner(any(), any(), any(), any());
@@ -219,6 +232,7 @@ class TestSemanticModelImportExportEvent {
request,
definition -> {
if (stage.equals("source")) throw failure;
+ return sources(definition);
}));
ImportSemanticModelFailureEvent event =
assertEvents(ImportSemanticModelPreEvent.class, ImportSemanticModelFailureEvent.class);
@@ -229,7 +243,7 @@ class TestSemanticModelImportExportEvent {
assertAudit(event, AuditLog.Operation.IMPORT_SEMANTIC_MODEL, OperationStatus.FAILURE);
if (!stage.equals("owner")) verifyNoInteractions(owners);
if (List.of("parse", "source", "normalize").contains(stage)) {
- verify(operation, never()).createSemanticModel(any(), any(), any(), any());
+ verify(operation, never()).createSemanticModel(any(), any(), any(), any(), any());
} else {
assertSame(expected, thrown);
}
@@ -244,6 +258,19 @@ class TestSemanticModelImportExportEvent {
verifyNoInteractions(operation, owners);
}
+ @Test
+ void testImportRejectsNullSourceUpdateBeforeWriting() {
+ IllegalArgumentException failure =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> dispatcher.importOssieDocument(NAMESPACE, document(), definition -> null));
+ assertEquals("sourceValidator must not return null", failure.getMessage());
+ ImportSemanticModelFailureEvent event =
+ assertEvents(ImportSemanticModelPreEvent.class, ImportSemanticModelFailureEvent.class);
+ assertSame(failure, event.exception());
+ verifyNoInteractions(operation, owners);
+ }
+
@ParameterizedTest
@ValueSource(booleans = {false, true})
void testPreEventRejectionEmitsFailureWithoutInvokingOperation(boolean importing) {
@@ -254,7 +281,9 @@ class TestSemanticModelImportExportEvent {
new SemanticModelEventDispatcher(new EventBus(List.of(rejecting)), normalizer);
Runnable action =
importing
- ? () -> rejectedDispatcher.importOssieDocument(NAMESPACE, document(), definition -> {})
+ ? () ->
+ rejectedDispatcher.importOssieDocument(
+ NAMESPACE, document(), definition -> sources(definition))
: () -> rejectedDispatcher.exportOssieDocument(IDENT, OssieFormat.YAML);
assertSame(denied, assertThrows(ForbiddenException.class, action::run));
verifyNoInteractions(normalizer, operation, owners);
@@ -271,7 +300,7 @@ class TestSemanticModelImportExportEvent {
void testNullImportDocumentStillEmitsFailure() {
assertThrows(
NullPointerException.class,
- () -> dispatcher.importOssieDocument(NAMESPACE, null, definition -> {}));
+ () -> dispatcher.importOssieDocument(NAMESPACE, null, definition -> sources(definition)));
ImportSemanticModelFailureEvent event =
assertEvents(ImportSemanticModelPreEvent.class, ImportSemanticModelFailureEvent.class);
assertNull(event.format());
@@ -338,7 +367,7 @@ class TestSemanticModelImportExportEvent {
if (fail) {
doThrow(new IllegalArgumentException("rejected"))
.when(operation)
- .createSemanticModel(any(), any(), any(), any());
+ .createSemanticModel(any(), any(), any(), any(), any());
doThrow(new IllegalArgumentException("rejected")).when(operation).loadSemanticModel(any());
}
for (boolean importing : new boolean[] {true, false}) {
@@ -347,7 +376,9 @@ class TestSemanticModelImportExportEvent {
principal.when(PrincipalUtils::getCurrentUserName).thenReturn("initiator", "changed");
Runnable action =
importing
- ? () -> dispatcher.importOssieDocument(NAMESPACE, document(), definition -> {})
+ ? () ->
+ dispatcher.importOssieDocument(
+ NAMESPACE, document(), definition -> sources(definition))
: () -> dispatcher.exportOssieDocument(IDENT, OssieFormat.JSON);
if (fail) assertThrows(IllegalArgumentException.class, action::run);
else action.run();
@@ -365,9 +396,9 @@ class TestSemanticModelImportExportEvent {
T postEvent = assertInstanceOf(post, listener.getPostEvents().getFirst());
assertEquals(preEvent.operationType(), postEvent.operationType());
assertEquals(OperationStatus.UNPROCESSED, preEvent.operationStatus());
- verify(normalizer, never()).createSemanticModel(any(), any(), any(), any());
+ verify(normalizer, never()).createSemanticModel(any(), any(), any(), any(), any());
verify(normalizer, never()).loadSemanticModel(any());
- verify(hook, never()).createSemanticModel(any(), any(), any(), any());
+ verify(hook, never()).createSemanticModel(any(), any(), any(), any(), any());
verify(hook, never()).loadSemanticModel(any());
return postEvent;
}
diff --git a/core/src/test/java/org/apache/gravitino/semantic/SemanticModelTestUtils.java b/core/src/test/java/org/apache/gravitino/semantic/SemanticModelTestUtils.java
new file mode 100644
index 0000000000..ea5507ef35
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/semantic/SemanticModelTestUtils.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.semantic;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+import org.apache.gravitino.Entity;
+
+/** Resolved source fixtures for tests that exercise the internal model write pipeline. */
+public final class SemanticModelTestUtils {
+ private SemanticModelTestUtils() {}
+
+ /**
+ * Builds deterministic associations without accessing a catalog; source resolution is tested in
+ * REST.
+ *
+ * @param definition A test definition, including malformed definitions used by validation tests.
+ * @return A replacement instruction with one association per valid dataset name.
+ */
+ public static SemanticModelSourceUpdate sources(SemanticModelDefinition definition) {
+ if (definition == null || definition.datasets() == null) {
+ return SemanticModelSourceUpdate.replace(List.of());
+ }
+ return SemanticModelSourceUpdate.replace(
+ Arrays.stream(definition.datasets())
+ .filter(Objects::nonNull)
+ .map(Dataset::name)
+ .filter(name -> name != null && !name.isEmpty())
+ .distinct()
+ .map(name -> new SemanticModelSource(name, Entity.EntityType.TABLE, 1L))
+ .toList());
+ }
+}
diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
index 949dc53900..b32c1eb9ce 100644
--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
@@ -109,6 +109,7 @@ import org.apache.gravitino.meta.SchemaVersion;
import org.apache.gravitino.meta.UserEntity;
import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.server.ServerConfig;
import org.apache.gravitino.server.authorization.AuthorizationRequestScope;
import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
@@ -4121,12 +4122,13 @@ public class TestJcasbinAuthorizer {
SemanticModel renamed = mock(SemanticModel.class);
when(renamed.name()).thenReturn(newIdent.name());
SemanticModelChange rename = SemanticModelChange.rename(newIdent.name());
- when(dispatcher.alterSemanticModel(oldIdent, rename)).thenReturn(renamed);
+ when(dispatcher.alterSemanticModel(oldIdent, SemanticModelSourceUpdate.preserve(), rename))
+ .thenReturn(renamed);
when(dispatcher.dropSemanticModel(newIdent)).thenReturn(true);
when(gravitinoEnv.gravitinoAuthorizer()).thenReturn(jcasbinAuthorizer);
SemanticModelHookDispatcher hook = new SemanticModelHookDispatcher(dispatcher, () -> null);
try {
- hook.alterSemanticModel(oldIdent, rename);
+ hook.alterSemanticModel(oldIdent, SemanticModelSourceUpdate.preserve(), rename);
metadataIdConverterMockedStatic
.when(
() ->
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java
index 21cc62a478..fea55639e0 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java
@@ -57,6 +57,7 @@ import org.apache.gravitino.semantic.OssieFormat;
import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.server.authorization.MetadataAuthzHelper;
import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;
import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;
@@ -354,13 +355,15 @@ public class SemanticModelOperations {
.anyMatch(change -> change instanceof SemanticModelChange.ReplaceDefinition)) {
dispatcher.loadSemanticModel(ident);
}
+ SemanticModelSourceUpdate sourceUpdate = SemanticModelSourceUpdate.preserve();
for (SemanticModelChange change : changes) {
if (change instanceof SemanticModelChange.ReplaceDefinition) {
- sourceValidator.validate(
- metalake, ((SemanticModelChange.ReplaceDefinition) change).getDefinition());
+ sourceUpdate =
+ sourceValidator.validate(
+ metalake, ((SemanticModelChange.ReplaceDefinition) change).getDefinition());
}
}
- SemanticModel altered = dispatcher.alterSemanticModel(ident, changes);
+ SemanticModel altered = dispatcher.alterSemanticModel(ident, sourceUpdate, changes);
LOG.info(
"Semantic Model altered: {}.{}.{}.{}", metalake, catalog, schema, altered.name());
return Utils.ok(new SemanticModelResponse(DTOConverters.toDTO(altered)));
@@ -483,14 +486,15 @@ public class SemanticModelOperations {
String metalake, String catalog, String schema, SemanticModelCreateRequest request) {
request.validate();
SemanticModelDefinition definition = request.toDefinition();
- sourceValidator.validate(metalake, definition);
+ SemanticModelSourceUpdate sourceUpdate = sourceValidator.validate(metalake, definition);
NameIdentifier ident =
NameIdentifierUtil.ofSemanticModel(metalake, catalog, schema, request.getName());
return dispatcher.createSemanticModel(
ident,
request.getComment(),
definition,
- request.getProperties() == null ? Collections.emptyMap() : request.getProperties());
+ request.getProperties() == null ? Collections.emptyMap() : request.getProperties(),
+ sourceUpdate);
}
private static OssieFormat parseOssieFormat(String format) {
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelSourceValidator.java b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelSourceValidator.java
index b77eab345c..4f10549318 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelSourceValidator.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelSourceValidator.java
@@ -18,10 +18,12 @@
*/
package org.apache.gravitino.server.web.rest;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
@@ -30,8 +32,11 @@ import javax.inject.Inject;
import org.apache.gravitino.Entity;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.StringIdentifier;
import org.apache.gravitino.authorization.AuthorizationRequestContext;
import org.apache.gravitino.authorization.GravitinoAuthorizer;
+import org.apache.gravitino.catalog.EntityCombinedTable;
+import org.apache.gravitino.catalog.EntityCombinedView;
import org.apache.gravitino.catalog.TableDispatcher;
import org.apache.gravitino.catalog.ViewDispatcher;
import org.apache.gravitino.connector.CatalogOperations;
@@ -39,11 +44,15 @@ import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.exceptions.IllegalSemanticModelException;
import org.apache.gravitino.exceptions.NotFoundException;
import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.TableCatalog;
+import org.apache.gravitino.rel.View;
import org.apache.gravitino.rel.ViewCatalog;
import org.apache.gravitino.semantic.Dataset;
import org.apache.gravitino.semantic.Relationship;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelSource;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;
import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionEvaluator;
@@ -110,12 +119,14 @@ public class SemanticModelSourceValidator {
*
* @param metalake the request's metalake, also used for cross-catalog source references
* @param definition the complete definition to validate before persistence
+ * @return The complete source associations resolved by this validation.
*/
- public void validate(String metalake, SemanticModelDefinition definition) {
+ public SemanticModelSourceUpdate validate(String metalake, SemanticModelDefinition definition) {
AuthorizationRequestContext context = new AuthorizationRequestContext();
GravitinoAuthorizer currentAuthorizer = authorizer.get();
Map<String, Set<String>> datasetColumns = new HashMap<>();
- Map<NameIdentifier, Set<String>> sourceColumns = new HashMap<>();
+ Map<NameIdentifier, ResolvedSource> resolvedSources = new HashMap<>();
+ List<SemanticModelSource> associations = new ArrayList<>();
for (Dataset dataset : definition.datasets()) {
NameIdentifier source = dataset.source();
if (source.namespace().length() != 2) {
@@ -124,8 +135,11 @@ public class SemanticModelSourceValidator {
NameIdentifier ident =
NameIdentifier.of(
metalake, source.namespace().level(0), source.namespace().level(1), source.name());
- Set<String> columns =
- sourceColumns.computeIfAbsent(ident, key -> loadColumns(key, currentAuthorizer, context));
+ ResolvedSource resolved =
+ resolvedSources.computeIfAbsent(
+ ident, key -> loadSource(key, currentAuthorizer, context));
+ Set<String> columns = resolved.columns;
+ associations.add(new SemanticModelSource(dataset.name(), resolved.type, resolved.id));
datasetColumns.put(dataset.name(), columns);
checkColumns(dataset.name(), dataset.primaryKey(), columns);
if (dataset.uniqueKeys() != null) {
@@ -144,9 +158,10 @@ public class SemanticModelSourceValidator {
relationship.to(), relationship.toColumns(), datasetColumns.get(relationship.to()));
}
}
+ return SemanticModelSourceUpdate.replace(associations);
}
- private Set<String> loadColumns(
+ private ResolvedSource loadSource(
NameIdentifier ident,
GravitinoAuthorizer currentAuthorizer,
AuthorizationRequestContext context) {
@@ -172,13 +187,18 @@ public class SemanticModelSourceValidator {
supported = supportedSourceTypes.apply(ident);
if (tableAllowed && supported.contains(Entity.EntityType.TABLE)) {
try {
- return columnNames(ident, tables.loadTable(ident).columns());
+ Table table = tables.loadTable(ident);
+ Set<String> columns = columnNames(ident, table.columns());
+ return new ResolvedSource(
+ registeredTableId(ident, table), Entity.EntityType.TABLE, columns);
} catch (NotFoundException missing) {
// An untyped source can also refer to a view.
}
}
if (viewAllowed && supported.contains(Entity.EntityType.VIEW)) {
- return columnNames(ident, views.loadView(ident).columns());
+ View view = views.loadView(ident);
+ Set<String> columns = columnNames(ident, view.columns());
+ return new ResolvedSource(registeredViewId(ident, view), Entity.EntityType.VIEW, columns);
}
} catch (NotFoundException missing) {
// Do not disclose whether the other, inaccessible object type exists.
@@ -190,6 +210,55 @@ public class SemanticModelSourceValidator {
throw new IllegalSemanticModelException("Semantic Model source %s does not exist", ident);
}
+ private static long registeredTableId(NameIdentifier ident, Table table) {
+ if (table instanceof EntityCombinedTable) {
+ EntityCombinedTable combined = (EntityCombinedTable) table;
+ if (combined.tableFromGravitino() != null) {
+ return combined.tableFromGravitino().id();
+ }
+ // Managed tables carry their stored ID in the loaded catalog properties, without a separate
+ // TableEntity. Read it before public-property masking, without resolving the name again.
+ if (combined.imported()) {
+ StringIdentifier id =
+ StringIdentifier.fromProperties(combined.tableFromCatalog().properties());
+ if (id != null) {
+ return id.id();
+ }
+ }
+ }
+ throw new IllegalStateException("Source table has no registered Gravitino identity: " + ident);
+ }
+
+ private static long registeredViewId(NameIdentifier ident, View view) {
+ if (view instanceof EntityCombinedView) {
+ EntityCombinedView combined = (EntityCombinedView) view;
+ if (combined.viewEntity() != null) {
+ return combined.viewEntity().id();
+ }
+ // Managed views use the same stored-identity property as managed tables.
+ if (combined.imported()) {
+ StringIdentifier id =
+ StringIdentifier.fromProperties(combined.viewFromCatalog().properties());
+ if (id != null) {
+ return id.id();
+ }
+ }
+ }
+ throw new IllegalStateException("Source view has no registered Gravitino identity: " + ident);
+ }
+
+ private static class ResolvedSource {
+ private final long id;
+ private final Entity.EntityType type;
+ private final Set<String> columns;
+
+ private ResolvedSource(long id, Entity.EntityType type, Set<String> columns) {
+ this.id = id;
+ this.type = type;
+ this.columns = columns;
+ }
+ }
+
private boolean canLoad(
NameIdentifier ident,
Entity.EntityType type,
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
index 97cc2dd10a..97334951f0 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
@@ -58,6 +58,7 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.authorization.GravitinoAuthorizer;
import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.catalog.EntityCombinedTable;
import org.apache.gravitino.catalog.SemanticModelDispatcher;
import org.apache.gravitino.catalog.TableDispatcher;
import org.apache.gravitino.catalog.ViewDispatcher;
@@ -94,6 +95,7 @@ import org.apache.gravitino.listener.api.event.semantic.ImportSemanticModelFailu
import org.apache.gravitino.listener.api.event.semantic.ImportSemanticModelPreEvent;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.meta.TableEntity;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rest.RESTUtils;
@@ -111,6 +113,8 @@ import org.apache.gravitino.semantic.OssieFormat;
import org.apache.gravitino.semantic.SemanticModel;
import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelSource;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.server.authorization.MetadataAuthzHelper;
import org.apache.gravitino.server.authorization.PassThroughAuthorizer;
import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;
@@ -208,7 +212,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
tablesSupported = true;
viewsSupported = true;
sourceAuthorizer = new PassThroughAuthorizer();
- Table table = mock(Table.class);
+ Table table = registeredTable();
Column column = mock(Column.class);
when(column.name()).thenReturn("order_id");
when(table.columns()).thenReturn(new Column[] {column});
@@ -312,7 +316,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
message = "offline";
break;
case "column":
- Table table = mock(Table.class);
+ Table table = registeredTable();
when(table.columns()).thenReturn(new Column[0]);
when(tables.loadTable(any())).thenReturn(table);
message = "order_id";
@@ -399,7 +403,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(ident),
eq("Sales definitions"),
any(SemanticModelDefinition.class),
- eq(Map.of("domain", "sales"))))
+ eq(Map.of("domain", "sales")),
+ any()))
.thenReturn(semanticModel);
Response response = post(semanticModelPath(), request);
@@ -412,13 +417,20 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
ArgumentCaptor<SemanticModelDefinition> definitionCaptor =
ArgumentCaptor.forClass(SemanticModelDefinition.class);
+ ArgumentCaptor<SemanticModelSourceUpdate> sourceCaptor =
+ ArgumentCaptor.forClass(SemanticModelSourceUpdate.class);
verify(dispatcher)
.createSemanticModel(
eq(ident),
eq("Sales definitions"),
definitionCaptor.capture(),
- eq(Map.of("domain", "sales")));
+ eq(Map.of("domain", "sales")),
+ sourceCaptor.capture());
Assertions.assertEquals(definition, definitionCaptor.getValue());
+ Assertions.assertEquals(
+ SemanticModelSourceUpdate.replace(
+ List.of(new SemanticModelSource("orders", EntityType.TABLE, 101L))),
+ sourceCaptor.getValue());
Assertions.assertEquals(
"TRINO", definitionCaptor.getValue().metrics()[0].expression().dialects()[0].dialect());
Assertions.assertEquals(DataType.DECIMAL, definitionCaptor.getValue().metrics()[0].datatype());
@@ -438,7 +450,11 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
null);
SemanticModel semanticModel = semanticModel("sales", "Sales definitions");
when(dispatcher.createSemanticModel(
- eq(ident), eq("Sales definitions"), any(SemanticModelDefinition.class), eq(Map.of())))
+ eq(ident),
+ eq("Sales definitions"),
+ any(SemanticModelDefinition.class),
+ eq(Map.of()),
+ any()))
.thenReturn(semanticModel);
Response response = post(semanticModelPath(), request);
@@ -446,7 +462,11 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
verify(dispatcher)
.createSemanticModel(
- eq(ident), eq("Sales definitions"), any(SemanticModelDefinition.class), eq(Map.of()));
+ eq(ident),
+ eq("Sales definitions"),
+ any(SemanticModelDefinition.class),
+ eq(Map.of()),
+ any());
}
@Test
@@ -496,7 +516,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(ident),
eq("Sales definitions"),
any(SemanticModelDefinition.class),
- eq(Map.of("domain", "sales")));
+ eq(Map.of("domain", "sales")),
+ any());
assertError(
post(semanticModelPath(), request),
Response.Status.NOT_FOUND,
@@ -510,7 +531,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(ident),
eq("Sales definitions"),
any(SemanticModelDefinition.class),
- eq(Map.of("domain", "sales")));
+ eq(Map.of("domain", "sales")),
+ any());
assertError(
post(semanticModelPath(), request),
Response.Status.BAD_REQUEST,
@@ -524,7 +546,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(ident),
eq("Sales definitions"),
any(SemanticModelDefinition.class),
- eq(Map.of("domain", "sales")));
+ eq(Map.of("domain", "sales")),
+ any());
assertError(
post(semanticModelPath(), request),
Response.Status.CONFLICT,
@@ -538,7 +561,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(ident),
eq("Sales definitions"),
any(SemanticModelDefinition.class),
- eq(Map.of("domain", "sales")));
+ eq(Map.of("domain", "sales")),
+ any());
assertError(
post(semanticModelPath(), request),
Response.Status.FORBIDDEN,
@@ -552,7 +576,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(ident),
eq("Sales definitions"),
any(SemanticModelDefinition.class),
- eq(Map.of("domain", "sales")));
+ eq(Map.of("domain", "sales")),
+ any());
ErrorResponse unavailable =
assertError(
post(semanticModelPath(), request),
@@ -585,7 +610,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(semanticModelIdentifier("sales")),
eq("Sales definitions"),
any(SemanticModelDefinition.class),
- eq(Map.of("domain", "sales")));
+ eq(Map.of("domain", "sales")),
+ any());
assertError(
post(semanticModelPath(), request),
@@ -608,7 +634,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
new SemanticModelUpdateRequest.RemoveSemanticModelPropertyRequest("legacy"),
new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(
SemanticModelDefinitionDTO.fromDefinition(replacement))));
- when(dispatcher.alterSemanticModel(eq(ident), any(SemanticModelChange[].class)))
+ when(dispatcher.alterSemanticModel(eq(ident), any(), any(SemanticModelChange[].class)))
.thenReturn(semanticModel("sales_v2", "Updated"));
Response response = put(semanticModelPath() + "/sales", request);
@@ -620,7 +646,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
ArgumentCaptor<SemanticModelChange[]> changesCaptor =
ArgumentCaptor.forClass(SemanticModelChange[].class);
- verify(dispatcher).alterSemanticModel(eq(ident), changesCaptor.capture());
+ verify(dispatcher).alterSemanticModel(eq(ident), any(), changesCaptor.capture());
SemanticModelChange[] changes = changesCaptor.getValue();
Assertions.assertEquals(5, changes.length);
Assertions.assertInstanceOf(SemanticModelChange.RenameSemanticModel.class, changes[0]);
@@ -652,6 +678,123 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
verifyNoMoreInteractions(dispatcher);
}
+ @Test
+ void testMetadataOnlyAlterPreservesSourcesWithoutResolving() {
+ sourceAuthorizer = mock(GravitinoAuthorizer.class);
+ when(dispatcher.alterSemanticModel(any(), any(), any(SemanticModelChange[].class)))
+ .thenReturn(semanticModel("renamed", "Updated"));
+ SemanticModelUpdatesRequest request =
+ new SemanticModelUpdatesRequest(
+ List.of(
+ new SemanticModelUpdateRequest.RenameSemanticModelRequest("renamed"),
+ new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest("Updated"),
+ new SemanticModelUpdateRequest.SetSemanticModelPropertyRequest("owner", "sales"),
+ new SemanticModelUpdateRequest.RemoveSemanticModelPropertyRequest("legacy")));
+
+ Assertions.assertEquals(
+ Response.Status.OK.getStatusCode(),
+ put(semanticModelPath() + "/sales", request).getStatus());
+ verify(dispatcher)
+ .alterSemanticModel(
+ eq(semanticModelIdentifier("sales")),
+ eq(SemanticModelSourceUpdate.preserve()),
+ any(SemanticModelChange[].class));
+ verifyNoInteractions(tables, views, sourceAuthorizer);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testReplacementRebindsUnchangedSources(boolean metricOnlyChange) {
+ SemanticModelDefinition original =
+ SemanticModelDefinition.builder()
+ .withDatasets(semanticModelDefinition().datasets())
+ .withMetrics(semanticModelDefinition().metrics())
+ .build();
+ when(dispatcher.createSemanticModel(any(), any(), any(), any(), any()))
+ .thenReturn(semanticModel("sales", null));
+ when(dispatcher.alterSemanticModel(any(), any(), any(SemanticModelChange[].class)))
+ .thenReturn(semanticModel("sales", null));
+ Assertions.assertEquals(
+ Response.Status.OK.getStatusCode(), writeDefinition(false, original).getStatus());
+ verify(dispatcher)
+ .createSemanticModel(
+ any(),
+ any(),
+ eq(original),
+ any(),
+ eq(
+ SemanticModelSourceUpdate.replace(
+ List.of(new SemanticModelSource("orders", EntityType.TABLE, 101L)))));
+
+ // The original table was renamed and another table now uses its previous name.
+ Table replacementTable = registeredTable(202L);
+ Column column = mock(Column.class);
+ when(column.name()).thenReturn("order_id");
+ when(replacementTable.columns()).thenReturn(new Column[] {column});
+ when(tables.loadTable(any())).thenReturn(replacementTable);
+ SemanticModelDefinition replacement = original;
+ if (metricOnlyChange) {
+ Metric metric =
+ Metric.builder()
+ .withName("order_total")
+ .withExpression(expression(Dialects.ANSI_SQL, "COUNT(orders.order_id)"))
+ .withDatatype(DataType.DECIMAL)
+ .build();
+ replacement =
+ SemanticModelDefinition.builder()
+ .withDatasets(original.datasets())
+ .withMetrics(new Metric[] {metric})
+ .build();
+ }
+
+ Assertions.assertEquals(
+ Response.Status.OK.getStatusCode(), writeDefinition(true, replacement).getStatus());
+ verify(dispatcher)
+ .alterSemanticModel(
+ any(),
+ eq(
+ SemanticModelSourceUpdate.replace(
+ List.of(new SemanticModelSource("orders", EntityType.TABLE, 202L)))),
+ any(SemanticModelChange[].class));
+ verify(tables, times(2)).loadTable(NameIdentifier.of(metalake, catalog, schema, "orders"));
+ }
+
+ @Test
+ void testBatchReplacementUsesFinalDefinitionAssociations() {
+ when(dispatcher.alterSemanticModel(any(), any(), any(SemanticModelChange[].class)))
+ .thenReturn(semanticModel("sales", null));
+ SemanticModelDefinition finalDefinition =
+ SemanticModelDefinition.builder()
+ .withDatasets(
+ new Dataset[] {
+ Dataset.builder()
+ .withName("Final.Alias")
+ .withSource(NameIdentifier.of(catalog, schema, "orders"))
+ .build()
+ })
+ .build();
+ SemanticModelUpdatesRequest request =
+ new SemanticModelUpdatesRequest(
+ List.of(
+ new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(
+ SemanticModelDefinitionDTO.fromDefinition(semanticModelDefinition())),
+ new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest("Updated"),
+ new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(
+ SemanticModelDefinitionDTO.fromDefinition(finalDefinition)),
+ new SemanticModelUpdateRequest.SetSemanticModelPropertyRequest("owner", "sales")));
+
+ Assertions.assertEquals(
+ Response.Status.OK.getStatusCode(),
+ put(semanticModelPath() + "/sales", request).getStatus());
+ verify(dispatcher)
+ .alterSemanticModel(
+ any(),
+ eq(
+ SemanticModelSourceUpdate.replace(
+ List.of(new SemanticModelSource("Final.Alias", EntityType.TABLE, 101L)))),
+ any(SemanticModelChange[].class));
+ }
+
@Test
void testAlterSemanticModelRejectsNullBody() {
assertError(
@@ -672,7 +815,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
doThrow(new NoSuchSemanticModelException("sales does not exist"))
.when(dispatcher)
- .alterSemanticModel(eq(ident), any(SemanticModelChange[].class));
+ .alterSemanticModel(eq(ident), any(), any(SemanticModelChange[].class));
assertError(
put(semanticModelPath() + "/sales", request),
Response.Status.NOT_FOUND,
@@ -682,7 +825,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
doThrow(new OptimisticLockException("sales changed in this transaction"))
.when(dispatcher)
- .alterSemanticModel(eq(ident), any(SemanticModelChange[].class));
+ .alterSemanticModel(eq(ident), any(), any(SemanticModelChange[].class));
assertError(
put(semanticModelPath() + "/sales", request),
Response.Status.CONFLICT,
@@ -874,7 +1017,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void testMissingColumnWithAuthorizationDisabled(boolean replaceDefinition) {
- Table table = mock(Table.class);
+ Table table = registeredTable();
when(table.columns()).thenReturn(new Column[0]);
when(tables.loadTable(any())).thenReturn(table);
assertError(
@@ -941,9 +1084,9 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
when(tables.loadTable(fullSource)).thenThrow(new NoSuchTableException("missing table"));
when(views.loadView(fullSource)).thenThrow(new NoSuchViewException("missing view"));
}
- when(dispatcher.createSemanticModel(any(), any(), any(), any()))
+ when(dispatcher.createSemanticModel(any(), any(), any(), any(), any()))
.thenReturn(semanticModel("sales", null));
- when(dispatcher.alterSemanticModel(any(), any(SemanticModelChange[].class)))
+ when(dispatcher.alterSemanticModel(any(), any(), any(SemanticModelChange[].class)))
.thenReturn(semanticModel("sales", null));
Response response = writeDefinition(replaceDefinition, definition);
if (segment == 0) {
@@ -961,9 +1104,9 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
// Characterize existing behavior: resolvable names are not rejected solely for whitespace.
Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
if (replaceDefinition) {
- verify(dispatcher).alterSemanticModel(any(), any(SemanticModelChange[].class));
+ verify(dispatcher).alterSemanticModel(any(), any(), any(SemanticModelChange[].class));
} else {
- verify(dispatcher).createSemanticModel(any(), any(), eq(definition), any());
+ verify(dispatcher).createSemanticModel(any(), any(), eq(definition), any(), any());
}
verifyNoInteractions(views);
} else {
@@ -998,9 +1141,9 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
}
private void verifyNoModelWrites() {
- verify(dispatcher, never()).createSemanticModel(any(), any(), any(), any());
- verify(dispatcher, never()).importSemanticModel(any(), any(), any(), any());
- verify(dispatcher, never()).alterSemanticModel(any(), any(SemanticModelChange[].class));
+ verify(dispatcher, never()).createSemanticModel(any(), any(), any(), any(), any());
+ verify(dispatcher, never()).importSemanticModel(any(), any(), any(), any(), any());
+ verify(dispatcher, never()).alterSemanticModel(any(), any(), any(SemanticModelChange[].class));
}
private Response writeDefinition(boolean replaceDefinition, SemanticModelDefinition definition) {
@@ -1023,13 +1166,15 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(salesIdent),
eq("Sales definitions"),
any(SemanticModelDefinition.class),
- eq(Map.of("domain", "sales", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION))))
+ eq(Map.of("domain", "sales", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION)),
+ any()))
.thenReturn(semanticModel("sales", "Sales definitions"));
when(dispatcher.importSemanticModel(
eq(inventoryIdent),
eq(null),
any(SemanticModelDefinition.class),
- eq(Map.of(PROPERTY_OSSIE_VERSION, "future-version"))))
+ eq(Map.of(PROPERTY_OSSIE_VERSION, "future-version")),
+ any()))
.thenReturn(semanticModel("inventory", null));
String yaml =
@@ -1087,7 +1232,10 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(salesIdent),
eq("Sales definitions"),
definitionCaptor.capture(),
- eq(Map.of("domain", "sales", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION)));
+ eq(Map.of("domain", "sales", PROPERTY_OSSIE_VERSION, DEFAULT_VERSION)),
+ eq(
+ SemanticModelSourceUpdate.replace(
+ List.of(new SemanticModelSource("orders", EntityType.TABLE, 101L)))));
Assertions.assertEquals(
NameIdentifier.of(catalog, schema, "orders"),
definitionCaptor.getValue().datasets()[0].source());
@@ -1099,7 +1247,10 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(inventoryIdent),
eq(null),
any(SemanticModelDefinition.class),
- eq(Map.of(PROPERTY_OSSIE_VERSION, "future-version")));
+ eq(Map.of(PROPERTY_OSSIE_VERSION, "future-version")),
+ eq(
+ SemanticModelSourceUpdate.replace(
+ List.of(new SemanticModelSource("orders", EntityType.TABLE, 101L)))));
verify(dispatcher).importOssieDocument(eq(namespace), eq(OssieDocument.yaml(yaml)), any());
verify(dispatcher).importOssieDocument(eq(namespace), eq(OssieDocument.json(json)), any());
verifyNoMoreInteractions(dispatcher);
@@ -1113,7 +1264,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(ident),
eq(null),
any(SemanticModelDefinition.class),
- eq(Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION))))
+ eq(Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION)),
+ any()))
.thenReturn(semanticModel("marketing", null));
String yaml =
@@ -1136,7 +1288,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(ident),
eq(null),
any(SemanticModelDefinition.class),
- eq(Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION)));
+ eq(Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION)),
+ any());
verify(dispatcher).importOssieDocument(eq(namespace), eq(OssieDocument.yaml(yaml)), any());
verifyNoMoreInteractions(dispatcher);
}
@@ -1149,7 +1302,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(ident),
eq(null),
any(SemanticModelDefinition.class),
- eq(Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION))))
+ eq(Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION)),
+ any()))
.thenReturn(semanticModel("marketing", null));
String yaml =
@@ -1183,7 +1337,8 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
eq(ident),
eq(null),
any(SemanticModelDefinition.class),
- eq(Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION)));
+ eq(Map.of(PROPERTY_OSSIE_VERSION, DEFAULT_VERSION)),
+ any());
verify(dispatcher).importOssieDocument(eq(namespace), eq(OssieDocument.yaml(yaml)), any());
verifyNoMoreInteractions(dispatcher);
}
@@ -1295,7 +1450,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
+ " - name: orders\n source: sales.mart.orders\n";
doThrow(new SemanticModelAlreadyExistsException("sales already exists"))
.when(dispatcher)
- .importSemanticModel(eq(semanticModelIdentifier("sales")), eq(null), any(), any());
+ .importSemanticModel(eq(semanticModelIdentifier("sales")), eq(null), any(), any(), any());
assertError(
postDocument(semanticModelPath() + "/ossie", yaml, "application/yaml"),
Response.Status.CONFLICT,
@@ -1304,7 +1459,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
"sales already exists");
verify(dispatcher).importOssieDocument(eq(namespace), eq(OssieDocument.yaml(yaml)), any());
verify(dispatcher)
- .importSemanticModel(eq(semanticModelIdentifier("sales")), eq(null), any(), any());
+ .importSemanticModel(eq(semanticModelIdentifier("sales")), eq(null), any(), any(), any());
verifyNoMoreInteractions(dispatcher);
}
@@ -1345,7 +1500,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
tablesSupported = false;
viewsSupported = false;
}
- when(dispatcher.importSemanticModel(any(), any(), any(), any()))
+ when(dispatcher.importSemanticModel(any(), any(), any(), any(), any()))
.thenReturn(semanticModel("sales", null));
String document =
scenario.equals("invalid")
@@ -1364,7 +1519,7 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
Assertions.assertInstanceOf(ImportSemanticModelPreEvent.class, events.getAllValues().get(0));
if (status == 200) {
Assertions.assertInstanceOf(ImportSemanticModelEvent.class, events.getAllValues().get(1));
- verify(dispatcher).importSemanticModel(any(), any(), any(), any());
+ verify(dispatcher).importSemanticModel(any(), any(), any(), any(), any());
} else {
Assertions.assertInstanceOf(
ImportSemanticModelFailureEvent.class, events.getAllValues().get(1));
@@ -1543,4 +1698,16 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
Assertions.assertTrue(error.getMessage().contains(expectedMessageFragment));
return error;
}
+
+ private static Table registeredTable() {
+ return registeredTable(101L);
+ }
+
+ private static Table registeredTable(long sourceId) {
+ EntityCombinedTable table = mock(EntityCombinedTable.class);
+ TableEntity entity = mock(TableEntity.class);
+ when(entity.id()).thenReturn(sourceId);
+ when(table.tableFromGravitino()).thenReturn(entity);
+ return table;
+ }
}
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelSourceValidator.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelSourceValidator.java
index 3395c8827b..688af61c45 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelSourceValidator.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelSourceValidator.java
@@ -18,6 +18,7 @@
*/
package org.apache.gravitino.server.web.rest;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -33,15 +34,19 @@ import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import java.util.EnumSet;
+import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import org.apache.gravitino.Entity.EntityType;
import org.apache.gravitino.GravitinoEnv;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.StringIdentifier;
import org.apache.gravitino.authorization.GravitinoAuthorizer;
import org.apache.gravitino.authorization.Privilege;
import org.apache.gravitino.catalog.CatalogManager;
+import org.apache.gravitino.catalog.EntityCombinedTable;
+import org.apache.gravitino.catalog.EntityCombinedView;
import org.apache.gravitino.catalog.TableDispatcher;
import org.apache.gravitino.catalog.ViewDispatcher;
import org.apache.gravitino.connector.BaseCatalog;
@@ -51,6 +56,8 @@ import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.exceptions.IllegalSemanticModelException;
import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.exceptions.NoSuchViewException;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.ViewEntity;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.TableCatalog;
@@ -59,6 +66,7 @@ import org.apache.gravitino.rel.ViewCatalog;
import org.apache.gravitino.semantic.Dataset;
import org.apache.gravitino.semantic.Relationship;
import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.server.authorization.PassThroughAuthorizer;
import org.apache.gravitino.utils.ThrowableFunction;
import org.junit.jupiter.api.Test;
@@ -91,12 +99,101 @@ public class TestSemanticModelSourceValidator {
}
@Test
- void testViewFallbackAndColumns() {
+ void testManagedTableUsesIdentityFromLoadedProperties() {
+ Table managed = mock(Table.class);
+ doReturn(columns("id")).when(managed).columns();
+ when(managed.properties())
+ .thenReturn(StringIdentifier.newPropertiesWithId(StringIdentifier.fromId(303L), Map.of()));
+ EntityCombinedTable combined = EntityCombinedTable.of(managed).withImported(true);
+ when(tables.loadTable(FULL_SOURCE)).thenReturn(combined);
+ SemanticModelSourceUpdate update =
+ validator.validate("metalake", definition(dataset("orders", null, null)));
+ assertEquals(303L, update.sources().get(0).getSourceId());
+ assertEquals(EntityType.TABLE, update.sources().get(0).getSourceType());
+ verify(tables).loadTable(FULL_SOURCE);
+ verifyNoInteractions(views);
+
+ // An unregistered external table's connector property is not a registered identity.
+ combined.withImported(false);
+ assertThrows(
+ IllegalStateException.class,
+ () -> validator.validate("metalake", definition(dataset("orders", null, null))));
+ }
+
+ @Test
+ void testTableWithoutRegisteredIdentityIsRejected() {
+ Table table = mock(Table.class);
+ doReturn(columns("id")).when(table).columns();
+ when(tables.loadTable(FULL_SOURCE)).thenReturn(table);
+ assertThrows(
+ IllegalStateException.class,
+ () -> validator.validate("metalake", definition(dataset("orders", null, null))));
+
+ when(tables.loadTable(FULL_SOURCE))
+ .thenReturn(EntityCombinedTable.of(table).withImported(true));
+ when(table.properties()).thenReturn(Map.of());
+ assertThrows(
+ IllegalStateException.class,
+ () -> validator.validate("metalake", definition(dataset("orders", null, null))));
+ verifyNoInteractions(views);
+ }
+
+ @Test
+ void testViewWithoutRegisteredIdentityIsRejected() {
when(tables.loadTable(FULL_SOURCE)).thenThrow(new NoSuchTableException("missing"));
View view = mock(View.class);
doReturn(columns("id")).when(view).columns();
when(views.loadView(FULL_SOURCE)).thenReturn(view);
- validator.validate("metalake", definition(dataset("orders", new String[] {"id"}, null)));
+ assertThrows(
+ IllegalStateException.class,
+ () -> validator.validate("metalake", definition(dataset("orders", null, null))));
+
+ EntityCombinedView combined = mock(EntityCombinedView.class);
+ doReturn(columns("id")).when(combined).columns();
+ when(views.loadView(FULL_SOURCE)).thenReturn(combined);
+ assertThrows(
+ IllegalStateException.class,
+ () -> validator.validate("metalake", definition(dataset("orders", null, null))));
+ }
+
+ @Test
+ void testManagedViewUsesIdentityFromLoadedProperties() {
+ when(tables.loadTable(FULL_SOURCE)).thenThrow(new NoSuchTableException("missing"));
+ View managed = mock(View.class);
+ doReturn(columns("id")).when(managed).columns();
+ when(managed.properties())
+ .thenReturn(StringIdentifier.newPropertiesWithId(StringIdentifier.fromId(404L), Map.of()));
+ EntityCombinedView combined = EntityCombinedView.of(managed).withImported(true);
+ when(views.loadView(FULL_SOURCE)).thenReturn(combined);
+
+ SemanticModelSourceUpdate update =
+ validator.validate("metalake", definition(dataset("orders", null, null)));
+ assertEquals(404L, update.sources().get(0).getSourceId());
+ assertEquals(EntityType.VIEW, update.sources().get(0).getSourceType());
+
+ combined.withImported(false);
+ assertThrows(
+ IllegalStateException.class,
+ () -> validator.validate("metalake", definition(dataset("orders", null, null))));
+
+ combined.withImported(true);
+ when(managed.properties()).thenReturn(Map.of());
+ assertThrows(
+ IllegalStateException.class,
+ () -> validator.validate("metalake", definition(dataset("orders", null, null))));
+ }
+
+ @Test
+ void testViewFallbackAndColumns() {
+ when(tables.loadTable(FULL_SOURCE)).thenThrow(new NoSuchTableException("missing"));
+ View view = registeredView();
+ doReturn(columns("id")).when(view).columns();
+ when(views.loadView(FULL_SOURCE)).thenReturn(view);
+ SemanticModelSourceUpdate update =
+ validator.validate("metalake", definition(dataset("orders", new String[] {"id"}, null)));
+ assertEquals(1, update.sources().size());
+ assertEquals(202L, update.sources().get(0).getSourceId());
+ assertEquals(EntityType.VIEW, update.sources().get(0).getSourceType());
assertThrows(
IllegalSemanticModelException.class,
() ->
@@ -124,7 +221,13 @@ public class TestSemanticModelSourceValidator {
Dataset first = dataset("orders", null, null);
Dataset second = dataset("customers", null, null);
SemanticModelDefinition valid = related(first, second, "id", "id");
- validator.validate("metalake", valid);
+ SemanticModelSourceUpdate update = validator.validate("metalake", valid);
+ assertEquals(2, update.sources().size());
+ assertEquals(101L, update.sources().get(0).getSourceId());
+ assertEquals(101L, update.sources().get(1).getSourceId());
+ assertEquals(EntityType.TABLE, update.sources().get(0).getSourceType());
+ assertEquals("orders", update.sources().get(0).getDatasetName());
+ assertEquals("customers", update.sources().get(1).getDatasetName());
verify(tables, times(1)).loadTable(FULL_SOURCE);
assertThrows(
IllegalSemanticModelException.class,
@@ -137,7 +240,7 @@ public class TestSemanticModelSourceValidator {
@Test
void testDeniedTableCanResolveAuthorizedViewWithoutTableLookup() {
authorizeOnly(MetadataObject.Type.VIEW, Privilege.Name.SELECT_VIEW);
- View view = mock(View.class);
+ View view = registeredView();
doReturn(columns("id")).when(view).columns();
when(views.loadView(FULL_SOURCE)).thenReturn(view);
validator.validate("metalake", definition(dataset("orders", null, null)));
@@ -255,7 +358,7 @@ public class TestSemanticModelSourceValidator {
@Test
void testViewOnlyCatalogCanResolveSourceWithoutTableLookup() {
authorizeOnly(MetadataObject.Type.VIEW, Privilege.Name.SELECT_VIEW);
- View view = mock(View.class);
+ View view = registeredView();
doReturn(columns("id")).when(view).columns();
when(views.loadView(FULL_SOURCE)).thenReturn(view);
SemanticModelSourceValidator checking =
@@ -316,7 +419,7 @@ public class TestSemanticModelSourceValidator {
}
private Table table(String... names) {
- Table table = mock(Table.class);
+ Table table = registeredTable();
doReturn(columns(names)).when(table).columns();
when(tables.loadTable(FULL_SOURCE)).thenReturn(table);
return table;
@@ -359,4 +462,20 @@ public class TestSemanticModelSourceValidator {
})
.build();
}
+
+ private static Table registeredTable() {
+ EntityCombinedTable table = mock(EntityCombinedTable.class);
+ TableEntity entity = mock(TableEntity.class);
+ when(entity.id()).thenReturn(101L);
+ when(table.tableFromGravitino()).thenReturn(entity);
+ return table;
+ }
+
+ private static View registeredView() {
+ EntityCombinedView view = mock(EntityCombinedView.class);
+ ViewEntity entity = mock(ViewEntity.class);
+ when(entity.id()).thenReturn(202L);
+ when(view.viewEntity()).thenReturn(entity);
+ return view;
+ }
}