Skip to content

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

[#12608] feat(server): Add Semantic Model list, alter, and drop REST APIs (#12626)

mchades2b514d5cd59f
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelCreateRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelCreateRequest.java
index 63e2248daf..e371edd158 100644
--- a/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelCreateRequest.java
+++ b/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelCreateRequest.java
@@ -88,6 +88,7 @@ public class SemanticModelCreateRequest implements RESTRequest {
StringUtils.isNotBlank(name), "\"name\" field is required and cannot be empty");
Preconditions.checkArgument(
definition != null, "\"definition\" field is required and cannot be null");
+ definition.validate();
}
/**
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelUpdateRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelUpdateRequest.java
new file mode 100644
index 0000000000..acdc490607
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelUpdateRequest.java
@@ -0,0 +1,245 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import com.google.common.base.Preconditions;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.dto.semantic.SemanticModelDefinitionDTO;
+import org.apache.gravitino.rest.RESTRequest;
+import org.apache.gravitino.semantic.SemanticModelChange;
+
+/** Represents one change in a request to alter a Semantic Model. */
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
+@JsonSubTypes({
+ @JsonSubTypes.Type(
+ value = SemanticModelUpdateRequest.RenameSemanticModelRequest.class,
+ name = "rename"),
+ @JsonSubTypes.Type(
+ value = SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest.class,
+ name = "updateComment"),
+ @JsonSubTypes.Type(
+ value = SemanticModelUpdateRequest.SetSemanticModelPropertyRequest.class,
+ name = "setProperty"),
+ @JsonSubTypes.Type(
+ value = SemanticModelUpdateRequest.RemoveSemanticModelPropertyRequest.class,
+ name = "removeProperty"),
+ @JsonSubTypes.Type(
+ value = SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest.class,
+ name = "replaceDefinition")
+})
+public interface SemanticModelUpdateRequest extends RESTRequest {
+
+ /**
+ * Returns the Semantic Model change represented by this request.
+ *
+ * @return The Semantic Model change.
+ */
+ SemanticModelChange semanticModelChange();
+
+ /** Represents a request to rename a Semantic Model. */
+ @Getter
+ @EqualsAndHashCode
+ @ToString
+ class RenameSemanticModelRequest implements SemanticModelUpdateRequest {
+
+ @JsonProperty("newName")
+ private final String newName;
+
+ /** Default constructor for Jackson deserialization. */
+ public RenameSemanticModelRequest() {
+ this(null);
+ }
+
+ /**
+ * Creates a request to rename a Semantic Model.
+ *
+ * @param newName The new Semantic Model name.
+ */
+ public RenameSemanticModelRequest(String newName) {
+ this.newName = newName;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(newName), "\"newName\" field is required and cannot be empty");
+ }
+
+ @Override
+ public SemanticModelChange semanticModelChange() {
+ return SemanticModelChange.rename(newName);
+ }
+ }
+
+ /** Represents a request to update a Semantic Model comment. */
+ @Getter
+ @EqualsAndHashCode
+ @ToString
+ class UpdateSemanticModelCommentRequest implements SemanticModelUpdateRequest {
+
+ @Nullable
+ @JsonProperty("newComment")
+ private final String newComment;
+
+ /** Default constructor for Jackson deserialization. */
+ public UpdateSemanticModelCommentRequest() {
+ this(null);
+ }
+
+ /**
+ * Creates a request to update or clear a Semantic Model comment.
+ *
+ * @param newComment The new comment, or {@code null} to clear it.
+ */
+ public UpdateSemanticModelCommentRequest(@Nullable String newComment) {
+ this.newComment = newComment;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ // A null comment clears the current comment; an empty comment is stored as supplied.
+ }
+
+ @Override
+ public SemanticModelChange semanticModelChange() {
+ return SemanticModelChange.updateComment(newComment);
+ }
+ }
+
+ /** Represents a request to set a Semantic Model property. */
+ @Getter
+ @EqualsAndHashCode
+ @ToString
+ class SetSemanticModelPropertyRequest implements SemanticModelUpdateRequest {
+
+ @JsonProperty("property")
+ private final String property;
+
+ @JsonProperty("value")
+ private final String value;
+
+ /** Default constructor for Jackson deserialization. */
+ public SetSemanticModelPropertyRequest() {
+ this(null, null);
+ }
+
+ /**
+ * Creates a request to set a Semantic Model property.
+ *
+ * @param property The property name.
+ * @param value The property value.
+ */
+ public SetSemanticModelPropertyRequest(String property, String value) {
+ this.property = property;
+ this.value = value;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(property), "\"property\" field is required and cannot be empty");
+ Preconditions.checkArgument(value != null, "\"value\" field is required and cannot be null");
+ }
+
+ @Override
+ public SemanticModelChange semanticModelChange() {
+ return SemanticModelChange.setProperty(property, value);
+ }
+ }
+
+ /** Represents a request to remove a Semantic Model property. */
+ @Getter
+ @EqualsAndHashCode
+ @ToString
+ class RemoveSemanticModelPropertyRequest implements SemanticModelUpdateRequest {
+
+ @JsonProperty("property")
+ private final String property;
+
+ /** Default constructor for Jackson deserialization. */
+ public RemoveSemanticModelPropertyRequest() {
+ this(null);
+ }
+
+ /**
+ * Creates a request to remove a Semantic Model property.
+ *
+ * @param property The property name.
+ */
+ public RemoveSemanticModelPropertyRequest(String property) {
+ this.property = property;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(property), "\"property\" field is required and cannot be empty");
+ }
+
+ @Override
+ public SemanticModelChange semanticModelChange() {
+ return SemanticModelChange.removeProperty(property);
+ }
+ }
+
+ /** Represents a request to replace the complete Semantic Model definition. */
+ @Getter
+ @EqualsAndHashCode
+ @ToString
+ class ReplaceSemanticModelDefinitionRequest implements SemanticModelUpdateRequest {
+
+ @JsonProperty("definition")
+ private final SemanticModelDefinitionDTO definition;
+
+ /** Default constructor for Jackson deserialization. */
+ public ReplaceSemanticModelDefinitionRequest() {
+ this(null);
+ }
+
+ /**
+ * Creates a request to replace the complete Semantic Model definition.
+ *
+ * @param definition The replacement definition DTO.
+ */
+ public ReplaceSemanticModelDefinitionRequest(SemanticModelDefinitionDTO definition) {
+ this.definition = definition;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ definition != null, "\"definition\" field is required and cannot be null");
+ definition.validate();
+ }
+
+ @Override
+ public SemanticModelChange semanticModelChange() {
+ return SemanticModelChange.replaceDefinition(definition.toDefinition());
+ }
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelUpdatesRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelUpdatesRequest.java
new file mode 100644
index 0000000000..27f57f0a47
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/requests/SemanticModelUpdatesRequest.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.requests;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import java.util.List;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.gravitino.rest.RESTRequest;
+
+/** Represents an atomic request to alter a Semantic Model. */
+@Getter
+@EqualsAndHashCode
+@ToString
+public class SemanticModelUpdatesRequest implements RESTRequest {
+
+ @JsonProperty("updates")
+ private final List<SemanticModelUpdateRequest> updates;
+
+ /** Default constructor for Jackson deserialization. */
+ public SemanticModelUpdatesRequest() {
+ this(null);
+ }
+
+ /**
+ * Creates an atomic Semantic Model updates request.
+ *
+ * @param updates The non-empty list of updates to apply.
+ */
+ public SemanticModelUpdatesRequest(List<SemanticModelUpdateRequest> updates) {
+ this.updates = updates;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(updates != null, "updates must not be null");
+ Preconditions.checkArgument(!updates.isEmpty(), "updates must not be empty");
+ for (SemanticModelUpdateRequest update : updates) {
+ Preconditions.checkArgument(update != null, "update must not be null");
+ update.validate();
+ }
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDefinitionDTO.java b/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDefinitionDTO.java
index 5bbe365803..f274823c6b 100644
--- a/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDefinitionDTO.java
+++ b/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDefinitionDTO.java
@@ -147,6 +147,15 @@ public class SemanticModelDefinitionDTO {
.build();
}
+ /**
+ * Validates this Semantic Model definition without converting it to the API representation.
+ *
+ * @throws IllegalArgumentException If any definition field is invalid.
+ */
+ public void validate() throws IllegalArgumentException {
+ SemanticModelDefinitionValidator.validate(this);
+ }
+
/**
* Converts this persistence DTO to an API Semantic Model definition.
*
diff --git a/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDefinitionValidator.java b/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDefinitionValidator.java
new file mode 100644
index 0000000000..2241e53109
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/semantic/SemanticModelDefinitionValidator.java
@@ -0,0 +1,217 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.semantic;
+
+import com.google.common.base.Preconditions;
+import java.util.HashSet;
+import java.util.Set;
+import javax.annotation.Nullable;
+
+final class SemanticModelDefinitionValidator {
+
+ private SemanticModelDefinitionValidator() {}
+
+ static void validate(SemanticModelDefinitionDTO definition) {
+ DatasetDTO[] datasets = definition.getDatasets();
+ RelationshipDTO[] relationships = definition.getRelationships();
+ MetricDTO[] metrics = definition.getMetrics();
+ CustomExtensionDTO[] customExtensions = definition.getCustomExtensions();
+
+ Preconditions.checkArgument(
+ datasets != null && datasets.length > 0, "datasets must not be null or empty");
+ validateNoNullElements("datasets", datasets);
+ validateNoNullElements("relationships", relationships);
+ validateNoNullElements("metrics", metrics);
+ validateNoNullElements("customExtensions", customExtensions);
+
+ for (DatasetDTO dataset : datasets) {
+ validateDataset(dataset);
+ }
+ if (relationships != null) {
+ for (RelationshipDTO relationship : relationships) {
+ validateRelationship(relationship);
+ }
+ }
+ if (metrics != null) {
+ for (MetricDTO metric : metrics) {
+ validateMetric(metric);
+ }
+ }
+ validateCustomExtensions(customExtensions);
+ validateAIContext(definition.getAiContext());
+ }
+
+ private static void validateDataset(DatasetDTO dataset) {
+ Preconditions.checkArgument(
+ dataset.getName() != null && !dataset.getName().isEmpty(),
+ "name must not be null or empty");
+ Preconditions.checkArgument(dataset.getSource() != null, "source must not be null");
+
+ String[] primaryKey = dataset.getPrimaryKey();
+ String[][] uniqueKeys = dataset.getUniqueKeys();
+ FieldDTO[] fields = dataset.getFields();
+ CustomExtensionDTO[] customExtensions = dataset.getCustomExtensions();
+ validateNonEmptyStringElements("primaryKey", primaryKey);
+ validateUniqueKeys(uniqueKeys);
+ validateNoNullElements("fields", fields);
+ validateNoNullElements("customExtensions", customExtensions);
+
+ if (fields != null) {
+ for (FieldDTO field : fields) {
+ validateField(field);
+ }
+ }
+ validateCustomExtensions(customExtensions);
+ validateAIContext(dataset.getAiContext());
+ }
+
+ private static void validateRelationship(RelationshipDTO relationship) {
+ Preconditions.checkArgument(
+ relationship.getName() != null && !relationship.getName().isEmpty(),
+ "name must not be null or empty");
+ Preconditions.checkArgument(
+ relationship.getFrom() != null && !relationship.getFrom().isEmpty(),
+ "from must not be null or empty");
+ Preconditions.checkArgument(
+ relationship.getTo() != null && !relationship.getTo().isEmpty(),
+ "to must not be null or empty");
+
+ String[] fromColumns = relationship.getFromColumns();
+ String[] toColumns = relationship.getToColumns();
+ Preconditions.checkArgument(
+ fromColumns != null && fromColumns.length > 0, "fromColumns must not be null or empty");
+ Preconditions.checkArgument(
+ toColumns != null && toColumns.length > 0, "toColumns must not be null or empty");
+ validateNonEmptyStringElements("fromColumns", fromColumns);
+ validateNonEmptyStringElements("toColumns", toColumns);
+ Preconditions.checkArgument(
+ fromColumns.length == toColumns.length,
+ "fromColumns and toColumns must have the same length");
+
+ CustomExtensionDTO[] customExtensions = relationship.getCustomExtensions();
+ validateNoNullElements("customExtensions", customExtensions);
+ validateCustomExtensions(customExtensions);
+ validateAIContext(relationship.getAiContext());
+ }
+
+ private static void validateField(FieldDTO field) {
+ Preconditions.checkArgument(
+ field.getName() != null && !field.getName().isEmpty(), "name must not be null or empty");
+ Preconditions.checkArgument(field.getExpression() != null, "expression must not be null");
+
+ CustomExtensionDTO[] customExtensions = field.getCustomExtensions();
+ validateNoNullElements("customExtensions", customExtensions);
+ validateExpression(field.getExpression());
+ validateCustomExtensions(customExtensions);
+ validateAIContext(field.getAiContext());
+ }
+
+ private static void validateMetric(MetricDTO metric) {
+ Preconditions.checkArgument(
+ metric.getName() != null && !metric.getName().isEmpty(), "name must not be null or empty");
+ Preconditions.checkArgument(metric.getExpression() != null, "expression must not be null");
+
+ CustomExtensionDTO[] customExtensions = metric.getCustomExtensions();
+ validateNoNullElements("customExtensions", customExtensions);
+ validateExpression(metric.getExpression());
+ validateCustomExtensions(customExtensions);
+ validateAIContext(metric.getAiContext());
+ }
+
+ private static void validateExpression(ExpressionDTO expression) {
+ DialectExpressionDTO[] dialects = expression.getDialects();
+ Preconditions.checkArgument(
+ dialects != null && dialects.length > 0, "dialects must not be null or empty");
+ validateNoNullElements("dialects", dialects);
+
+ Set<String> seenDialects = new HashSet<>();
+ for (DialectExpressionDTO dialect : dialects) {
+ Preconditions.checkArgument(
+ dialect.getDialect() != null && !dialect.getDialect().isEmpty(),
+ "dialect must not be null or empty");
+ Preconditions.checkArgument(
+ dialect.getExpression() != null && !dialect.getExpression().isEmpty(),
+ "expression must not be null or empty");
+ Preconditions.checkArgument(
+ seenDialects.add(dialect.getDialect()),
+ "dialects must not contain duplicate dialect: %s",
+ dialect.getDialect());
+ }
+ }
+
+ private static void validateCustomExtensions(@Nullable CustomExtensionDTO[] customExtensions) {
+ if (customExtensions == null) {
+ return;
+ }
+ for (CustomExtensionDTO customExtension : customExtensions) {
+ Preconditions.checkArgument(
+ customExtension.getVendorName() != null, "vendorName must not be null");
+ Preconditions.checkArgument(customExtension.getData() != null, "data must not be null");
+ }
+ }
+
+ private static void validateAIContext(@Nullable AIContextDTO aiContext) {
+ if (aiContext == null) {
+ return;
+ }
+ Preconditions.checkArgument(
+ (aiContext.getText() == null) != (aiContext.getObject() == null),
+ "AI context must contain exactly one of text or object");
+ if (aiContext.getObject() != null) {
+ validateNoNullElements("synonyms", aiContext.getObject().getSynonyms());
+ validateNoNullElements("examples", aiContext.getObject().getExamples());
+ }
+ }
+
+ private static void validateUniqueKeys(@Nullable String[][] uniqueKeys) {
+ if (uniqueKeys == null) {
+ return;
+ }
+ for (int index = 0; index < uniqueKeys.length; index++) {
+ String[] uniqueKey = uniqueKeys[index];
+ Preconditions.checkArgument(
+ uniqueKey != null && uniqueKey.length > 0,
+ "uniqueKeys[%s] must not be null or empty",
+ index);
+ validateNonEmptyStringElements("uniqueKeys[" + index + "]", uniqueKey);
+ }
+ }
+
+ private static void validateNoNullElements(String name, @Nullable Object[] values) {
+ if (values == null) {
+ return;
+ }
+ for (int index = 0; index < values.length; index++) {
+ Preconditions.checkArgument(values[index] != null, "%s[%s] must not be null", name, index);
+ }
+ }
+
+ private static void validateNonEmptyStringElements(String name, @Nullable String[] values) {
+ if (values == null) {
+ return;
+ }
+ for (int index = 0; index < values.length; index++) {
+ Preconditions.checkArgument(
+ values[index] != null && !values[index].isEmpty(),
+ "%s[%s] must not be null or empty",
+ name,
+ index);
+ }
+ }
+}
diff --git a/common/src/test/java/org/apache/gravitino/dto/requests/TestSemanticModelCreateRequest.java b/common/src/test/java/org/apache/gravitino/dto/requests/TestSemanticModelCreateRequest.java
index 4c4d398852..f061560cf8 100644
--- a/common/src/test/java/org/apache/gravitino/dto/requests/TestSemanticModelCreateRequest.java
+++ b/common/src/test/java/org/apache/gravitino/dto/requests/TestSemanticModelCreateRequest.java
@@ -149,9 +149,8 @@ public class TestSemanticModelCreateRequest {
SemanticModelCreateRequest request =
JsonUtils.objectMapper().readValue(json, SemanticModelCreateRequest.class);
- request.validate();
IllegalArgumentException exception =
- assertThrows(IllegalArgumentException.class, request::toDefinition);
+ assertThrows(IllegalArgumentException.class, request::validate);
assertEquals("datasets[0] must not be null", exception.getMessage());
}
diff --git a/common/src/test/java/org/apache/gravitino/dto/requests/TestSemanticModelUpdateRequest.java b/common/src/test/java/org/apache/gravitino/dto/requests/TestSemanticModelUpdateRequest.java
new file mode 100644
index 0000000000..485b042fd7
--- /dev/null
+++ b/common/src/test/java/org/apache/gravitino/dto/requests/TestSemanticModelUpdateRequest.java
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.dto.requests;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import java.util.Arrays;
+import java.util.Collections;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.semantic.SemanticModelChange;
+import org.junit.jupiter.api.Test;
+
+public class TestSemanticModelUpdateRequest {
+
+ @Test
+ public void testAllUpdateTypesSerDeValidateAndConvert() throws JsonProcessingException {
+ String json =
+ "{\"updates\":["
+ + "{\"@type\":\"rename\",\"newName\":\"sales_v2\"},"
+ + "{\"@type\":\"updateComment\",\"newComment\":null},"
+ + "{\"@type\":\"setProperty\",\"property\":\"owner\",\"value\":\"finance\"},"
+ + "{\"@type\":\"removeProperty\",\"property\":\"legacy\"},"
+ + "{\"@type\":\"replaceDefinition\",\"definition\":{"
+ + "\"datasets\":[{\"name\":\"orders\","
+ + "\"source\":{\"namespace\":[\"sales\",\"mart\"],\"name\":\"orders\"}}],"
+ + "\"relationships\":[],\"metrics\":[],\"customExtensions\":[]}}"
+ + "]}";
+
+ SemanticModelUpdatesRequest request =
+ JsonUtils.objectMapper().readValue(json, SemanticModelUpdatesRequest.class);
+ request.validate();
+
+ assertInstanceOf(
+ SemanticModelUpdateRequest.RenameSemanticModelRequest.class, request.getUpdates().get(0));
+ assertInstanceOf(
+ SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest.class,
+ request.getUpdates().get(1));
+ assertInstanceOf(
+ SemanticModelUpdateRequest.SetSemanticModelPropertyRequest.class,
+ request.getUpdates().get(2));
+ assertInstanceOf(
+ SemanticModelUpdateRequest.RemoveSemanticModelPropertyRequest.class,
+ request.getUpdates().get(3));
+ assertInstanceOf(
+ SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest.class,
+ request.getUpdates().get(4));
+
+ SemanticModelChange.RenameSemanticModel rename =
+ (SemanticModelChange.RenameSemanticModel) request.getUpdates().get(0).semanticModelChange();
+ assertEquals("sales_v2", rename.getNewName());
+ SemanticModelChange.UpdateComment updateComment =
+ (SemanticModelChange.UpdateComment) request.getUpdates().get(1).semanticModelChange();
+ assertNull(updateComment.getNewComment());
+ SemanticModelChange.SetProperty setProperty =
+ (SemanticModelChange.SetProperty) request.getUpdates().get(2).semanticModelChange();
+ assertEquals("owner", setProperty.getProperty());
+ assertEquals("finance", setProperty.getValue());
+ SemanticModelChange.RemoveProperty removeProperty =
+ (SemanticModelChange.RemoveProperty) request.getUpdates().get(3).semanticModelChange();
+ assertEquals("legacy", removeProperty.getProperty());
+ SemanticModelChange.ReplaceDefinition replaceDefinition =
+ (SemanticModelChange.ReplaceDefinition) request.getUpdates().get(4).semanticModelChange();
+ assertEquals("orders", replaceDefinition.getDefinition().datasets()[0].name());
+ assertEquals(0, replaceDefinition.getDefinition().relationships().length);
+
+ JsonNode serialized =
+ JsonUtils.objectMapper().readTree(JsonUtils.objectMapper().writeValueAsString(request));
+ assertEquals("rename", serialized.path("updates").get(0).path("@type").textValue());
+ assertEquals("updateComment", serialized.path("updates").get(1).path("@type").textValue());
+ assertEquals("setProperty", serialized.path("updates").get(2).path("@type").textValue());
+ assertEquals("removeProperty", serialized.path("updates").get(3).path("@type").textValue());
+ assertEquals("replaceDefinition", serialized.path("updates").get(4).path("@type").textValue());
+ assertEquals(
+ "orders",
+ serialized
+ .path("updates")
+ .get(4)
+ .path("definition")
+ .path("datasets")
+ .get(0)
+ .path("name")
+ .textValue());
+ }
+
+ @Test
+ public void testUpdatesWrapperRequiresNonEmptyValidatedItems() {
+ IllegalArgumentException missing =
+ assertThrows(IllegalArgumentException.class, new SemanticModelUpdatesRequest()::validate);
+ assertEquals("updates must not be null", missing.getMessage());
+
+ IllegalArgumentException empty =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> new SemanticModelUpdatesRequest(Collections.emptyList()).validate());
+ assertEquals("updates must not be empty", empty.getMessage());
+
+ IllegalArgumentException nullItem =
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ new SemanticModelUpdatesRequest(Arrays.asList((SemanticModelUpdateRequest) null))
+ .validate());
+ assertEquals("update must not be null", nullItem.getMessage());
+
+ IllegalArgumentException invalidRename =
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ new SemanticModelUpdatesRequest(
+ Collections.singletonList(
+ new SemanticModelUpdateRequest.RenameSemanticModelRequest(" ")))
+ .validate());
+ assertEquals("\"newName\" field is required and cannot be empty", invalidRename.getMessage());
+ }
+
+ @Test
+ public void testCommentValuesAndReplacementValidation() throws JsonProcessingException {
+ SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest emptyComment =
+ new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest("");
+ emptyComment.validate();
+ assertEquals(
+ "",
+ ((SemanticModelChange.UpdateComment) emptyComment.semanticModelChange()).getNewComment());
+
+ String nullDataset =
+ "{\"updates\":[{\"@type\":\"replaceDefinition\","
+ + "\"definition\":{\"datasets\":[null]}}]}";
+ SemanticModelUpdatesRequest request =
+ JsonUtils.objectMapper().readValue(nullDataset, SemanticModelUpdatesRequest.class);
+ IllegalArgumentException exception =
+ assertThrows(IllegalArgumentException.class, request::validate);
+ assertEquals("datasets[0] must not be null", exception.getMessage());
+ }
+
+ @Test
+ public void testReplaceDefinitionRejectsUnknownNestedFields() {
+ String json =
+ "{\"updates\":[{\"@type\":\"replaceDefinition\",\"definition\":{"
+ + "\"datasets\":[{\"name\":\"orders\","
+ + "\"source\":{\"namespace\":[\"sales\",\"mart\"],\"name\":\"orders\"}}],"
+ + "\"unknown\":true}}]}";
+
+ assertThrows(
+ JsonProcessingException.class,
+ () -> JsonUtils.objectMapper().readValue(json, SemanticModelUpdatesRequest.class));
+ }
+}
diff --git a/common/src/test/java/org/apache/gravitino/dto/semantic/TestSemanticModelDefinitionDTO.java b/common/src/test/java/org/apache/gravitino/dto/semantic/TestSemanticModelDefinitionDTO.java
index 0b5256a964..a2c0adcd1f 100644
--- a/common/src/test/java/org/apache/gravitino/dto/semantic/TestSemanticModelDefinitionDTO.java
+++ b/common/src/test/java/org/apache/gravitino/dto/semantic/TestSemanticModelDefinitionDTO.java
@@ -420,6 +420,69 @@ public class TestSemanticModelDefinitionDTO {
assertArrayEquals(new String[] {"external_id", "source"}, dataset.getUniqueKeys()[0]);
}
+ @Test
+ public void testDefinitionValidationMatchesConversionValidation() throws JsonProcessingException {
+ SemanticModelDefinitionDTO valid = SemanticModelDefinitionDTO.fromDefinition(definition());
+ valid.validate();
+
+ Map<String, String> invalidDefinitions = new LinkedHashMap<>();
+ invalidDefinitions.put("{\"datasets\":[]}", "datasets must not be null or empty");
+ invalidDefinitions.put("{\"datasets\":[null]}", "datasets[0] must not be null");
+ invalidDefinitions.put(
+ "{\"datasets\":[{\"source\":{\"namespace\":[\"sales\"],\"name\":\"orders\"}}]}",
+ "name must not be null or empty");
+ invalidDefinitions.put(
+ "{\"datasets\":[{\"name\":\"orders\","
+ + "\"source\":{\"namespace\":[\"sales\"],\"name\":\"orders\"},"
+ + "\"primaryKey\":[null]}]}",
+ "primaryKey[0] must not be null or empty");
+ invalidDefinitions.put(
+ "{\"datasets\":[{\"name\":\"orders\","
+ + "\"source\":{\"namespace\":[\"sales\"],\"name\":\"orders\"},"
+ + "\"uniqueKeys\":[[]]}]}",
+ "uniqueKeys[0] must not be null or empty");
+ invalidDefinitions.put(
+ "{\"datasets\":[{\"name\":\"orders\","
+ + "\"source\":{\"namespace\":[\"sales\"],\"name\":\"orders\"},"
+ + "\"fields\":[{\"name\":\"id\"}]}]}",
+ "expression must not be null");
+ invalidDefinitions.put(
+ "{\"datasets\":[{\"name\":\"orders\","
+ + "\"source\":{\"namespace\":[\"sales\"],\"name\":\"orders\"},"
+ + "\"fields\":[{\"name\":\"id\",\"expression\":{\"dialects\":["
+ + "{\"dialect\":\"ANSI_SQL\",\"expression\":\"id\"},"
+ + "{\"dialect\":\"ANSI_SQL\",\"expression\":\"id\"}]}}]}]}",
+ "dialects must not contain duplicate dialect: ANSI_SQL");
+ invalidDefinitions.put(
+ "{\"datasets\":[{\"name\":\"orders\","
+ + "\"source\":{\"namespace\":[\"sales\"],\"name\":\"orders\"}}],"
+ + "\"relationships\":[{\"name\":\"self\",\"from\":\"orders\","
+ + "\"to\":\"orders\",\"fromColumns\":[\"id\"],"
+ + "\"toColumns\":[\"id\",\"other_id\"]}]}",
+ "fromColumns and toColumns must have the same length");
+ invalidDefinitions.put(
+ "{\"datasets\":[{\"name\":\"orders\","
+ + "\"source\":{\"namespace\":[\"sales\"],\"name\":\"orders\"}}],"
+ + "\"metrics\":[{\"name\":\"count\"}]}",
+ "expression must not be null");
+ invalidDefinitions.put(
+ "{\"datasets\":[{\"name\":\"orders\","
+ + "\"source\":{\"namespace\":[\"sales\"],\"name\":\"orders\"}}],"
+ + "\"customExtensions\":[{\"vendorName\":\"example\"}]}",
+ "data must not be null");
+
+ for (Map.Entry<String, String> entry : invalidDefinitions.entrySet()) {
+ SemanticModelDefinitionDTO invalid =
+ objectMapper.readValue(entry.getKey(), SemanticModelDefinitionDTO.class);
+ IllegalArgumentException validationException =
+ assertThrows(IllegalArgumentException.class, invalid::validate);
+ IllegalArgumentException conversionException =
+ assertThrows(IllegalArgumentException.class, invalid::toDefinition);
+ assertEquals(entry.getValue(), validationException.getMessage());
+ assertEquals(conversionException.getMessage(), validationException.getMessage());
+ }
+ }
+
private static SemanticModelDefinition definition() {
Map<String, Object> semanticHints = new LinkedHashMap<>();
semanticHints.put("first", "prefer certified metrics");
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java
index 1c011be250..ab68d05ff0 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/SemanticModelOperations.java
@@ -23,27 +23,36 @@ import com.codahale.metrics.annotation.Timed;
import java.util.Collections;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
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.NameIdentifier;
+import org.apache.gravitino.Namespace;
import org.apache.gravitino.catalog.SemanticModelDispatcher;
import org.apache.gravitino.dto.requests.SemanticModelCreateRequest;
+import org.apache.gravitino.dto.requests.SemanticModelUpdateRequest;
+import org.apache.gravitino.dto.requests.SemanticModelUpdatesRequest;
+import org.apache.gravitino.dto.responses.DropResponse;
+import org.apache.gravitino.dto.responses.EntityListResponse;
import org.apache.gravitino.dto.responses.SemanticModelResponse;
import org.apache.gravitino.dto.util.DTOConverters;
import org.apache.gravitino.metrics.MetricNames;
import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.server.web.Utils;
import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.NamespaceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/** REST create and load operations for schema-scoped Semantic Models. */
+/** REST operations for schema-scoped Semantic Model management. */
@Path("metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/semantic-models")
public class SemanticModelOperations {
@@ -63,6 +72,43 @@ public class SemanticModelOperations {
this.dispatcher = dispatcher;
}
+ /**
+ * Lists Semantic Models in a schema.
+ *
+ * @param metalake The metalake name.
+ * @param catalog The catalog name.
+ * @param schema The schema name.
+ * @return A response containing Semantic Model identifiers.
+ */
+ @GET
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "list-semantic-model." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "list-semantic-model", absolute = true)
+ public Response listSemanticModels(
+ @PathParam("metalake") String metalake,
+ @PathParam("catalog") String catalog,
+ @PathParam("schema") String schema) {
+ LOG.info(
+ "Received list Semantic Models request for schema: {}.{}.{}", metalake, catalog, schema);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ Namespace namespace = NamespaceUtil.ofSemanticModel(metalake, catalog, schema);
+ NameIdentifier[] identifiers = dispatcher.listSemanticModels(namespace);
+ LOG.info(
+ "List {} Semantic Models under schema: {}.{}.{}",
+ identifiers.length,
+ metalake,
+ catalog,
+ schema);
+ return Utils.ok(new EntityListResponse(identifiers));
+ });
+ } catch (Exception e) {
+ return ExceptionHandlers.handleSemanticModelException(OperationType.LIST, "", schema, e);
+ }
+ }
+
/**
* Creates a Semantic Model.
*
@@ -157,4 +203,103 @@ public class SemanticModelOperations {
OperationType.LOAD, semanticModel, schema, e);
}
}
+
+ /**
+ * Alters a Semantic Model atomically.
+ *
+ * @param metalake The metalake name.
+ * @param catalog The catalog name.
+ * @param schema The schema name.
+ * @param semanticModel The current Semantic Model name.
+ * @param request The updates to apply.
+ * @return A response containing the altered Semantic Model.
+ */
+ @PUT
+ @Path("{semanticModel}")
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "alter-semantic-model." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "alter-semantic-model", absolute = true)
+ public Response alterSemanticModel(
+ @PathParam("metalake") String metalake,
+ @PathParam("catalog") String catalog,
+ @PathParam("schema") String schema,
+ @PathParam("semanticModel") String semanticModel,
+ SemanticModelUpdatesRequest request) {
+ LOG.info(
+ "Received alter Semantic Model request: {}.{}.{}.{}",
+ metalake,
+ catalog,
+ schema,
+ semanticModel);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ if (request == null) {
+ throw new IllegalArgumentException("Request body must not be null");
+ }
+ request.validate();
+ NameIdentifier ident =
+ NameIdentifierUtil.ofSemanticModel(metalake, catalog, schema, semanticModel);
+ SemanticModelChange[] changes =
+ request.getUpdates().stream()
+ .map(SemanticModelUpdateRequest::semanticModelChange)
+ .toArray(SemanticModelChange[]::new);
+ SemanticModel altered = dispatcher.alterSemanticModel(ident, changes);
+ LOG.info(
+ "Semantic Model altered: {}.{}.{}.{}", metalake, catalog, schema, altered.name());
+ return Utils.ok(new SemanticModelResponse(DTOConverters.toDTO(altered)));
+ });
+ } catch (Exception e) {
+ return ExceptionHandlers.handleSemanticModelException(
+ OperationType.ALTER, semanticModel, schema, e);
+ }
+ }
+
+ /**
+ * Drops a Semantic Model.
+ *
+ * @param metalake The metalake name.
+ * @param catalog The catalog name.
+ * @param schema The schema name.
+ * @param semanticModel The Semantic Model name.
+ * @return A response indicating whether a Semantic Model was dropped.
+ */
+ @DELETE
+ @Path("{semanticModel}")
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "drop-semantic-model." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "drop-semantic-model", absolute = true)
+ public Response dropSemanticModel(
+ @PathParam("metalake") String metalake,
+ @PathParam("catalog") String catalog,
+ @PathParam("schema") String schema,
+ @PathParam("semanticModel") String semanticModel) {
+ LOG.info(
+ "Received drop Semantic Model request: {}.{}.{}.{}",
+ metalake,
+ catalog,
+ schema,
+ semanticModel);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ NameIdentifier ident =
+ NameIdentifierUtil.ofSemanticModel(metalake, catalog, schema, semanticModel);
+ boolean dropped = dispatcher.dropSemanticModel(ident);
+ if (dropped) {
+ LOG.info(
+ "Semantic Model dropped: {}.{}.{}.{}", metalake, catalog, schema, semanticModel);
+ } else {
+ LOG.warn(
+ "Cannot find Semantic Model {} to drop under schema {}", semanticModel, schema);
+ }
+ return Utils.ok(new DropResponse(dropped));
+ });
+ } catch (Exception e) {
+ return ExceptionHandlers.handleSemanticModelException(
+ OperationType.DROP, semanticModel, schema, e);
+ }
+ }
}
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
index a463c33775..1246f5c173 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestSemanticModelOperations.java
@@ -29,6 +29,7 @@ import static org.mockito.Mockito.when;
import java.io.IOException;
import java.time.Instant;
+import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.client.Entity;
@@ -39,6 +40,10 @@ import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.Namespace;
import org.apache.gravitino.catalog.SemanticModelDispatcher;
import org.apache.gravitino.dto.requests.SemanticModelCreateRequest;
+import org.apache.gravitino.dto.requests.SemanticModelUpdateRequest;
+import org.apache.gravitino.dto.requests.SemanticModelUpdatesRequest;
+import org.apache.gravitino.dto.responses.DropResponse;
+import org.apache.gravitino.dto.responses.EntityListResponse;
import org.apache.gravitino.dto.responses.ErrorConstants;
import org.apache.gravitino.dto.responses.ErrorResponse;
import org.apache.gravitino.dto.responses.SemanticModelResponse;
@@ -50,6 +55,7 @@ import org.apache.gravitino.exceptions.IllegalSemanticModelException;
import org.apache.gravitino.exceptions.MetalakeNotInUseException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NoSuchSemanticModelException;
+import org.apache.gravitino.exceptions.OptimisticLockException;
import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.SemanticModelEntity;
@@ -64,6 +70,7 @@ import org.apache.gravitino.semantic.Expression;
import org.apache.gravitino.semantic.Field;
import org.apache.gravitino.semantic.Metric;
import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.semantic.SemanticModelChange;
import org.apache.gravitino.semantic.SemanticModelDefinition;
import org.apache.gravitino.utils.NameIdentifierUtil;
import org.apache.gravitino.utils.NamespaceUtil;
@@ -75,7 +82,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
-/** Tests the Semantic Model create/load REST resource and its error mappings. */
+/** Tests Semantic Model REST lifecycle operations and their error mappings. */
public class TestSemanticModelOperations extends BaseOperationsTest {
private static final String VND_V1_JSON = "application/vnd.gravitino.v1+json";
@@ -121,6 +128,30 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
reset(dispatcher);
}
+ @Test
+ void testListSemanticModels() {
+ NameIdentifier first = semanticModelIdentifier("sales");
+ NameIdentifier second = semanticModelIdentifier("finance");
+ when(dispatcher.listSemanticModels(namespace)).thenReturn(new NameIdentifier[] {first, second});
+
+ Response response = get(semanticModelPath());
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+ EntityListResponse body = response.readEntity(EntityListResponse.class);
+ Assertions.assertEquals(0, body.getCode());
+ Assertions.assertArrayEquals(new NameIdentifier[] {first, second}, body.identifiers());
+
+ doThrow(new NoSuchSchemaException("schema is missing"))
+ .when(dispatcher)
+ .listSemanticModels(namespace);
+ assertError(
+ get(semanticModelPath()),
+ Response.Status.NOT_FOUND,
+ ErrorConstants.NOT_FOUND_CODE,
+ NoSuchSchemaException.class.getSimpleName(),
+ "schema is missing");
+ }
+
@Test
void testLoadSemanticModelReturnsCompleteDefinitionWithoutWrites() {
NameIdentifier ident = semanticModelIdentifier("sales");
@@ -382,6 +413,123 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
"catalog is not relational");
}
+ @Test
+ void testAlterSemanticModelConvertsAllChangesAtomically() {
+ NameIdentifier ident = semanticModelIdentifier("sales");
+ SemanticModelDefinition replacement = semanticModelDefinition("TRINO");
+ SemanticModelUpdatesRequest request =
+ new SemanticModelUpdatesRequest(
+ List.of(
+ new SemanticModelUpdateRequest.RenameSemanticModelRequest("sales_v2"),
+ new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest("Updated"),
+ new SemanticModelUpdateRequest.SetSemanticModelPropertyRequest("owner", "finance"),
+ new SemanticModelUpdateRequest.RemoveSemanticModelPropertyRequest("legacy"),
+ new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(
+ SemanticModelDefinitionDTO.fromDefinition(replacement))));
+ when(dispatcher.alterSemanticModel(eq(ident), any(SemanticModelChange[].class)))
+ .thenReturn(semanticModel("sales_v2", "Updated"));
+
+ Response response = put(semanticModelPath() + "/sales", request);
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+ SemanticModelResponse body = response.readEntity(SemanticModelResponse.class);
+ body.validate();
+ Assertions.assertEquals("sales_v2", body.getSemanticModel().name());
+
+ ArgumentCaptor<SemanticModelChange[]> changesCaptor =
+ ArgumentCaptor.forClass(SemanticModelChange[].class);
+ verify(dispatcher).alterSemanticModel(eq(ident), changesCaptor.capture());
+ SemanticModelChange[] changes = changesCaptor.getValue();
+ Assertions.assertEquals(5, changes.length);
+ Assertions.assertInstanceOf(SemanticModelChange.RenameSemanticModel.class, changes[0]);
+ Assertions.assertInstanceOf(SemanticModelChange.UpdateComment.class, changes[1]);
+ Assertions.assertInstanceOf(SemanticModelChange.SetProperty.class, changes[2]);
+ Assertions.assertInstanceOf(SemanticModelChange.RemoveProperty.class, changes[3]);
+ Assertions.assertInstanceOf(SemanticModelChange.ReplaceDefinition.class, changes[4]);
+ Assertions.assertEquals(
+ replacement, ((SemanticModelChange.ReplaceDefinition) changes[4]).getDefinition());
+ }
+
+ @Test
+ void testAlterSemanticModelRejectsInvalidBatchBeforeDispatch() {
+ SemanticModelDefinitionDTO invalidDefinition =
+ SemanticModelDefinitionDTO.builder().withDatasets(new DatasetDTO[] {null}).build();
+ SemanticModelUpdatesRequest request =
+ new SemanticModelUpdatesRequest(
+ List.of(
+ new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest("Updated"),
+ new SemanticModelUpdateRequest.ReplaceSemanticModelDefinitionRequest(
+ invalidDefinition)));
+
+ assertError(
+ put(semanticModelPath() + "/sales", request),
+ Response.Status.BAD_REQUEST,
+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE,
+ IllegalArgumentException.class.getSimpleName(),
+ "datasets[0] must not be null");
+ verifyNoMoreInteractions(dispatcher);
+ }
+
+ @Test
+ void testAlterSemanticModelRejectsNullBody() {
+ assertError(
+ putJson(semanticModelPath() + "/sales", "null"),
+ Response.Status.BAD_REQUEST,
+ ErrorConstants.ILLEGAL_ARGUMENTS_CODE,
+ IllegalArgumentException.class.getSimpleName(),
+ "Request body must not be null");
+ verifyNoMoreInteractions(dispatcher);
+ }
+
+ @Test
+ void testAlterSemanticModelErrors() {
+ NameIdentifier ident = semanticModelIdentifier("sales");
+ SemanticModelUpdatesRequest request =
+ new SemanticModelUpdatesRequest(
+ List.of(new SemanticModelUpdateRequest.UpdateSemanticModelCommentRequest("Updated")));
+
+ doThrow(new NoSuchSemanticModelException("sales does not exist"))
+ .when(dispatcher)
+ .alterSemanticModel(eq(ident), any(SemanticModelChange[].class));
+ assertError(
+ put(semanticModelPath() + "/sales", request),
+ Response.Status.NOT_FOUND,
+ ErrorConstants.NOT_FOUND_CODE,
+ NoSuchSemanticModelException.class.getSimpleName(),
+ "sales does not exist");
+
+ doThrow(new OptimisticLockException("sales changed in this transaction"))
+ .when(dispatcher)
+ .alterSemanticModel(eq(ident), any(SemanticModelChange[].class));
+ assertError(
+ put(semanticModelPath() + "/sales", request),
+ Response.Status.CONFLICT,
+ ErrorConstants.OPTIMISTIC_LOCK_CONFLICT_CODE,
+ OptimisticLockException.class.getSimpleName(),
+ "sales changed in this transaction");
+ }
+
+ @Test
+ void testDropSemanticModel() {
+ NameIdentifier ident = semanticModelIdentifier("sales");
+ when(dispatcher.dropSemanticModel(ident)).thenReturn(true, false);
+
+ Response dropped = delete(semanticModelPath() + "/sales");
+ Assertions.assertTrue(dropped.readEntity(DropResponse.class).dropped());
+ Response missing = delete(semanticModelPath() + "/sales");
+ Assertions.assertFalse(missing.readEntity(DropResponse.class).dropped());
+
+ doThrow(new OptimisticLockException("sales changed in this transaction"))
+ .when(dispatcher)
+ .dropSemanticModel(ident);
+ assertError(
+ delete(semanticModelPath() + "/sales"),
+ Response.Status.CONFLICT,
+ ErrorConstants.OPTIMISTIC_LOCK_CONFLICT_CODE,
+ OptimisticLockException.class.getSimpleName(),
+ "sales changed in this transaction");
+ }
+
private SemanticModelCreateRequest createRequest(
String name, String comment, SemanticModelDefinition definition) {
return new SemanticModelCreateRequest(
@@ -479,6 +627,24 @@ public class TestSemanticModelOperations extends BaseOperationsTest {
.post(Entity.entity(json, MediaType.APPLICATION_JSON_TYPE));
}
+ private Response put(String path, SemanticModelUpdatesRequest request) {
+ return target(path)
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept(VND_V1_JSON)
+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
+ }
+
+ private Response putJson(String path, String json) {
+ return target(path)
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept(VND_V1_JSON)
+ .put(Entity.entity(json, MediaType.APPLICATION_JSON_TYPE));
+ }
+
+ private Response delete(String path) {
+ return target(path).request(MediaType.APPLICATION_JSON_TYPE).accept(VND_V1_JSON).delete();
+ }
+
private static ErrorResponse assertError(
Response response,
Response.Status expectedStatus,