Skip to content

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

[#14820] feat(server): List Semantic Model datasets by source (#14822)

mchades6b394f3c1ab1
diff --git a/core/src/main/java/org/apache/gravitino/SupportsRelationOperations.java b/core/src/main/java/org/apache/gravitino/SupportsRelationOperations.java
index 97e0105873..f8d8655926 100644
--- a/core/src/main/java/org/apache/gravitino/SupportsRelationOperations.java
+++ b/core/src/main/java/org/apache/gravitino/SupportsRelationOperations.java
@@ -43,6 +43,8 @@ public interface SupportsRelationOperations {
TAG_METADATA_OBJECT_REL,
/** Policy to tag relationship */
POLICY_TAG_REL,
+ /** Semantic Model dataset to source relationship. */
+ SEMANTIC_MODEL_SOURCE_REL,
}
/**
diff --git a/core/src/main/java/org/apache/gravitino/audit/AuditLog.java b/core/src/main/java/org/apache/gravitino/audit/AuditLog.java
index a82c3f1923..c74f8cdaec 100644
--- a/core/src/main/java/org/apache/gravitino/audit/AuditLog.java
+++ b/core/src/main/java/org/apache/gravitino/audit/AuditLog.java
@@ -121,6 +121,8 @@ import org.apache.gravitino.listener.api.event.semantic.ExportSemanticModelEvent
import org.apache.gravitino.listener.api.event.semantic.ExportSemanticModelFailureEvent;
import org.apache.gravitino.listener.api.event.semantic.ImportSemanticModelEvent;
import org.apache.gravitino.listener.api.event.semantic.ImportSemanticModelFailureEvent;
+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelDatasetsBySourceEvent;
+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelDatasetsBySourceFailureEvent;
import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelEvent;
import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelFailureEvent;
import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricEvent;
@@ -543,6 +545,8 @@ public interface AuditLog {
LIST_SEMANTIC_MODEL,
/** List identifiers of metrics contained in Semantic Models. */
LIST_SEMANTIC_MODEL_METRIC,
+ /** Lists datasets associated with a source table or View. */
+ LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE,
/** List complete metrics contained in Semantic Models. */
LIST_SEMANTIC_MODEL_METRIC_INFOS,
/** Import a Semantic Model from an Ossie document. */
@@ -672,6 +676,9 @@ public interface AuditLog {
} else if (event instanceof ListSemanticModelEvent
|| event instanceof ListSemanticModelFailureEvent) {
return LIST_SEMANTIC_MODEL;
+ } else if (event instanceof ListSemanticModelDatasetsBySourceEvent
+ || event instanceof ListSemanticModelDatasetsBySourceFailureEvent) {
+ return LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE;
} else if (event instanceof ListSemanticModelMetricEvent
|| event instanceof ListSemanticModelMetricFailureEvent) {
return LIST_SEMANTIC_MODEL_METRIC;
diff --git a/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java b/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java
index 5881010fc9..8a5fa5ece0 100644
--- a/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java
+++ b/core/src/main/java/org/apache/gravitino/audit/v2/CompatibilityUtils.java
@@ -203,6 +203,9 @@ public class CompatibilityUtils {
.put(OperationType.LOAD_SEMANTIC_MODEL, Operation.LOAD_SEMANTIC_MODEL)
.put(OperationType.LIST_SEMANTIC_MODEL, Operation.LIST_SEMANTIC_MODEL)
.put(OperationType.LIST_SEMANTIC_MODEL_METRIC, Operation.LIST_SEMANTIC_MODEL_METRIC)
+ .put(
+ OperationType.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE,
+ Operation.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE)
.put(
OperationType.LIST_SEMANTIC_MODEL_METRIC_INFOS,
Operation.LIST_SEMANTIC_MODEL_METRIC_INFOS)
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 2836f0bd89..b57964e32a 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelDispatcher.java
@@ -23,9 +23,11 @@ import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import javax.annotation.Nullable;
+import org.apache.gravitino.Entity;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.exceptions.IllegalSemanticModelException;
+import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NoSuchSemanticModelException;
import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;
@@ -39,9 +41,19 @@ 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. */
+/** Dispatches Semantic Model operations through the server pipeline. */
public interface SemanticModelDispatcher {
+ /**
+ * Lists datasets directly associated with a table or View.
+ *
+ * @param source The fully qualified source identifier.
+ * @param sourceType TABLE or VIEW.
+ * @return Fully qualified dataset identifiers sorted by their components.
+ * @throws NoSuchMetadataObjectException If the source does not exist.
+ */
+ NameIdentifier[] listSemanticModelDatasets(NameIdentifier source, Entity.EntityType sourceType);
+
/**
* Lists the Semantic Models in a schema namespace.
*
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 8866f80ab3..ec4cfbcfc0 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelNormalizeDispatcher.java
@@ -22,11 +22,13 @@ import static org.apache.gravitino.catalog.CapabilityHelpers.applyCapabilities;
import static org.apache.gravitino.catalog.CapabilityHelpers.applyCapabilitiesOnName;
import static org.apache.gravitino.catalog.CapabilityHelpers.applyCaseSensitive;
import static org.apache.gravitino.catalog.CapabilityHelpers.getCapability;
+import static org.apache.gravitino.catalog.CapabilityHelpers.resolvePhysicalTableName;
import com.google.common.base.Preconditions;
import java.util.Arrays;
import java.util.Map;
import javax.annotation.Nullable;
+import org.apache.gravitino.Entity;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.connector.capability.Capability;
@@ -60,6 +62,22 @@ public class SemanticModelNormalizeDispatcher implements SemanticModelDispatcher
this.catalogManager = catalogManager;
}
+ @Override
+ public NameIdentifier[] listSemanticModelDatasets(
+ NameIdentifier source, Entity.EntityType sourceType) {
+ Preconditions.checkArgument(
+ sourceType == Entity.EntityType.TABLE || sourceType == Entity.EntityType.VIEW,
+ "Source must be a table or View");
+ Capability capability = getCapability(source, catalogManager);
+ Capability.Scope scope =
+ sourceType == Entity.EntityType.TABLE ? Capability.Scope.TABLE : Capability.Scope.VIEW;
+ NameIdentifier normalized = applyCaseSensitive(source, scope, capability);
+ if (sourceType == Entity.EntityType.TABLE) {
+ normalized = resolvePhysicalTableName(normalized, catalogManager);
+ }
+ return dispatcher.listSemanticModelDatasets(normalized, sourceType);
+ }
+
@Override
public NameIdentifier[] listSemanticModels(Namespace namespace) throws NoSuchSchemaException {
return dispatcher.listSemanticModels(normalizeParentForLookup(namespace));
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 ed6918d834..40d9b03509 100644
--- a/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/catalog/SemanticModelOperationDispatcher.java
@@ -23,17 +23,28 @@ import static org.apache.gravitino.catalog.PropertiesMetadataHelpers.validatePro
import static org.apache.gravitino.semantic.SemanticModel.PROPERTY_OSSIE_VERSION;
import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Comparator;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
+import org.apache.commons.lang3.ArrayUtils;
import org.apache.gravitino.Catalog;
+import org.apache.gravitino.Entity;
import org.apache.gravitino.EntityStore;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
+import org.apache.gravitino.RelationQuery;
+import org.apache.gravitino.SupportsRelationOperations;
import org.apache.gravitino.exceptions.IllegalSemanticModelException;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NoSuchSemanticModelException;
import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;
+import org.apache.gravitino.meta.SemanticModelDatasetListing;
import org.apache.gravitino.secret.SecretManager;
import org.apache.gravitino.semantic.OssieDocument;
import org.apache.gravitino.semantic.OssieDocumentConverter;
@@ -45,6 +56,8 @@ import org.apache.gravitino.semantic.SemanticModelMetric;
import org.apache.gravitino.semantic.SemanticModelPropertiesMetadata;
import org.apache.gravitino.semantic.SemanticModelSourceUpdate;
import org.apache.gravitino.storage.IdGenerator;
+import org.apache.gravitino.utils.MetadataObjectUtil;
+import org.apache.gravitino.utils.NameIdentifierUtil;
/** Dispatches always-managed Semantic Model operations to Gravitino's EntityStore. */
public class SemanticModelOperationDispatcher extends OperationDispatcher
@@ -82,6 +95,48 @@ public class SemanticModelOperationDispatcher extends OperationDispatcher
(ident, definition) -> SemanticModelValidator.validateDefinition(definition));
}
+ @Override
+ public NameIdentifier[] listSemanticModelDatasets(
+ NameIdentifier source, Entity.EntityType sourceType) {
+ Preconditions.checkArgument(
+ sourceType == Entity.EntityType.TABLE || sourceType == Entity.EntityType.VIEW,
+ "Source must be a table or View");
+ MetadataObjectUtil.checkMetadataObject(
+ source.namespace().level(0), NameIdentifierUtil.toMetadataObject(source, sourceType));
+ try {
+ List<SemanticModelDatasetListing> models =
+ store
+ .relationOperations()
+ .listEntitiesByRelation(
+ RelationQuery.of(
+ SupportsRelationOperations.Type.SEMANTIC_MODEL_SOURCE_REL,
+ source,
+ sourceType,
+ false,
+ null));
+ return models.stream()
+ .flatMap(
+ model ->
+ model.datasets().stream()
+ .map(
+ dataset ->
+ NameIdentifier.of(
+ Namespace.of(
+ ArrayUtils.add(model.namespace().levels(), model.name())),
+ dataset)))
+ .distinct()
+ .sorted(
+ Comparator.comparing(
+ (NameIdentifier ident) -> ident.namespace().levels(), Arrays::compare)
+ .thenComparing(NameIdentifier::name))
+ .toArray(NameIdentifier[]::new);
+ } catch (NoSuchEntityException e) {
+ throw new NoSuchMetadataObjectException(e, "Source %s does not exist", source);
+ } catch (IOException e) {
+ throw new RuntimeException("Failed to list Semantic Model datasets for source " + source, e);
+ }
+ }
+
@Override
public NameIdentifier[] listSemanticModels(Namespace namespace) throws NoSuchSchemaException {
checkRelationalCatalog(namespace);
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 f69b58c1d6..47c35c23b9 100644
--- a/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/hook/SemanticModelHookDispatcher.java
@@ -65,6 +65,12 @@ public class SemanticModelHookDispatcher implements SemanticModelDispatcher {
this.ownerDispatcher = ownerDispatcher;
}
+ @Override
+ public NameIdentifier[] listSemanticModelDatasets(
+ NameIdentifier source, Entity.EntityType sourceType) {
+ return dispatcher.listSemanticModelDatasets(source, sourceType);
+ }
+
@Override
public NameIdentifier[] listSemanticModels(Namespace namespace) throws NoSuchSchemaException {
return dispatcher.listSemanticModels(namespace);
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 9de6ffd2a9..de0330c437 100644
--- a/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/listener/SemanticModelEventDispatcher.java
@@ -22,6 +22,8 @@ package org.apache.gravitino.listener;
import java.util.Map;
import java.util.function.Function;
import javax.annotation.Nullable;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.catalog.SemanticModelDispatcher;
@@ -45,6 +47,9 @@ import org.apache.gravitino.listener.api.event.semantic.ExportSemanticModelPreEv
import org.apache.gravitino.listener.api.event.semantic.ImportSemanticModelEvent;
import org.apache.gravitino.listener.api.event.semantic.ImportSemanticModelFailureEvent;
import org.apache.gravitino.listener.api.event.semantic.ImportSemanticModelPreEvent;
+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelDatasetsBySourceEvent;
+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelDatasetsBySourceFailureEvent;
+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelDatasetsBySourcePreEvent;
import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelEvent;
import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelFailureEvent;
import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelMetricEvent;
@@ -88,6 +93,24 @@ public class SemanticModelEventDispatcher implements SemanticModelDispatcher {
this.dispatcher = dispatcher;
}
+ @Override
+ public NameIdentifier[] listSemanticModelDatasets(
+ NameIdentifier source, Entity.EntityType sourceType) {
+ String user = PrincipalUtils.getCurrentUserName();
+ MetadataObject.Type type = MetadataObject.Type.valueOf(sourceType.name());
+ eventBus.dispatchEvent(new ListSemanticModelDatasetsBySourcePreEvent(user, source, type));
+ try {
+ NameIdentifier[] datasets = dispatcher.listSemanticModelDatasets(source, sourceType);
+ eventBus.dispatchEvent(
+ new ListSemanticModelDatasetsBySourceEvent(user, source, type, datasets.length));
+ return datasets;
+ } catch (Exception e) {
+ eventBus.dispatchEvent(
+ new ListSemanticModelDatasetsBySourceFailureEvent(user, source, type, e));
+ throw e;
+ }
+ }
+
@Override
public NameIdentifier[] listSemanticModels(Namespace namespace) throws NoSuchSchemaException {
String user = PrincipalUtils.getCurrentUserName();
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java b/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java
index 9c23e70ce4..9e4e16d60e 100644
--- a/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java
+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/OperationType.java
@@ -219,6 +219,8 @@ public enum OperationType {
LIST_SEMANTIC_MODEL,
/** List identifiers of metrics contained in Semantic Models. */
LIST_SEMANTIC_MODEL_METRIC,
+ /** Lists datasets associated with a source table or View. */
+ LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE,
/** List complete metrics contained in Semantic Models. */
LIST_SEMANTIC_MODEL_METRIC_INFOS,
/** Import a Semantic Model from an Ossie document. */
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelDatasetsBySourceEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelDatasetsBySourceEvent.java
new file mode 100644
index 0000000000..2fc422f5c9
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelDatasetsBySourceEvent.java
@@ -0,0 +1,65 @@
+/*
+ * 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.listener.api.event.semantic;
+
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.annotation.DeveloperApi;
+import org.apache.gravitino.listener.api.event.ListEvent;
+import org.apache.gravitino.listener.api.event.OperationType;
+
+/** Source-scoped Semantic Model dataset lookup event. */
+@DeveloperApi
+public final class ListSemanticModelDatasetsBySourceEvent extends SemanticModelEvent
+ implements ListEvent {
+ private final MetadataObject.Type sourceType;
+ private final int count;
+
+ /**
+ * Creates a dataset lookup event.
+ *
+ * @param user The caller.
+ * @param source The fully qualified source identifier.
+ * @param sourceType The queried table or View type.
+ * @param count The number of matching dataset identifiers.
+ */
+ public ListSemanticModelDatasetsBySourceEvent(
+ String user, NameIdentifier source, MetadataObject.Type sourceType, int count) {
+ super(user, source);
+ this.sourceType = sourceType;
+ this.count = count;
+ }
+
+ /**
+ * @return The type of the source associated with this lookup.
+ */
+ public MetadataObject.Type sourceType() {
+ return sourceType;
+ }
+
+ @Override
+ public int resultCount() {
+ return count;
+ }
+
+ @Override
+ public OperationType operationType() {
+ return OperationType.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE;
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelDatasetsBySourceFailureEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelDatasetsBySourceFailureEvent.java
new file mode 100644
index 0000000000..2d60a06ef7
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelDatasetsBySourceFailureEvent.java
@@ -0,0 +1,56 @@
+/*
+ * 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.listener.api.event.semantic;
+
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.annotation.DeveloperApi;
+import org.apache.gravitino.listener.api.event.OperationType;
+
+/** Source-scoped Semantic Model dataset lookup failure event. */
+@DeveloperApi
+public final class ListSemanticModelDatasetsBySourceFailureEvent extends SemanticModelFailureEvent {
+ private final MetadataObject.Type sourceType;
+
+ /**
+ * Creates a dataset lookup event.
+ *
+ * @param user The caller.
+ * @param source The fully qualified source identifier.
+ * @param sourceType The queried table or View type.
+ * @param exception The failure.
+ */
+ public ListSemanticModelDatasetsBySourceFailureEvent(
+ String user, NameIdentifier source, MetadataObject.Type sourceType, Exception exception) {
+ super(user, source, exception);
+ this.sourceType = sourceType;
+ }
+
+ /**
+ * @return The type of the source associated with this lookup.
+ */
+ public MetadataObject.Type sourceType() {
+ return sourceType;
+ }
+
+ @Override
+ public OperationType operationType() {
+ return OperationType.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE;
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelDatasetsBySourcePreEvent.java b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelDatasetsBySourcePreEvent.java
new file mode 100644
index 0000000000..20a469515c
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/listener/api/event/semantic/ListSemanticModelDatasetsBySourcePreEvent.java
@@ -0,0 +1,55 @@
+/*
+ * 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.listener.api.event.semantic;
+
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.annotation.DeveloperApi;
+import org.apache.gravitino.listener.api.event.OperationType;
+
+/** Source-scoped Semantic Model dataset lookup pre-event. */
+@DeveloperApi
+public final class ListSemanticModelDatasetsBySourcePreEvent extends SemanticModelPreEvent {
+ private final MetadataObject.Type sourceType;
+
+ /**
+ * Creates a dataset lookup event.
+ *
+ * @param user The caller.
+ * @param source The fully qualified source identifier.
+ * @param sourceType The queried table or View type.
+ */
+ public ListSemanticModelDatasetsBySourcePreEvent(
+ String user, NameIdentifier source, MetadataObject.Type sourceType) {
+ super(user, source);
+ this.sourceType = sourceType;
+ }
+
+ /**
+ * @return The type of the source associated with this lookup.
+ */
+ public MetadataObject.Type sourceType() {
+ return sourceType;
+ }
+
+ @Override
+ public OperationType operationType() {
+ return OperationType.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE;
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/meta/SemanticModelDatasetListing.java b/core/src/main/java/org/apache/gravitino/meta/SemanticModelDatasetListing.java
new file mode 100644
index 0000000000..098955f86e
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/meta/SemanticModelDatasetListing.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.meta;
+
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.Field;
+import org.apache.gravitino.HasIdentifier;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+
+/** A current model identifier and its matching datasets, without loading its definition. */
+public final class SemanticModelDatasetListing implements Entity, HasIdentifier {
+ private final Long id;
+ private final NameIdentifier identifier;
+ private final List<String> datasets;
+
+ /**
+ * Creates a relation-query result.
+ *
+ * @param id The containing model ID.
+ * @param identifier The current fully qualified model identifier.
+ * @param datasets Matching exact dataset names.
+ */
+ public SemanticModelDatasetListing(Long id, NameIdentifier identifier, List<String> datasets) {
+ this.id = id;
+ this.identifier = identifier;
+ this.datasets = List.copyOf(datasets);
+ }
+
+ /**
+ * @return Matching dataset names in the current definition.
+ */
+ public List<String> datasets() {
+ return datasets;
+ }
+
+ @Override
+ public Long id() {
+ return id;
+ }
+
+ @Override
+ public String name() {
+ return identifier.name();
+ }
+
+ @Override
+ public Namespace namespace() {
+ return identifier.namespace();
+ }
+
+ @Override
+ public EntityType type() {
+ return EntityType.SEMANTIC_MODEL;
+ }
+
+ @Override
+ public Map<Field, Object> fields() {
+ return Map.of(
+ SemanticModelEntity.ID,
+ id,
+ SemanticModelEntity.NAME,
+ name(),
+ SemanticModelEntity.NAMESPACE,
+ namespace());
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
index d346b30fbc..6615a651ac 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
@@ -92,6 +92,7 @@ import org.apache.gravitino.storage.relational.service.RoleMetaService;
import org.apache.gravitino.storage.relational.service.SchemaMetaService;
import org.apache.gravitino.storage.relational.service.SemanticModelMetaService;
import org.apache.gravitino.storage.relational.service.SemanticModelMetricService;
+import org.apache.gravitino.storage.relational.service.SemanticModelSourceService;
import org.apache.gravitino.storage.relational.service.StatisticMetaService;
import org.apache.gravitino.storage.relational.service.TableColumnMetaService;
import org.apache.gravitino.storage.relational.service.TableMetaService;
@@ -721,6 +722,9 @@ public class JDBCBackend implements RelationalBackend, SupportsOrphanedRelationC
return (List<E>)
TagMetaService.getInstance().listTagsForMetadataObject(nameIdentifier, identType);
}
+ case SEMANTIC_MODEL_SOURCE_REL:
+ return (List<E>)
+ SemanticModelSourceService.getInstance().listForSource(nameIdentifier, identType);
case POLICY_TAG_REL:
return (List<E>)
PolicyTagRelService.getInstance()
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelSourceMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelSourceMapper.java
index a325649cf1..c089751f53 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelSourceMapper.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/SemanticModelSourceMapper.java
@@ -20,12 +20,14 @@ package org.apache.gravitino.storage.relational.mapper;
import java.util.List;
import org.apache.gravitino.semantic.SemanticModelSource;
+import org.apache.gravitino.storage.relational.po.SemanticModelSourceListingPO;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.UpdateProvider;
-/** Persists dataset-to-source associations and their retirement state. */
+/** Reads and persists dataset-to-source associations and their retirement state. */
public interface SemanticModelSourceMapper {
/** The dataset source association table name. */
String TABLE_NAME = "semantic_model_source_rel";
@@ -74,4 +76,22 @@ public interface SemanticModelSourceMapper {
method = "deleteByLegacyTimeline")
int deleteByLegacyTimeline(
@Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit);
+
+ /** Reads live models and matching datasets with current parent names in a single statement. */
+ @Select(
+ """
+ SELECT model.semantic_model_id AS semanticModelId, model.semantic_model_name AS semanticModelName,
+ metalake.metalake_name AS metalakeName, catalog.catalog_name AS catalogName,
+ schema_meta.schema_name AS schemaName, rel.dataset_name AS datasetName
+ FROM semantic_model_source_rel rel
+ JOIN semantic_model_meta model ON model.semantic_model_id = rel.semantic_model_id AND model.deleted_at = 0
+ JOIN schema_meta ON schema_meta.schema_id = model.schema_id AND schema_meta.deleted_at = 0
+ JOIN catalog_meta catalog ON catalog.catalog_id = model.catalog_id AND catalog.deleted_at = 0
+ JOIN metalake_meta metalake ON metalake.metalake_id = rel.metalake_id AND metalake.deleted_at = 0
+ WHERE rel.deleted_at = 0 AND rel.metalake_id = #{metalakeId} AND rel.source_type = #{sourceType} AND rel.source_id = #{sourceId}
+ """)
+ List<SemanticModelSourceListingPO> listForSource(
+ @Param("metalakeId") long metalakeId,
+ @Param("sourceType") String sourceType,
+ @Param("sourceId") long sourceId);
}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelSourceListingPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelSourceListingPO.java
new file mode 100644
index 0000000000..a8eb3bd1ae
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelSourceListingPO.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.po;
+
+import lombok.Getter;
+
+/** A current model's namespace and exact matching dataset name. */
+@Getter
+public class SemanticModelSourceListingPO {
+ private Long semanticModelId;
+ private String metalakeName;
+ private String catalogName;
+ private String schemaName;
+ private String semanticModelName;
+ private String datasetName;
+
+ /** Creates an empty projection for MyBatis. */
+ public SemanticModelSourceListingPO() {}
+}
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelSourceService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelSourceService.java
new file mode 100644
index 0000000000..4a1eba2006
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelSourceService.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelDatasetListing;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelSourceMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelSourceListingPO;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.HierarchicalSchemaUtil;
+
+/** Indexed reverse lookup of current Semantic Model datasets. */
+public final class SemanticModelSourceService {
+ private static final SemanticModelSourceService INSTANCE = new SemanticModelSourceService();
+
+ private SemanticModelSourceService() {}
+
+ /**
+ * @return The singleton source association service.
+ */
+ public static SemanticModelSourceService getInstance() {
+ return INSTANCE;
+ }
+
+ /**
+ * Lists the live model projections directly associated with an existing registered source.
+ *
+ * @param source The full source identifier.
+ * @param type TABLE or VIEW.
+ * @return One projection per matching model.
+ * @throws NoSuchEntityException If the source or one of its parents does not exist.
+ */
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "listSemanticModelDatasetsBySource")
+ public List<SemanticModelDatasetListing> listForSource(
+ NameIdentifier source, Entity.EntityType type) {
+ Preconditions.checkArgument(
+ type == Entity.EntityType.TABLE || type == Entity.EntityType.VIEW,
+ "Source must be a table or View");
+ long sourceId = EntityIdService.getEntityId(source, type);
+ long metalakeId =
+ EntityIdService.getEntityId(
+ NameIdentifier.of(source.namespace().level(0)), Entity.EntityType.METALAKE);
+ List<SemanticModelSourceListingPO> rows =
+ SessionUtils.getWithoutCommit(
+ SemanticModelSourceMapper.class,
+ mapper -> mapper.listForSource(metalakeId, type.name(), sourceId));
+ Map<Long, List<SemanticModelSourceListingPO>> groups = new LinkedHashMap<>();
+ rows.forEach(
+ row -> groups.computeIfAbsent(row.getSemanticModelId(), key -> new ArrayList<>()).add(row));
+ List<SemanticModelDatasetListing> result = new ArrayList<>();
+ groups.forEach(
+ (id, matches) -> {
+ SemanticModelSourceListingPO first = matches.get(0);
+ NameIdentifier model =
+ NameIdentifier.of(
+ first.getMetalakeName(),
+ first.getCatalogName(),
+ HierarchicalSchemaUtil.physicalToLogical(
+ first.getSchemaName(), HierarchicalSchemaUtil.schemaSeparator()),
+ first.getSemanticModelName());
+ result.add(
+ new SemanticModelDatasetListing(
+ id,
+ model,
+ matches.stream()
+ .map(SemanticModelSourceListingPO::getDatasetName)
+ .distinct()
+ .toList()));
+ });
+ return result;
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/audit/v2/TestCompatibilityUtils.java b/core/src/test/java/org/apache/gravitino/audit/v2/TestCompatibilityUtils.java
index 1ae072da2c..f436427462 100644
--- a/core/src/test/java/org/apache/gravitino/audit/v2/TestCompatibilityUtils.java
+++ b/core/src/test/java/org/apache/gravitino/audit/v2/TestCompatibilityUtils.java
@@ -204,6 +204,10 @@ public class TestCompatibilityUtils {
{OperationType.DROP_SEMANTIC_MODEL, Operation.DROP_SEMANTIC_MODEL},
{OperationType.LOAD_SEMANTIC_MODEL, Operation.LOAD_SEMANTIC_MODEL},
{OperationType.LIST_SEMANTIC_MODEL, Operation.LIST_SEMANTIC_MODEL},
+ {
+ OperationType.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE,
+ Operation.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE
+ },
{OperationType.LIST_SEMANTIC_MODEL_METRIC, Operation.LIST_SEMANTIC_MODEL_METRIC},
{OperationType.LIST_SEMANTIC_MODEL_METRIC_INFOS, Operation.LIST_SEMANTIC_MODEL_METRIC_INFOS},
{OperationType.IMPORT_SEMANTIC_MODEL, Operation.IMPORT_SEMANTIC_MODEL},
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 e2034a33d4..9c780c5524 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelNormalizeDispatcher.java
@@ -33,12 +33,16 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.withSettings;
import java.util.Locale;
import java.util.Map;
+import org.apache.gravitino.Entity;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.connector.BaseCatalog;
+import org.apache.gravitino.connector.CatalogOperations;
+import org.apache.gravitino.connector.SupportsTableNameResolution;
import org.apache.gravitino.connector.capability.Capability;
import org.apache.gravitino.connector.capability.CapabilityResult;
import org.apache.gravitino.semantic.Dataset;
@@ -77,6 +81,50 @@ public class TestSemanticModelNormalizeDispatcher {
dispatcher = new SemanticModelNormalizeDispatcher(delegate, catalogManager);
}
+ @Test
+ public void testSourceLookupUsesTableAndViewNamingRules() {
+ NameIdentifier source = NameIdentifier.of(INPUT_NAMESPACE, "Orders");
+ NameIdentifier[] datasets = {NameIdentifier.of("metalake", "other", "schema", "Model", "a")};
+ for (Entity.EntityType type :
+ new Entity.EntityType[] {Entity.EntityType.TABLE, Entity.EntityType.VIEW}) {
+ NameIdentifier normalized =
+ NameIdentifier.of(
+ NORMALIZED_NAMESPACE, type == Entity.EntityType.TABLE ? "orders" : "ORDERS");
+ when(delegate.listSemanticModelDatasets(normalized, type)).thenReturn(datasets);
+ assertSame(datasets, dispatcher.listSemanticModelDatasets(source, type));
+ verify(delegate).listSemanticModelDatasets(normalized, type);
+ }
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> dispatcher.listSemanticModelDatasets(source, Entity.EntityType.SCHEMA));
+ verifyNoMoreInteractions(delegate);
+ }
+
+ @Test
+ public void testSourceLookupResolvesPhysicalTableName() throws Exception {
+ CatalogManager manager = mock(CatalogManager.class);
+ BaseCatalog<?> catalog = mock(BaseCatalog.class);
+ CatalogOperations operations =
+ mock(
+ CatalogOperations.class,
+ withSettings().extraInterfaces(SupportsTableNameResolution.class));
+ when(catalog.ops()).thenReturn(operations);
+ when(catalog.capability()).thenReturn(new ParentNormalizingCapability());
+ CatalogTestUtils.mockDoWithCatalog(manager, catalog);
+ SemanticModelNormalizeDispatcher normalizer =
+ new SemanticModelNormalizeDispatcher(delegate, manager);
+ NameIdentifier source = NameIdentifier.of(INPUT_NAMESPACE, "orders");
+ NameIdentifier normalized = NameIdentifier.of(NORMALIZED_NAMESPACE, "orders");
+ NameIdentifier physical = NameIdentifier.of(NORMALIZED_NAMESPACE, "ORDERS");
+ when(((SupportsTableNameResolution) operations).resolveTableName(normalized))
+ .thenReturn(physical);
+ NameIdentifier[] datasets = new NameIdentifier[0];
+ when(delegate.listSemanticModelDatasets(physical, Entity.EntityType.TABLE))
+ .thenReturn(datasets);
+ assertSame(datasets, normalizer.listSemanticModelDatasets(source, Entity.EntityType.TABLE));
+ verify(delegate).listSemanticModelDatasets(physical, Entity.EntityType.TABLE);
+ }
+
@Test
public void testMetricDiscoveryNormalizesOnlyParents() {
NameIdentifier[] names = {
@@ -240,6 +288,12 @@ public class TestSemanticModelNormalizeDispatcher {
if (scope == Scope.SEMANTIC_MODEL) {
return name.toLowerCase(Locale.ROOT);
}
+ if (scope == Scope.TABLE) {
+ return name.toLowerCase(Locale.ROOT);
+ }
+ if (scope == Scope.VIEW) {
+ return name.toUpperCase(Locale.ROOT);
+ }
return name;
}
}
diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelSourceLookup.java b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelSourceLookup.java
new file mode 100644
index 0000000000..7b930e4ae2
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestSemanticModelSourceLookup.java
@@ -0,0 +1,236 @@
+/*
+ * 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.catalog;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.util.List;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.EntityStore;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.RelationQuery;
+import org.apache.gravitino.SupportsRelationOperations;
+import org.apache.gravitino.audit.AuditLog;
+import org.apache.gravitino.audit.v2.SimpleAuditLogV2;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
+import org.apache.gravitino.hook.SemanticModelHookDispatcher;
+import org.apache.gravitino.listener.EventBus;
+import org.apache.gravitino.listener.SemanticModelEventDispatcher;
+import org.apache.gravitino.listener.api.event.Event;
+import org.apache.gravitino.listener.api.event.OperationStatus;
+import org.apache.gravitino.listener.api.event.OperationType;
+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelDatasetsBySourceEvent;
+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelDatasetsBySourceFailureEvent;
+import org.apache.gravitino.listener.api.event.semantic.ListSemanticModelDatasetsBySourcePreEvent;
+import org.apache.gravitino.meta.SemanticModelDatasetListing;
+import org.apache.gravitino.secret.SecretManager;
+import org.apache.gravitino.storage.RandomIdGenerator;
+import org.apache.gravitino.utils.MetadataObjectUtil;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.MockedStatic;
+
+class TestSemanticModelSourceLookup {
+ private static final NameIdentifier SOURCE =
+ NameIdentifier.of("lake", "sources", "hr", "employees");
+ private final EntityStore store = mock(EntityStore.class);
+ private final SupportsRelationOperations relations = mock(SupportsRelationOperations.class);
+ private final SemanticModelOperationDispatcher operations =
+ new SemanticModelOperationDispatcher(
+ mock(CatalogManager.class),
+ mock(SchemaDispatcher.class),
+ store,
+ RandomIdGenerator.INSTANCE,
+ mock(SecretManager.class));
+
+ @Test
+ void testSourceExistenceStructuredSortAndDeduplication() throws Exception {
+ when(store.relationOperations()).thenReturn(relations);
+ when(relations.<SemanticModelDatasetListing>listEntitiesByRelation(any(RelationQuery.class)))
+ .thenReturn(
+ List.of(
+ new SemanticModelDatasetListing(
+ 2L, NameIdentifier.of("lake", "models", "semantic", "a-b"), List.of("a")),
+ new SemanticModelDatasetListing(
+ 1L,
+ NameIdentifier.of("lake", "models", "semantic", "a"),
+ List.of("z", "A", "a.b", "z", "\uE000", "\uD800\uDC00"))));
+ MetadataObject source = NameIdentifierUtil.toMetadataObject(SOURCE, Entity.EntityType.TABLE);
+ try (MockedStatic<MetadataObjectUtil> metadata = mockStatic(MetadataObjectUtil.class)) {
+ metadata
+ .when(() -> MetadataObjectUtil.checkMetadataObject("lake", source))
+ .thenAnswer(call -> null);
+ assertArrayEquals(
+ new NameIdentifier[] {
+ dataset("a", "A"), dataset("a", "a.b"), dataset("a", "z"),
+ dataset("a", "\uD800\uDC00"), dataset("a", "\uE000"), dataset("a-b", "a")
+ },
+ operations.listSemanticModelDatasets(SOURCE, Entity.EntityType.TABLE));
+ metadata.verify(() -> MetadataObjectUtil.checkMetadataObject("lake", source));
+ ArgumentCaptor<RelationQuery> query = ArgumentCaptor.forClass(RelationQuery.class);
+ verify(relations).listEntitiesByRelation(query.capture());
+ assertEquals(SOURCE, query.getValue().anchorIdentifier());
+ assertEquals(Entity.EntityType.TABLE, query.getValue().anchorEntityType());
+ assertEquals(
+ SupportsRelationOperations.Type.SEMANTIC_MODEL_SOURCE_REL,
+ query.getValue().relationType());
+ }
+ }
+
+ @Test
+ void testMissingSourceAndStorageErrorsNeverBecomeEmptyResults() throws Exception {
+ MetadataObject source = NameIdentifierUtil.toMetadataObject(SOURCE, Entity.EntityType.VIEW);
+ try (MockedStatic<MetadataObjectUtil> metadata = mockStatic(MetadataObjectUtil.class)) {
+ metadata
+ .when(() -> MetadataObjectUtil.checkMetadataObject("lake", source))
+ .thenThrow(new NoSuchMetadataObjectException("missing"));
+ assertThrows(
+ NoSuchMetadataObjectException.class,
+ () -> operations.listSemanticModelDatasets(SOURCE, Entity.EntityType.VIEW));
+ verifyNoInteractions(store);
+ metadata
+ .when(() -> MetadataObjectUtil.checkMetadataObject("lake", source))
+ .thenAnswer(call -> null);
+ when(store.relationOperations()).thenReturn(relations);
+ IOException failure = new IOException("storage failed");
+ when(relations.listEntitiesByRelation(any(RelationQuery.class))).thenThrow(failure);
+ assertSame(
+ failure,
+ assertThrows(
+ RuntimeException.class,
+ () -> operations.listSemanticModelDatasets(SOURCE, Entity.EntityType.VIEW))
+ .getCause());
+ when(relations.listEntitiesByRelation(any(RelationQuery.class)))
+ .thenThrow(new NoSuchEntityException("source registration missing"));
+ assertThrows(
+ NoSuchMetadataObjectException.class,
+ () -> operations.listSemanticModelDatasets(SOURCE, Entity.EntityType.VIEW));
+ }
+ }
+
+ @Test
+ void testUnsupportedSourceIsRejectedBeforeStorage() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> operations.listSemanticModelDatasets(SOURCE, Entity.EntityType.SCHEMA));
+ verifyNoInteractions(store);
+ }
+
+ @Test
+ void testEmptyLookupAndHookForwarding() throws Exception {
+ when(store.relationOperations()).thenReturn(relations);
+ when(relations.listEntitiesByRelation(any(RelationQuery.class))).thenReturn(List.of());
+ try (MockedStatic<MetadataObjectUtil> metadata = mockStatic(MetadataObjectUtil.class)) {
+ assertArrayEquals(
+ new NameIdentifier[0],
+ operations.listSemanticModelDatasets(SOURCE, Entity.EntityType.VIEW));
+ metadata.verify(
+ () ->
+ MetadataObjectUtil.checkMetadataObject(
+ "lake", NameIdentifierUtil.toMetadataObject(SOURCE, Entity.EntityType.VIEW)));
+ }
+ SemanticModelDispatcher delegate = mock(SemanticModelDispatcher.class);
+ NameIdentifier[] datasets = {dataset("staff", "employee")};
+ when(delegate.listSemanticModelDatasets(SOURCE, Entity.EntityType.VIEW)).thenReturn(datasets);
+ SemanticModelHookDispatcher hook =
+ new SemanticModelHookDispatcher(
+ delegate,
+ () -> {
+ throw new AssertionError("Lookup must not modify ownership");
+ });
+ assertSame(datasets, hook.listSemanticModelDatasets(SOURCE, Entity.EntityType.VIEW));
+ }
+
+ @Test
+ void testLookupEventsAndAuditMapping() {
+ EventBus bus = mock(EventBus.class);
+ SemanticModelDispatcher delegate = mock(SemanticModelDispatcher.class);
+ SemanticModelEventDispatcher dispatcher = new SemanticModelEventDispatcher(bus, delegate);
+ NameIdentifier[] datasets = {dataset("staff", "employee")};
+ when(delegate.listSemanticModelDatasets(SOURCE, Entity.EntityType.TABLE)).thenReturn(datasets);
+ assertSame(datasets, dispatcher.listSemanticModelDatasets(SOURCE, Entity.EntityType.TABLE));
+ ArgumentCaptor<Event> events = ArgumentCaptor.forClass(Event.class);
+ verify(bus, times(2)).dispatchEvent(events.capture());
+ ListSemanticModelDatasetsBySourcePreEvent pre =
+ assertInstanceOf(
+ ListSemanticModelDatasetsBySourcePreEvent.class, events.getAllValues().get(0));
+ assertEquals(SOURCE, pre.identifier());
+ assertEquals(MetadataObject.Type.TABLE, pre.sourceType());
+ assertEquals(OperationType.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE, pre.operationType());
+ ListSemanticModelDatasetsBySourceEvent success =
+ assertInstanceOf(ListSemanticModelDatasetsBySourceEvent.class, events.getValue());
+ assertEquals(1, success.resultCount());
+ assertEquals(SOURCE, success.identifier());
+ assertEquals(MetadataObject.Type.TABLE, success.sourceType());
+ assertEquals(OperationType.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE, success.operationType());
+ assertEquals(OperationStatus.SUCCESS, success.operationStatus());
+ assertEquals(
+ AuditLog.Operation.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE,
+ AuditLog.Operation.fromEvent(success));
+ SimpleAuditLogV2 successLog = new SimpleAuditLogV2(success);
+ assertEquals(SOURCE.toString(), successLog.identifier());
+ assertEquals(AuditLog.Operation.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE, successLog.operation());
+ assertEquals(AuditLog.Status.SUCCESS, successLog.status());
+ reset(bus);
+ RuntimeException failure = new RuntimeException("failed");
+ doThrow(failure).when(delegate).listSemanticModelDatasets(SOURCE, Entity.EntityType.VIEW);
+ assertSame(
+ failure,
+ assertThrows(
+ RuntimeException.class,
+ () -> dispatcher.listSemanticModelDatasets(SOURCE, Entity.EntityType.VIEW)));
+ verify(bus, times(2)).dispatchEvent(events.capture());
+ ListSemanticModelDatasetsBySourceFailureEvent failed =
+ assertInstanceOf(ListSemanticModelDatasetsBySourceFailureEvent.class, events.getValue());
+ assertSame(failure, failed.exception());
+ assertEquals(SOURCE, failed.identifier());
+ assertEquals(MetadataObject.Type.VIEW, failed.sourceType());
+ assertEquals(OperationType.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE, failed.operationType());
+ assertEquals(OperationStatus.FAILURE, failed.operationStatus());
+ assertEquals(
+ AuditLog.Operation.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE,
+ AuditLog.Operation.fromEvent(failed));
+ SimpleAuditLogV2 failureLog = new SimpleAuditLogV2(failed);
+ assertEquals(SOURCE.toString(), failureLog.identifier());
+ assertEquals(AuditLog.Operation.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE, failureLog.operation());
+ assertEquals(AuditLog.Status.FAILURE, failureLog.status());
+ }
+
+ private NameIdentifier dataset(String model, String dataset) {
+ return NameIdentifier.of(Namespace.of("lake", "models", "semantic", model), dataset);
+ }
+}
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceService.java
new file mode 100644
index 0000000000..a90ed65c01
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSemanticModelSourceService.java
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.service;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.RelationQuery;
+import org.apache.gravitino.SupportsRelationOperations;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelDatasetListing;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.ViewEntity;
+import org.apache.gravitino.semantic.Dataset;
+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.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelSourceMapper;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.HierarchicalSchemaUtil;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.TestTemplate;
+
+/** Exercises indexed source lookup and lifecycle visibility on all relational backends. */
+public class TestSemanticModelSourceService extends TestJDBCBackend {
+ private Namespace sourceNamespace;
+ private Namespace modelNamespace;
+ private TableEntity source;
+ private long metalakeId;
+
+ @BeforeEach
+ void prepareSources() throws Exception {
+ metalakeId = createAndInsertMakeLake("lake").id();
+ createAndInsertCatalog("lake", "sources");
+ createAndInsertCatalog("lake", "models");
+ createAndInsertSchema("lake", "sources", "hr");
+ createAndInsertSchema("lake", "models", "semantic");
+ sourceNamespace = Namespace.of("lake", "sources", "hr");
+ modelNamespace = Namespace.of("lake", "models", "semantic");
+ source = createAndInsertTableEntity(sourceNamespace, "employees");
+ }
+
+ @TestTemplate
+ void testCrossCatalogSharedSourcesCaseAndLongNames() throws Exception {
+ String[] names = {"employee", "Employee", "manager.with.dot", "long".repeat(300), "员工"};
+ SemanticModelEntity model = model("staff", source.id(), names);
+ backend.insert(model, false);
+ List<SemanticModelDatasetListing> found = lookup(source.nameIdentifier(), source.type());
+ assertEquals(1, found.size());
+ assertEquals(model.id(), found.get(0).id());
+ assertEquals(model.nameIdentifier(), found.get(0).nameIdentifier());
+ assertEquals(Set.of(names), Set.copyOf(found.get(0).datasets()));
+ assertEquals(names.length, rows(source.id(), source.type()).size());
+ assertTrue(
+ lookup(
+ createAndInsertTableEntity(sourceNamespace, "unused").nameIdentifier(),
+ source.type())
+ .isEmpty());
+ assertThrows(
+ NoSuchEntityException.class,
+ () -> lookup(NameIdentifier.of(sourceNamespace, "missing"), source.type()));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> lookup(source.nameIdentifier(), Entity.EntityType.SCHEMA));
+ }
+
+ @TestTemplate
+ void testMultipleModelsAndDuplicateRowsPreserveExactDatasetNames() throws Exception {
+ SemanticModelEntity first = model("staff", source.id(), "employee", "Employee");
+ SemanticModelEntity second = model("staff_again", source.id(), "employee");
+ backend.insert(first, false);
+ backend.insert(second, false);
+ SessionUtils.doWithCommit(
+ SemanticModelSourceMapper.class,
+ mapper ->
+ mapper.insertSources(
+ metalakeId,
+ first.id(),
+ List.of(new SemanticModelSource("employee", source.type(), source.id()))));
+ Map<Long, List<String>> found =
+ lookup(source.nameIdentifier(), source.type()).stream()
+ .collect(
+ Collectors.toMap(
+ SemanticModelDatasetListing::id, SemanticModelDatasetListing::datasets));
+ assertEquals(2, found.size());
+ assertEquals(2, found.get(first.id()).size());
+ assertEquals(Set.of("employee", "Employee"), Set.copyOf(found.get(first.id())));
+ assertEquals(List.of("employee"), found.get(second.id()));
+ }
+
+ @TestTemplate
+ void testCurrentParentNamesAndHierarchicalSchema() throws Exception {
+ SemanticModelEntity model = model("staff", source.id(), "employee");
+ backend.insert(model, false);
+ String physicalSchema =
+ HierarchicalSchemaUtil.logicalToPhysical(
+ "parent.child", HierarchicalSchemaUtil.schemaSeparator());
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+ PreparedStatement schema =
+ session
+ .getConnection()
+ .prepareStatement(
+ "UPDATE schema_meta SET schema_name = ? WHERE schema_name = 'semantic'");
+ Statement catalog = session.getConnection().createStatement()) {
+ schema.setString(1, physicalSchema);
+ schema.executeUpdate();
+ catalog.executeUpdate(
+ "UPDATE catalog_meta SET catalog_name = 'models_v2' WHERE catalog_name = 'models'");
+ session.commit(true);
+ }
+ assertEquals(
+ NameIdentifier.of("lake", "models_v2", "parent.child", "staff"),
+ lookup(source.nameIdentifier(), source.type()).get(0).nameIdentifier());
+ }
+
+ @TestTemplate
+ void testDeletedModelsAndParentsAreExcludedEvenWithLiveAssociations() throws Exception {
+ backend.insert(model("staff", source.id(), "employee"), false);
+ for (String table :
+ List.of("semantic_model_meta", "schema_meta", "catalog_meta", "metalake_meta")) {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+ Statement statement = session.getConnection().createStatement()) {
+ statement.executeUpdate("UPDATE " + table + " SET deleted_at = 1");
+ session.commit(true);
+ try {
+ assertEquals(1, associationCount());
+ assertTrue(rows(source.id(), source.type()).isEmpty(), table);
+ } finally {
+ statement.executeUpdate("UPDATE " + table + " SET deleted_at = 0");
+ session.commit(true);
+ }
+ }
+ }
+ assertEquals(1, lookup(source.nameIdentifier(), source.type()).size());
+ }
+
+ @TestTemplate
+ void testViewAndTableTypesAreDistinct() throws Exception {
+ ViewEntity view = createViewEntity(source.id(), sourceNamespace, "employees_view");
+ backend.insert(view, false);
+ SemanticModelEntity tableModel = model("table_model", source.id(), "employee");
+ backend.insert(tableModel, false);
+ SemanticModelEntity viewModel =
+ copy(
+ tableModel,
+ "view_model",
+ tableModel.definition(),
+ SemanticModelSourceUpdate.replace(
+ List.of(new SemanticModelSource("employee", Entity.EntityType.VIEW, view.id()))),
+ RandomIdGenerator.INSTANCE.nextId());
+ backend.insert(viewModel, false);
+ assertEquals(tableModel.id(), lookup(source.nameIdentifier(), source.type()).get(0).id());
+ assertEquals(viewModel.id(), lookup(view.nameIdentifier(), view.type()).get(0).id());
+ }
+
+ @TestTemplate
+ void testSourceRenameAndMetadataUpdatesPreserveBinding() throws Exception {
+ SemanticModelEntity original = model("staff", source.id(), "employee", "manager");
+ backend.insert(original, false);
+ TableEntity renamed =
+ createTableEntity(source.id(), sourceNamespace, "employees_v2", AUDIT_INFO);
+ backend.update(source.nameIdentifier(), source.type(), old -> renamed);
+ SemanticModelEntity renamedModel =
+ copy(
+ original,
+ "staff_v2",
+ original.definition(),
+ SemanticModelSourceUpdate.preserve(),
+ original.id());
+ backend.update(original.nameIdentifier(), original.type(), old -> renamedModel);
+ assertEquals(
+ renamedModel.nameIdentifier(),
+ lookup(renamed.nameIdentifier(), renamed.type()).get(0).nameIdentifier());
+ SemanticModelEntity loaded =
+ SemanticModelMetaService.getInstance()
+ .getSemanticModelByIdentifier(renamedModel.nameIdentifier());
+ assertEquals(
+ NameIdentifier.of("sources", "hr", "employees"),
+ loaded.definition().datasets()[0].source());
+ assertEquals(2, rows(source.id(), source.type()).size());
+ }
+
+ @TestTemplate
+ void testDeletionNameReuseAndIdenticalReplacement() throws Exception {
+ SemanticModelEntity original = model("staff", source.id(), "employee");
+ backend.insert(original, false);
+ backend.delete(source.nameIdentifier(), source.type(), false);
+ assertEquals(1, rows(source.id(), source.type()).size());
+ assertThrows(NoSuchEntityException.class, () -> lookup(source.nameIdentifier(), source.type()));
+ TableEntity recreated = createAndInsertTableEntity(sourceNamespace, source.name());
+ assertTrue(lookup(recreated.nameIdentifier(), recreated.type()).isEmpty());
+ SemanticModelEntity metadataOnly =
+ copy(
+ original,
+ "staff",
+ original.definition(),
+ SemanticModelSourceUpdate.preserve(),
+ original.id());
+ backend.update(original.nameIdentifier(), original.type(), old -> metadataOnly);
+ assertEquals(1, rows(source.id(), source.type()).size());
+ SemanticModelEntity replacement =
+ copy(
+ original,
+ "staff",
+ original.definition(),
+ SemanticModelSourceUpdate.replace(
+ List.of(new SemanticModelSource("employee", source.type(), recreated.id()))),
+ original.id());
+ backend.update(original.nameIdentifier(), original.type(), old -> replacement);
+ assertTrue(rows(source.id(), source.type()).isEmpty());
+ assertEquals(
+ List.of("employee"),
+ lookup(recreated.nameIdentifier(), recreated.type()).get(0).datasets());
+ }
+
+ @TestTemplate
+ void testDatasetReplacementAndOverwriteUsePersistedModelIdentity() throws Exception {
+ SemanticModelEntity original = model("staff", source.id(), "employee", "manager");
+ backend.insert(original, false);
+ SemanticModelEntity replacement = model("staff", source.id(), "renamed");
+ backend.insert(replacement, true);
+ List<SemanticModelDatasetListing> found = lookup(source.nameIdentifier(), source.type());
+ assertEquals(1, found.size());
+ assertEquals(original.id(), found.get(0).id());
+ assertEquals(List.of("renamed"), found.get(0).datasets());
+ backend.delete(original.nameIdentifier(), original.type(), false);
+ assertEquals(0, associationCount());
+ assertTrue(rows(source.id(), source.type()).isEmpty());
+ }
+
+ @TestTemplate
+ void testInsertFailureRestoresDeletedAssociationsAndDefinition() throws Exception {
+ SemanticModelEntity original = model("staff", source.id(), "employee");
+ backend.insert(original, false);
+ TableEntity blocked = createAndInsertTableEntity(sourceNamespace, "blocked");
+ // Reject the new association inside the database, after the old associations were retired.
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+ Statement statement = session.getConnection().createStatement()) {
+ statement.execute(
+ "ALTER TABLE semantic_model_source_rel ADD CONSTRAINT reject_test_source CHECK (source_id <> "
+ + blocked.id()
+ + ")");
+ session.commit(true);
+ }
+ try {
+ SemanticModelEntity definition = model("staff", blocked.id(), "renamed");
+ SemanticModelEntity replacement =
+ copy(
+ original,
+ original.name(),
+ definition.definition(),
+ definition.sourceUpdate(),
+ original.id());
+ IOException failure =
+ assertThrows(
+ IOException.class,
+ () -> backend.update(original.nameIdentifier(), original.type(), old -> replacement));
+ assertTrue(
+ ExceptionUtils.getStackTrace(failure)
+ .toLowerCase(Locale.ROOT)
+ .contains("reject_test_source"));
+ assertEquals(
+ original,
+ SemanticModelMetaService.getInstance()
+ .getSemanticModelByIdentifier(original.nameIdentifier()));
+ assertEquals(1, associationCount());
+ assertEquals(
+ List.of("employee"), lookup(source.nameIdentifier(), source.type()).get(0).datasets());
+ assertTrue(lookup(blocked.nameIdentifier(), blocked.type()).isEmpty());
+ } finally {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+ Statement statement = session.getConnection().createStatement()) {
+ statement.execute(
+ "ALTER TABLE semantic_model_source_rel DROP "
+ + ("mysql".equals(backendType) ? "CHECK" : "CONSTRAINT")
+ + " reject_test_source");
+ session.commit(true);
+ }
+ }
+ }
+
+ @TestTemplate
+ void testSourceParentDeletionKeepsAssociations() throws Exception {
+ SemanticModelEntity model = model("staff", source.id(), "employee");
+ backend.insert(model, false);
+ backend.delete(NameIdentifier.of("lake", "sources"), Entity.EntityType.CATALOG, true);
+ assertEquals(1, associationCount());
+ assertEquals(1, rows(source.id(), source.type()).size());
+ assertEquals(
+ model,
+ SemanticModelMetaService.getInstance()
+ .getSemanticModelByIdentifier(model.nameIdentifier()));
+ backend.delete(NameIdentifier.of(modelNamespace.levels()), Entity.EntityType.SCHEMA, true);
+ assertEquals(0, associationCount());
+ assertTrue(rows(source.id(), source.type()).isEmpty());
+ }
+
+ @TestTemplate
+ void testModelParentDeletionCleansRows() throws Exception {
+ SemanticModelEntity model = model("staff", source.id(), "employee");
+ backend.insert(model, false);
+ backend.delete(NameIdentifier.of("lake", "models"), Entity.EntityType.CATALOG, true);
+ assertEquals(0, associationCount());
+ assertTrue(rows(source.id(), source.type()).isEmpty());
+ createAndInsertCatalog("lake", "models");
+ createAndInsertSchema("lake", "models", "semantic");
+ backend.insert(model("staff", source.id(), "employee"), false);
+ backend.delete(NameIdentifier.of("lake"), Entity.EntityType.METALAKE, true);
+ assertEquals(0, associationCount());
+ assertTrue(rows(source.id(), source.type()).isEmpty());
+ }
+
+ private int associationCount() throws Exception {
+ try (SqlSession session =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession();
+ PreparedStatement statement =
+ session
+ .getConnection()
+ .prepareStatement(
+ "SELECT COUNT(*) FROM semantic_model_source_rel WHERE metalake_id = ? AND deleted_at = 0")) {
+ statement.setLong(1, metalakeId);
+ try (ResultSet result = statement.executeQuery()) {
+ result.next();
+ return result.getInt(1);
+ }
+ }
+ }
+
+ private List<SemanticModelDatasetListing> lookup(
+ NameIdentifier identifier, Entity.EntityType type) throws Exception {
+ return backend.listEntitiesByRelation(
+ RelationQuery.of(
+ SupportsRelationOperations.Type.SEMANTIC_MODEL_SOURCE_REL,
+ identifier,
+ type,
+ false,
+ null));
+ }
+
+ private List<?> rows(long sourceId, Entity.EntityType type) {
+ return SessionUtils.getWithoutCommit(
+ SemanticModelSourceMapper.class,
+ mapper -> mapper.listForSource(metalakeId, type.name(), sourceId));
+ }
+
+ private SemanticModelEntity model(String name, long sourceId, String... names) {
+ SemanticModelDefinition definition =
+ SemanticModelDefinition.builder()
+ .withDatasets(
+ Arrays.stream(names)
+ .map(
+ dataset ->
+ Dataset.builder()
+ .withName(dataset)
+ .withSource(NameIdentifier.of("sources", "hr", "employees"))
+ .build())
+ .toArray(Dataset[]::new))
+ .build();
+ SemanticModelSourceUpdate update =
+ SemanticModelSourceUpdate.replace(
+ Arrays.stream(names)
+ .map(dataset -> new SemanticModelSource(dataset, Entity.EntityType.TABLE, sourceId))
+ .collect(Collectors.toList()));
+ return SemanticModelEntity.builder()
+ .withId(RandomIdGenerator.INSTANCE.nextId())
+ .withName(name)
+ .withNamespace(modelNamespace)
+ .withDefinition(definition)
+ .withProperties(Map.of())
+ .withAuditInfo(AUDIT_INFO)
+ .withSourceUpdate(update)
+ .build();
+ }
+
+ private SemanticModelEntity copy(
+ SemanticModelEntity original,
+ String name,
+ SemanticModelDefinition definition,
+ SemanticModelSourceUpdate update,
+ long id) {
+ return SemanticModelEntity.builder()
+ .withId(id)
+ .withName(name)
+ .withNamespace(original.namespace())
+ .withDefinition(definition)
+ .withProperties(Map.of("updated", "true"))
+ .withAuditInfo(AUDIT_INFO)
+ .withSourceUpdate(update)
+ .build();
+ }
+}
diff --git a/docs/open-api/openapi.yaml b/docs/open-api/openapi.yaml
index 9e4d335f33..4a8b03c4df 100644
--- a/docs/open-api/openapi.yaml
+++ b/docs/open-api/openapi.yaml
@@ -168,6 +168,9 @@ paths:
/metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/views/{view}:
$ref: "./views.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1catalogs~1%7Bcatalog%7D~1schemas~1%7Bschema%7D~1views~1%7Bview%7D"
+ /metalakes/{metalake}/objects/{metadataObjectType}/{metadataObjectFullName}/semantic-model-datasets:
+ $ref: "./semantic-models.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1objects~1%7BmetadataObjectType%7D~1%7BmetadataObjectFullName%7D~1semantic-model-datasets"
+
/metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/semantic-model-metrics:
$ref: "./semantic-models.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1catalogs~1%7Bcatalog%7D~1schemas~1%7Bschema%7D~1semantic-model-metrics"
diff --git a/docs/open-api/semantic-models.yaml b/docs/open-api/semantic-models.yaml
index 906716f5f8..8207706ade 100644
--- a/docs/open-api/semantic-models.yaml
+++ b/docs/open-api/semantic-models.yaml
@@ -19,6 +19,54 @@
paths:
+ /metalakes/{metalake}/objects/{metadataObjectType}/{metadataObjectFullName}/semantic-model-datasets:
+ parameters:
+ - $ref: "./openapi.yaml#/components/parameters/metalake"
+ - name: metadataObjectType
+ in: path
+ required: true
+ description: The source metadata object type
+ schema:
+ type: string
+ enum: [table, view]
+ - $ref: "./openapi.yaml#/components/parameters/metadataObjectFullName"
+ get:
+ tags:
+ - semantic-model
+ summary: List Semantic Model datasets associated with a source
+ description: >-
+ Lists datasets directly associated with a registered table or View in the same metalake,
+ including models in other catalogs and schemas. Requires access to the source metadata
+ and returns datasets only from models the caller can load, including access to each model's
+ catalog and schema. Authorization evaluation failures exclude the affected models.
+ Returns one identifier per matching dataset, with namespace
+ [metalake, catalog, schema, semanticModel] and the exact, case-sensitive dataset name.
+ Results are sorted by those components in order using UTF-16 code units, independently of
+ database collation. Dataset names containing dots remain a single name component.
+ An existing source with no visible matches returns an empty identifiers array; missing
+ sources and storage failures fail the request. The response is unpaginated.
+ Associations refer to source IDs resolved at the latest definition write. Renaming a source
+ while preserving its ID keeps its associations; reusing its name for a new source does not.
+ This lookup neither rewrites nor revalidates model definitions and does not follow View
+ dependencies. The source full name uses catalog.schema.name; literal dots in source name
+ components cannot be represented reliably by this route.
+ operationId: listSemanticModelDatasets
+ responses:
+ "200":
+ $ref: "#/components/responses/SemanticModelDatasetListResponse"
+ "400":
+ $ref: "#/components/responses/SemanticModelBadRequestResponse"
+ "403":
+ $ref: "#/components/responses/SemanticModelForbiddenResponse"
+ "404":
+ description: The source or one of its parents does not exist
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
+ "5XX":
+ $ref: "./openapi.yaml#/components/responses/ServerErrorResponse"
+
/metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/semantic-model-metrics:
parameters:
- $ref: "./openapi.yaml#/components/parameters/metalake"
@@ -1190,6 +1238,54 @@ components:
}
responses:
+ SemanticModelDatasetListResponse:
+ description: Fully qualified identifiers of visible datasets directly associated with the source
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ type: object
+ required: [code, identifiers]
+ properties:
+ code:
+ type: integer
+ format: int32
+ enum: [0]
+ identifiers:
+ type: array
+ items:
+ type: object
+ required: [namespace, name]
+ properties:
+ namespace:
+ type: array
+ description: Full namespace [metalake, catalog, schema, semanticModel]
+ minItems: 4
+ maxItems: 4
+ items:
+ type: string
+ minLength: 1
+ name:
+ type: string
+ minLength: 1
+ description: The exact, case-sensitive dataset name, which may contain dots
+ additionalProperties: false
+ additionalProperties: false
+ examples:
+ SharedSource:
+ summary: Two datasets in one model referencing the same source
+ value:
+ code: 0
+ identifiers:
+ - namespace: [example, analytics, semantic, employee_analysis]
+ name: employee
+ - namespace: [example, analytics, semantic, employee_analysis]
+ name: manager
+ Empty:
+ summary: The source exists but no matching datasets are visible
+ value:
+ code: 0
+ identifiers: []
+
SemanticModelMetricListResponse:
description: Metric identifiers or complete metric definitions, according to details
content:
diff --git a/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java b/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java
index 0e0b0a6a49..40cbd5e882 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/filter/GravitinoInterceptionService.java
@@ -71,6 +71,7 @@ import org.apache.gravitino.server.web.rest.JobOperations;
import org.apache.gravitino.server.web.rest.MetadataObjectCredentialOperations;
import org.apache.gravitino.server.web.rest.MetadataObjectPolicyOperations;
import org.apache.gravitino.server.web.rest.MetadataObjectSecretOperations;
+import org.apache.gravitino.server.web.rest.MetadataObjectSemanticModelOperations;
import org.apache.gravitino.server.web.rest.MetadataObjectTagOperations;
import org.apache.gravitino.server.web.rest.MetalakeOperations;
import org.apache.gravitino.server.web.rest.ModelOperations;
@@ -118,6 +119,7 @@ public class GravitinoInterceptionService implements InterceptionService {
FunctionOperations.class.getName(),
SemanticModelOperations.class.getName(),
SemanticModelMetricOperations.class.getName(),
+ MetadataObjectSemanticModelOperations.class.getName(),
TopicOperations.class.getName(),
FilesetOperations.class.getName(),
BulkOperations.class.getName(),
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectSemanticModelOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectSemanticModelOperations.java
new file mode 100644
index 0000000000..9c557f28fb
--- /dev/null
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectSemanticModelOperations.java
@@ -0,0 +1,129 @@
+/*
+ * 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.server.web.rest;
+
+import com.codahale.metrics.annotation.ResponseMetered;
+import com.codahale.metrics.annotation.Timed;
+import com.google.common.base.Preconditions;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Set;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.catalog.SemanticModelDispatcher;
+import org.apache.gravitino.dto.responses.EntityListResponse;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.server.authorization.MetadataAuthzHelper;
+import org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;
+import org.apache.gravitino.server.authorization.annotations.AuthorizationFullName;
+import org.apache.gravitino.server.authorization.annotations.AuthorizationMetadata;
+import org.apache.gravitino.server.authorization.annotations.AuthorizationObjectType;
+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;
+import org.apache.gravitino.server.web.Utils;
+import org.apache.gravitino.utils.MetadataObjectUtil;
+
+/** Lists visible Semantic Model datasets directly associated with a source metadata object. */
+@Path("/metalakes/{metalake}/objects/{type}/{fullName}/semantic-model-datasets")
+public class MetadataObjectSemanticModelOperations {
+ private final SemanticModelDispatcher dispatcher;
+ @Context private HttpServletRequest httpRequest;
+
+ /**
+ * Creates source-scoped dataset discovery operations.
+ *
+ * @param dispatcher The Semantic Model dispatcher.
+ */
+ @Inject
+ public MetadataObjectSemanticModelOperations(SemanticModelDispatcher dispatcher) {
+ this.dispatcher = dispatcher;
+ }
+
+ /**
+ * Lists matching datasets from models the caller can load, including their parent access checks.
+ *
+ * @param metalake The source metalake.
+ * @param type The table or View source type.
+ * @param fullName The source's catalog.schema.name.
+ * @return An ordered list of fully qualified dataset identifiers.
+ */
+ @GET
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(
+ name = "list-semantic-model-datasets." + MetricNames.HTTP_PROCESS_DURATION,
+ absolute = true)
+ @ResponseMetered(name = "list-semantic-model-datasets", absolute = true)
+ @AuthorizationExpression(expression = AuthorizationExpressionConstants.CAN_ACCESS_METADATA)
+ public Response listSemanticModelDatasets(
+ @PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)
+ String metalake,
+ @PathParam("type") @AuthorizationObjectType String type,
+ @PathParam("fullName") @AuthorizationFullName String fullName) {
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ MetadataObject.Type sourceType =
+ MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT));
+ Preconditions.checkArgument(
+ sourceType == MetadataObject.Type.TABLE || sourceType == MetadataObject.Type.VIEW,
+ "Source must be a table or View");
+ MetadataObject source = MetadataObjects.parse(fullName, sourceType);
+ NameIdentifier[] datasets =
+ dispatcher.listSemanticModelDatasets(
+ MetadataObjectUtil.toEntityIdent(metalake, source),
+ MetadataObjectUtil.toEntityType(source));
+ NameIdentifier[] models =
+ Arrays.stream(datasets)
+ .map(dataset -> NameIdentifier.of(dataset.namespace().levels()))
+ .distinct()
+ .toArray(NameIdentifier[]::new);
+ Set<NameIdentifier> visible =
+ new HashSet<>(
+ Arrays.asList(
+ MetadataAuthzHelper.filterByExpression(
+ metalake,
+ AuthorizationExpressionConstants
+ .LOAD_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION,
+ Entity.EntityType.SEMANTIC_MODEL,
+ models)));
+ return Utils.ok(
+ new EntityListResponse(
+ Arrays.stream(datasets)
+ .filter(
+ dataset ->
+ visible.contains(NameIdentifier.of(dataset.namespace().levels())))
+ .toArray(NameIdentifier[]::new)));
+ });
+ } catch (Exception e) {
+ return ExceptionHandlers.handleSemanticModelException(
+ OperationType.LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE, "", fullName, e);
+ }
+ }
+}
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/OperationType.java b/server/src/main/java/org/apache/gravitino/server/web/rest/OperationType.java
index 947aeaef5c..7a92ea355b 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/OperationType.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/OperationType.java
@@ -39,6 +39,8 @@ public enum OperationType {
LIST_VERSIONS, // An operation to list versions of a model
/** An operation to list metrics contained in Semantic Models. */
LIST_SEMANTIC_MODEL_METRICS,
+ /** An operation to list Semantic Model datasets associated with a source table or View. */
+ LIST_SEMANTIC_MODEL_DATASETS_BY_SOURCE,
LINK, // An operation to link a version to a model
RUN, // An operation to run a job
CANCEL, // An operation to cancel a job
diff --git a/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java b/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java
index 983084f597..24c7927059 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/filter/TestGravitinoInterceptionService.java
@@ -59,6 +59,7 @@ import org.apache.gravitino.authorization.AuthorizationUtils;
import org.apache.gravitino.authorization.GravitinoAuthorizer;
import org.apache.gravitino.authorization.Owner;
import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.catalog.SemanticModelDispatcher;
import org.apache.gravitino.catalog.TableDispatcher;
import org.apache.gravitino.catalog.ViewDispatcher;
import org.apache.gravitino.dto.requests.CatalogUpdateRequest;
@@ -106,6 +107,7 @@ import org.apache.gravitino.server.web.filter.authorization.AuthorizeExecutorFac
import org.apache.gravitino.server.web.rest.CatalogOperations;
import org.apache.gravitino.server.web.rest.JobOperations;
import org.apache.gravitino.server.web.rest.MetadataObjectPolicyOperations;
+import org.apache.gravitino.server.web.rest.MetadataObjectSemanticModelOperations;
import org.apache.gravitino.server.web.rest.MetadataObjectTagOperations;
import org.apache.gravitino.server.web.rest.OwnerOperations;
import org.apache.gravitino.server.web.rest.PermissionOperations;
@@ -146,6 +148,71 @@ public class TestGravitinoInterceptionService {
RequestContext.clear();
}
+ @ParameterizedTest
+ @ValueSource(strings = {"table", "view"})
+ public void testDeniedSourceLookupDoesNotReachDispatcher(String type) throws Throwable {
+ try (MockedStatic<PrincipalUtils> principalUtilsMocked = mockStatic(PrincipalUtils.class);
+ MockedStatic<GravitinoAuthorizerProvider> authorizerMocked =
+ mockStatic(GravitinoAuthorizerProvider.class);
+ MockedStatic<AuthorizationUtils> authUtilsMocked = mockStatic(AuthorizationUtils.class);
+ MockedStatic<GravitinoEnv> envMocked = mockStatic(GravitinoEnv.class)) {
+ principalUtilsMocked
+ .when(PrincipalUtils::getCurrentPrincipal)
+ .thenReturn(new UserPrincipal("tester"));
+ principalUtilsMocked.when(PrincipalUtils::getCurrentUserName).thenReturn("tester");
+ authUtilsMocked
+ .when(
+ () ->
+ AuthorizationUtils.checkCurrentUser(
+ ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any()))
+ .thenAnswer(invocation -> null);
+
+ GravitinoAuthorizerProvider provider = mock(GravitinoAuthorizerProvider.class);
+ GravitinoAuthorizer authorizer = mock(GravitinoAuthorizer.class);
+ authorizerMocked.when(GravitinoAuthorizerProvider::getInstance).thenReturn(provider);
+ when(provider.getGravitinoAuthorizer()).thenReturn(authorizer);
+
+ GravitinoEnv env = mock(GravitinoEnv.class);
+ EventBus eventBus = mock(EventBus.class);
+ envMocked.when(GravitinoEnv::getInstance).thenReturn(env);
+ when(env.eventBus()).thenReturn(eventBus);
+
+ SemanticModelDispatcher dispatcher = mock(SemanticModelDispatcher.class);
+ MetadataObjectSemanticModelOperations operations =
+ new MetadataObjectSemanticModelOperations(dispatcher);
+ FieldUtils.writeField(operations, "httpRequest", mock(HttpServletRequest.class), true);
+ Method method =
+ MetadataObjectSemanticModelOperations.class.getMethod(
+ "listSemanticModelDatasets", String.class, String.class, String.class);
+ MethodInvocation invocation = mock(MethodInvocation.class);
+ when(invocation.getMethod()).thenReturn(method);
+ when(invocation.getArguments())
+ .thenReturn(new Object[] {"testMetalake", type, "testCatalog.testSchema.source"});
+ when(invocation.proceed())
+ .thenAnswer(
+ ignored ->
+ operations.listSemanticModelDatasets(
+ "testMetalake", type, "testCatalog.testSchema.source"));
+
+ MethodInterceptor interceptor =
+ new GravitinoInterceptionService().getMethodInterceptors(method).get(0);
+ Response response = (Response) interceptor.invoke(invocation);
+
+ assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
+ verify(invocation, never()).proceed();
+ verify(dispatcher, never()).listSemanticModelDatasets(any(), any());
+ }
+ }
+
+ @Test
+ public void testSourceLookupIsRegisteredForInterception() {
+ Descriptor descriptor = mock(Descriptor.class);
+ when(descriptor.getImplementation())
+ .thenReturn(MetadataObjectSemanticModelOperations.class.getName());
+ Assertions.assertTrue(
+ new GravitinoInterceptionService().getDescriptorFilter().matches(descriptor));
+ }
+
@Test
public void testPathMetalakeValidationPrecedesExecutorConstruction() throws Throwable {
Method method =
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectSemanticModelOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectSemanticModelOperations.java
new file mode 100644
index 0000000000..aab48e33a4
--- /dev/null
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectSemanticModelOperations.java
@@ -0,0 +1,280 @@
+/*
+ * 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.server.web.rest;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.CALLS_REAL_METHODS;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.UserPrincipal;
+import org.apache.gravitino.authorization.GravitinoAuthorizer;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.catalog.SemanticModelDispatcher;
+import org.apache.gravitino.dto.responses.EntityListResponse;
+import org.apache.gravitino.exceptions.ForbiddenException;
+import org.apache.gravitino.exceptions.NoSuchMetadataObjectException;
+import org.apache.gravitino.listener.EventBus;
+import org.apache.gravitino.listener.SemanticModelEventDispatcher;
+import org.apache.gravitino.rest.RESTUtils;
+import org.apache.gravitino.server.authorization.MetadataAuthzHelper;
+import org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;
+import org.glassfish.jersey.internal.inject.AbstractBinder;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.test.TestProperties;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.MockedStatic;
+
+/** Exercises the wire contract and full cross-catalog model load authorization. */
+public class TestMetadataObjectSemanticModelOperations extends BaseOperationsTest {
+ private static final String MEDIA_TYPE = "application/vnd.gravitino.v1+json";
+ private static final NameIdentifier SOURCE =
+ NameIdentifier.of("lake", "sources", "hr", "employees");
+ private static final String FILTER =
+ AuthorizationExpressionConstants.LOAD_SEMANTIC_MODEL_AUTHORIZATION_EXPRESSION;
+ private final SemanticModelDispatcher dispatcher = mock(SemanticModelDispatcher.class);
+ private final EventBus eventBus = mock(EventBus.class);
+
+ private static class MockServletRequestFactory extends ServletRequestFactoryBase {
+ @Override
+ public HttpServletRequest get() {
+ return mock(HttpServletRequest.class);
+ }
+ }
+
+ @Override
+ protected Application configure() {
+ try {
+ forceSet(
+ TestProperties.CONTAINER_PORT, String.valueOf(RESTUtils.findAvailablePort(2000, 3000)));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return new ResourceConfig()
+ .register(MetadataObjectSemanticModelOperations.class)
+ .register(
+ new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(new SemanticModelEventDispatcher(eventBus, dispatcher))
+ .to(SemanticModelDispatcher.class)
+ .ranked(2);
+ bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);
+ }
+ });
+ }
+
+ @BeforeEach
+ void resetDispatcher() {
+ reset(dispatcher, eventBus);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"table", "view"})
+ void testStructuredDatasetIdentifiersAndEmptyResults(String type) {
+ Entity.EntityType entityType =
+ type.equals("table") ? Entity.EntityType.TABLE : Entity.EntityType.VIEW;
+ NameIdentifier[] names = {
+ dataset("models", "semantic", "staff", "employee.with.dot"),
+ dataset("other", "semantic", "staff", "经理")
+ };
+ when(dispatcher.listSemanticModelDatasets(SOURCE, entityType)).thenReturn(names);
+ try (Response response = get(type)) {
+ assertEquals(200, response.getStatus());
+ EntityListResponse body = response.readEntity(EntityListResponse.class);
+ body.validate();
+ assertArrayEquals(names, body.identifiers());
+ }
+ when(dispatcher.listSemanticModelDatasets(SOURCE, entityType))
+ .thenReturn(new NameIdentifier[0]);
+ try (Response response = get(type)) {
+ assertEquals(200, response.getStatus());
+ assertEquals(0, response.readEntity(EntityListResponse.class).identifiers().length);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"schema", "catalog", "column", "unknown"})
+ void testUnsupportedSourceTypes(String type) {
+ try (Response response = get(type)) {
+ assertEquals(400, response.getStatus());
+ }
+ }
+
+ @Test
+ void testSourceAndStorageFailuresFailWholeRequest() {
+ List<RuntimeException> errors =
+ List.of(
+ new NoSuchMetadataObjectException("missing"),
+ new ForbiddenException("denied"),
+ new RuntimeException("storage failed"));
+ int[] statuses = {404, 403, 500};
+ for (int i = 0; i < errors.size(); i++) {
+ doThrow(errors.get(i))
+ .when(dispatcher)
+ .listSemanticModelDatasets(SOURCE, Entity.EntityType.TABLE);
+ try (Response response = get("table")) {
+ assertEquals(statuses[i], response.getStatus());
+ }
+ }
+ }
+
+ @Test
+ void testEachModelIsFilteredOnceAndItsDatasetsStayTogether() throws Exception {
+ NameIdentifier[] datasets = {
+ dataset("models", "semantic", "visible", "a"),
+ dataset("models", "semantic", "visible", "b"),
+ dataset("hidden", "semantic", "hidden", "c")
+ };
+ NameIdentifier[] models =
+ Arrays.stream(datasets)
+ .map(id -> NameIdentifier.of(id.namespace().levels()))
+ .distinct()
+ .toArray(NameIdentifier[]::new);
+ when(dispatcher.listSemanticModelDatasets(SOURCE, Entity.EntityType.TABLE))
+ .thenReturn(datasets);
+ try (MockedStatic<MetadataAuthzHelper> helper = mockStatic(MetadataAuthzHelper.class)) {
+ helper
+ .when(
+ () ->
+ MetadataAuthzHelper.filterByExpression(
+ "lake", FILTER, Entity.EntityType.SEMANTIC_MODEL, models))
+ .thenReturn(new NameIdentifier[] {models[0]});
+ try (Response response =
+ operations().listSemanticModelDatasets("lake", "table", "sources.hr.employees")) {
+ assertEquals(200, response.getStatus());
+ assertArrayEquals(
+ Arrays.copyOf(datasets, 2), ((EntityListResponse) response.getEntity()).identifiers());
+ }
+ helper.verify(
+ () ->
+ MetadataAuthzHelper.filterByExpression(
+ "lake", FILTER, Entity.EntityType.SEMANTIC_MODEL, models));
+ }
+ }
+
+ @Test
+ void testModelOwnershipDoesNotBypassCatalogAndSchemaAccess() throws Exception {
+ Config previous = GravitinoEnv.getInstance().config();
+ Config config = new Config(false) {};
+ config.set(Configs.ENABLE_AUTHORIZATION, true);
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", config, true);
+ GravitinoAuthorizer authorizer = mock(GravitinoAuthorizer.class);
+ when(authorizer.isOwner(any(), eq("lake"), any(), any()))
+ .thenAnswer(
+ call -> {
+ MetadataObject object = call.getArgument(2);
+ if (object.type() != MetadataObject.Type.SEMANTIC_MODEL) return false;
+ if (object.name().equals("failed"))
+ throw new IllegalStateException("authorization unavailable");
+ return true;
+ });
+ when(authorizer.authorize(any(), eq("lake"), any(), any(), any()))
+ .thenAnswer(
+ call -> {
+ MetadataObject object = call.getArgument(2);
+ Privilege.Name privilege = call.getArgument(3);
+ return (privilege == Privilege.Name.USE_CATALOG
+ && object.type() == MetadataObject.Type.CATALOG
+ && object.name().equals("allowed"))
+ || (privilege == Privilege.Name.USE_SCHEMA
+ && object.type() == MetadataObject.Type.SCHEMA
+ && object.name().equals("allowed_schema"));
+ });
+ NameIdentifier[] datasets = {
+ dataset("allowed", "allowed_schema", "visible", "a"),
+ dataset("allowed", "allowed_schema", "visible", "b"),
+ dataset("blocked", "allowed_schema", "hidden_catalog", "a"),
+ dataset("allowed", "blocked_schema", "hidden_schema", "a"),
+ dataset("allowed", "allowed_schema", "failed", "a")
+ };
+ when(dispatcher.listSemanticModelDatasets(SOURCE, Entity.EntityType.TABLE))
+ .thenReturn(datasets);
+ try (MockedStatic<MetadataAuthzHelper> helper =
+ mockStatic(MetadataAuthzHelper.class, CALLS_REAL_METHODS)) {
+ helper
+ .when(
+ () ->
+ MetadataAuthzHelper.filterByExpression(
+ eq("lake"),
+ eq(FILTER),
+ eq(Entity.EntityType.SEMANTIC_MODEL),
+ any(NameIdentifier[].class)))
+ .thenAnswer(
+ call ->
+ MetadataAuthzHelper.filterByExpression(
+ "lake",
+ FILTER,
+ Entity.EntityType.SEMANTIC_MODEL,
+ call.getArgument(3, NameIdentifier[].class),
+ value -> value,
+ new UserPrincipal("tester"),
+ authorizer));
+ try (Response response =
+ operations().listSemanticModelDatasets("lake", "table", "sources.hr.employees")) {
+ assertEquals(200, response.getStatus());
+ assertArrayEquals(
+ Arrays.copyOf(datasets, 2), ((EntityListResponse) response.getEntity()).identifiers());
+ }
+ } finally {
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", previous, true);
+ }
+ }
+
+ private Response get(String type) {
+ return target(
+ "metalakes/lake/objects/" + type + "/sources.hr.employees/semantic-model-datasets")
+ .request(MEDIA_TYPE)
+ .get();
+ }
+
+ private MetadataObjectSemanticModelOperations operations() throws Exception {
+ MetadataObjectSemanticModelOperations operations =
+ new MetadataObjectSemanticModelOperations(dispatcher);
+ FieldUtils.writeField(operations, "httpRequest", mock(HttpServletRequest.class), true);
+ return operations;
+ }
+
+ private static NameIdentifier dataset(String catalog, String schema, String model, String name) {
+ return NameIdentifier.of(Namespace.of("lake", catalog, schema, model), name);
+ }
+}