World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#12498] feat(api): Add Semantic Model Java API (#12499)
mchadesad9e0da85fe6
diff --git a/api/src/main/java/org/apache/gravitino/Catalog.java b/api/src/main/java/org/apache/gravitino/Catalog.javaindex 3fb8b81693..30cffefb0f 100644--- a/api/src/main/java/org/apache/gravitino/Catalog.java+++ b/api/src/main/java/org/apache/gravitino/Catalog.java@@ -31,6 +31,7 @@ import org.apache.gravitino.policy.SupportsPolicies;import org.apache.gravitino.rel.TableCatalog;import org.apache.gravitino.rel.ViewCatalog;import org.apache.gravitino.secret.SupportsSecrets;+import org.apache.gravitino.semantic.SemanticModelCatalog;import org.apache.gravitino.tag.SupportsTags;/**@@ -256,6 +257,15 @@ public interface Catalog extends Auditable {throw new UnsupportedOperationException("Catalog does not support view operations");}+ /**+ * @return the {@link SemanticModelCatalog} if the catalog supports Semantic Model operations.+ * @throws UnsupportedOperationException if the catalog does not support Semantic Model+ * operations.+ */+ default SemanticModelCatalog asSemanticModelCatalog() throws UnsupportedOperationException {+ throw new UnsupportedOperationException("Catalog does not support Semantic Model operations");+ }+/*** @return the {@link SupportsTags} if the catalog supports tag operations.* @throws UnsupportedOperationException if the catalog does not support tag operations.diff --git a/api/src/main/java/org/apache/gravitino/MetadataObject.java b/api/src/main/java/org/apache/gravitino/MetadataObject.javaindex 97a8525284..6dca45345d 100644--- a/api/src/main/java/org/apache/gravitino/MetadataObject.java+++ b/api/src/main/java/org/apache/gravitino/MetadataObject.java@@ -54,6 +54,8 @@ public interface MetadataObject {TABLE,/** A view is mapped to the view of relational data sources like Apache Hive, MySQL, etc. */VIEW,+ /** A Semantic Model represents a governed analytical semantic definition. */+ SEMANTIC_MODEL,/*** A topic is mapped the topic of messaging data sources like Apache Kafka, Apache Pulsar, etc.*/diff --git a/api/src/main/java/org/apache/gravitino/MetadataObjects.java b/api/src/main/java/org/apache/gravitino/MetadataObjects.javaindex 57bf2fc252..835c1636b3 100644--- a/api/src/main/java/org/apache/gravitino/MetadataObjects.java+++ b/api/src/main/java/org/apache/gravitino/MetadataObjects.java@@ -60,7 +60,8 @@ public class MetadataObjects {MetadataObject.Type.VIEW,MetadataObject.Type.TOPIC,MetadataObject.Type.MODEL,- MetadataObject.Type.FUNCTION);+ MetadataObject.Type.FUNCTION,+ MetadataObject.Type.SEMANTIC_MODEL);private static final Set<MetadataObject.Type> VALID_FOUR_LEVEL_NAME_TYPES =Sets.newHashSet(MetadataObject.Type.COLUMN);@@ -153,6 +154,7 @@ public class MetadataObjects {case TOPIC:case MODEL:case FUNCTION:+ case SEMANTIC_MODEL:parentType = MetadataObject.Type.SCHEMA;break;case SCHEMA:diff --git a/api/src/main/java/org/apache/gravitino/exceptions/IllegalSemanticModelException.java b/api/src/main/java/org/apache/gravitino/exceptions/IllegalSemanticModelException.javanew file mode 100644index 0000000000..db30394ddc--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/exceptions/IllegalSemanticModelException.java@@ -0,0 +1,50 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.exceptions;++import com.google.errorprone.annotations.FormatMethod;+import com.google.errorprone.annotations.FormatString;++/** Exception thrown when a Semantic Model definition or change is invalid. */+public class IllegalSemanticModelException extends IllegalArgumentException {++ /**+ * Constructs an exception with a formatted detail message.+ *+ * @param message The detail message format.+ * @param args The arguments referenced by the format specifiers in the detail message.+ */+ @FormatMethod+ public IllegalSemanticModelException(@FormatString String message, Object... args) {+ super(String.format(message, args));+ }++ /**+ * Constructs an exception with a cause and a formatted detail message.+ *+ * @param cause The cause of the exception.+ * @param message The detail message format.+ * @param args The arguments referenced by the format specifiers in the detail message.+ */+ @FormatMethod+ public IllegalSemanticModelException(+ Throwable cause, @FormatString String message, Object... args) {+ super(String.format(message, args), cause);+ }+}diff --git a/api/src/main/java/org/apache/gravitino/exceptions/NoSuchSemanticModelException.java b/api/src/main/java/org/apache/gravitino/exceptions/NoSuchSemanticModelException.javanew file mode 100644index 0000000000..0f3092124f--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/exceptions/NoSuchSemanticModelException.java@@ -0,0 +1,50 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.exceptions;++import com.google.errorprone.annotations.FormatMethod;+import com.google.errorprone.annotations.FormatString;++/** Exception thrown when a Semantic Model with the specified identifier does not exist. */+public class NoSuchSemanticModelException extends NotFoundException {++ /**+ * Constructs an exception with a formatted detail message.+ *+ * @param message The detail message format.+ * @param args The arguments referenced by the format specifiers in the detail message.+ */+ @FormatMethod+ public NoSuchSemanticModelException(@FormatString String message, Object... args) {+ super(message, args);+ }++ /**+ * Constructs an exception with a cause and a formatted detail message.+ *+ * @param cause The cause of the exception.+ * @param message The detail message format.+ * @param args The arguments referenced by the format specifiers in the detail message.+ */+ @FormatMethod+ public NoSuchSemanticModelException(+ Throwable cause, @FormatString String message, Object... args) {+ super(cause, message, args);+ }+}diff --git a/api/src/main/java/org/apache/gravitino/exceptions/SemanticModelAlreadyExistsException.java b/api/src/main/java/org/apache/gravitino/exceptions/SemanticModelAlreadyExistsException.javanew file mode 100644index 0000000000..5d34a1799b--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/exceptions/SemanticModelAlreadyExistsException.java@@ -0,0 +1,50 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.exceptions;++import com.google.errorprone.annotations.FormatMethod;+import com.google.errorprone.annotations.FormatString;++/** Exception thrown when a Semantic Model with the specified identifier already exists. */+public class SemanticModelAlreadyExistsException extends AlreadyExistsException {++ /**+ * Constructs an exception with a formatted detail message.+ *+ * @param message The detail message format.+ * @param args The arguments referenced by the format specifiers in the detail message.+ */+ @FormatMethod+ public SemanticModelAlreadyExistsException(@FormatString String message, Object... args) {+ super(message, args);+ }++ /**+ * Constructs an exception with a cause and a formatted detail message.+ *+ * @param cause The cause of the exception.+ * @param message The detail message format.+ * @param args The arguments referenced by the format specifiers in the detail message.+ */+ @FormatMethod+ public SemanticModelAlreadyExistsException(+ Throwable cause, @FormatString String message, Object... args) {+ super(cause, message, args);+ }+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/AIContext.java b/api/src/main/java/org/apache/gravitino/semantic/AIContext.javanew file mode 100644index 0000000000..c977adf9d5--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/AIContext.java@@ -0,0 +1,133 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import com.google.common.base.Preconditions;+import java.util.Objects;+import javax.annotation.Nullable;+import org.apache.gravitino.annotation.Evolving;++/** Additional context for AI tools, represented as either a string or an object. */+@Evolving+public final class AIContext {++ @Nullable private final String text;+ @Nullable private final AIContextObject object;++ private AIContext(String text) {+ this.text = text;+ this.object = null;+ }++ private AIContext(AIContextObject object) {+ this.text = null;+ this.object = object;+ }++ /**+ * Creates AI context from a string value.+ *+ * @param value The string context.+ * @return The AI context.+ * @throws IllegalArgumentException If the value is null.+ */+ public static AIContext of(String value) {+ Preconditions.checkArgument(value != null, "AI context string must not be null");+ return new AIContext(value);+ }++ /**+ * Creates AI context from a structured object.+ *+ * @param value The object context.+ * @return The AI context.+ * @throws IllegalArgumentException If the value is null.+ */+ public static AIContext of(AIContextObject value) {+ Preconditions.checkArgument(value != null, "AI context object must not be null");+ return new AIContext(value);+ }++ /**+ * Returns whether this context contains a string value.+ *+ * @return {@code true} when this context contains a string.+ */+ public boolean isText() {+ return text != null;+ }++ /**+ * Returns the string context when this is the string variant.+ *+ * @return The string context, or null for the object variant.+ */+ @Nullable+ public String text() {+ return text;+ }++ /**+ * Returns the structured context when this is the object variant.+ *+ * @return The object context, or null for the string variant.+ */+ @Nullable+ public AIContextObject object() {+ return object;+ }++ /**+ * Compares this AI context with another object.+ *+ * @param other The object to compare.+ * @return {@code true} if the object contains the same context variant and value.+ */+ @Override+ public boolean equals(@Nullable Object other) {+ if (this == other) {+ return true;+ }+ if (!(other instanceof AIContext)) {+ return false;+ }+ AIContext that = (AIContext) other;+ return Objects.equals(text, that.text) && Objects.equals(object, that.object);+ }++ /**+ * Returns the hash code of this AI context.+ *+ * @return The hash code.+ */+ @Override+ public int hashCode() {+ return Objects.hash(text, object);+ }++ /**+ * Returns a string representation of this AI context.+ *+ * @return The string representation.+ */+ @Override+ public String toString() {+ return "AIContext{" + "text=" + text + ", object=" + object + '}';+ }+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/AIContextObject.java b/api/src/main/java/org/apache/gravitino/semantic/AIContextObject.javanew file mode 100644index 0000000000..6e9c156786--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/AIContextObject.java@@ -0,0 +1,387 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import com.google.common.base.Preconditions;+import java.lang.reflect.Array;+import java.math.BigDecimal;+import java.math.BigInteger;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collections;+import java.util.IdentityHashMap;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Objects;+import javax.annotation.Nullable;+import org.apache.gravitino.annotation.Evolving;++/** Structured AI context with optional standard fields and retained custom JSON properties. */+@Evolving+public final class AIContextObject {++ static final int MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH = 100;++ @Nullable private final String instructions;+ @Nullable private final String[] synonyms;+ @Nullable private final String[] examples;+ private final Map<String, Object> additionalProperties;++ private AIContextObject(Builder builder) {+ this.instructions = builder.instructions;+ this.synonyms = SemanticModelDefinition.copyOrNull(builder.synonyms);+ this.examples = SemanticModelDefinition.copyOrNull(builder.examples);+ this.additionalProperties = immutableAdditionalProperties(builder.additionalProperties);+ }++ /**+ * Creates a builder for structured AI context.+ *+ * @return A new builder.+ */+ public static Builder builder() {+ return new Builder();+ }++ /**+ * Returns instructions for AI tools.+ *+ * @return The instructions, or null when not provided.+ */+ @Nullable+ public String instructions() {+ return instructions;+ }++ /**+ * Returns alternative names and terms.+ *+ * @return A defensive copy of the synonyms, or {@code null} when not provided.+ */+ @Nullable+ public String[] synonyms() {+ return SemanticModelDefinition.copyOrNull(synonyms);+ }++ /**+ * Returns sample questions or use cases.+ *+ * @return A defensive copy of the examples, or {@code null} when not provided.+ */+ @Nullable+ public String[] examples() {+ return SemanticModelDefinition.copyOrNull(examples);+ }++ /**+ * Returns custom JSON-compatible properties not represented by the standard fields.+ *+ * <p>The returned map and every nested map or JSON array are unmodifiable. Java arrays supplied+ * to the builder are represented as unmodifiable lists. Integral numbers are represented as+ * {@link BigInteger}, and decimal numbers are represented as {@link BigDecimal}.+ *+ * @return The deeply immutable additional properties, preserving iteration order.+ */+ public Map<String, Object> additionalProperties() {+ return additionalProperties;+ }++ /**+ * Compares this structured AI context with another object.+ *+ * @param other The object to compare.+ * @return {@code true} if the object has the same standard and additional properties.+ */+ @Override+ public boolean equals(@Nullable Object other) {+ if (this == other) {+ return true;+ }+ if (!(other instanceof AIContextObject)) {+ return false;+ }+ AIContextObject that = (AIContextObject) other;+ return Objects.equals(instructions, that.instructions)+ && Arrays.equals(synonyms, that.synonyms)+ && Arrays.equals(examples, that.examples)+ && additionalProperties.equals(that.additionalProperties);+ }++ /**+ * Returns the hash code of this structured AI context.+ *+ * @return The hash code.+ */+ @Override+ public int hashCode() {+ int result = Objects.hash(instructions, additionalProperties);+ result = 31 * result + Arrays.hashCode(synonyms);+ result = 31 * result + Arrays.hashCode(examples);+ return result;+ }++ /**+ * Returns a string representation of this structured AI context.+ *+ * @return The string representation.+ */+ @Override+ public String toString() {+ return "AIContextObject{"+ + "instructions='"+ + instructions+ + '\''+ + ", synonyms="+ + Arrays.toString(synonyms)+ + ", examples="+ + Arrays.toString(examples)+ + ", additionalProperties="+ + additionalProperties+ + '}';+ }++ /** A builder for {@link AIContextObject}. */+ public static final class Builder {++ @Nullable private String instructions;+ @Nullable private String[] synonyms;+ @Nullable private String[] examples;+ private Map<String, Object> additionalProperties = Collections.emptyMap();++ private Builder() {}++ /**+ * Sets or clears instructions for AI tools.+ *+ * @param instructions The instructions, or null to leave them unset.+ * @return This builder.+ */+ public Builder withInstructions(@Nullable String instructions) {+ this.instructions = instructions;+ return this;+ }++ /**+ * Sets or clears alternative names and terms.+ *+ * @param synonyms The synonyms, or null to leave them unset.+ * @return This builder.+ */+ public Builder withSynonyms(@Nullable String[] synonyms) {+ this.synonyms = synonyms;+ return this;+ }++ /**+ * Sets or clears sample questions or use cases.+ *+ * @param examples The examples, or null to leave them unset.+ * @return This builder.+ */+ public Builder withExamples(@Nullable String[] examples) {+ this.examples = examples;+ return this;+ }++ /**+ * Sets additional JSON-compatible properties.+ *+ * <p>Values may be null, strings, booleans, JSON-compatible numbers, maps with string keys,+ * lists, or Java arrays. Integral numbers are normalized to {@link BigInteger}, and decimal+ * numbers are normalized to {@link BigDecimal} so their value semantics remain stable across+ * JSON round trips. Nested maps, lists, and arrays may be at most {@value+ * #MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH} levels deep. Property names must not duplicate {@code+ * instructions}, {@code synonyms}, or {@code examples}.+ *+ * @param additionalProperties The additional properties.+ * @return This builder.+ */+ public Builder withAdditionalProperties(Map<String, Object> additionalProperties) {+ this.additionalProperties = additionalProperties;+ return this;+ }++ /**+ * Builds structured AI context.+ *+ * @return The immutable structured AI context.+ * @throws IllegalArgumentException If a string array contains null, the additional properties+ * are null, a property duplicates a standard field, or a property value is not+ * JSON-compatible or exceeds the supported nesting depth.+ */+ public AIContextObject build() {+ SemanticModelDefinition.validateNoNullElements("synonyms", synonyms);+ SemanticModelDefinition.validateNoNullElements("examples", examples);+ Preconditions.checkArgument(+ additionalProperties != null, "additionalProperties must not be null");+ return new AIContextObject(this);+ }+ }++ private static Map<String, Object> immutableAdditionalProperties(Map<String, Object> properties) {+ Map<String, Object> result = new LinkedHashMap<>();+ IdentityHashMap<Object, Boolean> visiting = new IdentityHashMap<>();+ for (Map.Entry<String, Object> entry : properties.entrySet()) {+ String name = entry.getKey();+ Preconditions.checkArgument(name != null, "additional property name must not be null");+ Preconditions.checkArgument(+ !isStandardProperty(name),+ "additional property must not duplicate standard property: %s",+ name);+ result.put(name, immutableJsonValue(entry.getValue(), name, visiting, 0));+ }+ return Collections.unmodifiableMap(result);+ }++ private static Object immutableJsonValue(+ @Nullable Object value,+ String path,+ IdentityHashMap<Object, Boolean> visiting,+ int containerDepth) {+ if (value == null || value instanceof String || value instanceof Boolean) {+ return value;+ }+ if (value instanceof Number) {+ return canonicalizeJsonNumber((Number) value, path);+ }+ if (value instanceof Map) {+ return immutableJsonMap((Map<?, ?>) value, path, visiting, containerDepth + 1);+ }+ if (value instanceof List) {+ return immutableJsonList((List<?>) value, path, visiting, containerDepth + 1);+ }+ if (value.getClass().isArray()) {+ return immutableJsonArray(value, path, visiting, containerDepth + 1);+ }+ throw new IllegalArgumentException(+ String.format(+ "Additional property %s has non-JSON-compatible value type: %s",+ path, value.getClass().getName()));+ }++ private static Map<String, Object> immutableJsonMap(+ Map<?, ?> value, String path, IdentityHashMap<Object, Boolean> visiting, int containerDepth) {+ enterContainer(value, path, visiting, containerDepth);+ try {+ Map<String, Object> result = new LinkedHashMap<>();+ for (Map.Entry<?, ?> entry : value.entrySet()) {+ Preconditions.checkArgument(+ entry.getKey() instanceof String,+ "Additional property %s contains a map key that is not a string",+ path);+ String key = (String) entry.getKey();+ result.put(+ key, immutableJsonValue(entry.getValue(), path + "." + key, visiting, containerDepth));+ }+ return Collections.unmodifiableMap(result);+ } finally {+ visiting.remove(value);+ }+ }++ private static List<Object> immutableJsonList(+ List<?> value, String path, IdentityHashMap<Object, Boolean> visiting, int containerDepth) {+ enterContainer(value, path, visiting, containerDepth);+ try {+ List<Object> result = new ArrayList<>(value.size());+ for (int index = 0; index < value.size(); index++) {+ result.add(+ immutableJsonValue(+ value.get(index), path + "[" + index + "]", visiting, containerDepth));+ }+ return Collections.unmodifiableList(result);+ } finally {+ visiting.remove(value);+ }+ }++ private static List<Object> immutableJsonArray(+ Object value, String path, IdentityHashMap<Object, Boolean> visiting, int containerDepth) {+ enterContainer(value, path, visiting, containerDepth);+ try {+ int length = Array.getLength(value);+ List<Object> result = new ArrayList<>(length);+ for (int index = 0; index < length; index++) {+ result.add(+ immutableJsonValue(+ Array.get(value, index), path + "[" + index + "]", visiting, containerDepth));+ }+ return Collections.unmodifiableList(result);+ } finally {+ visiting.remove(value);+ }+ }++ private static Number canonicalizeJsonNumber(Number value, String path) {+ boolean supported =+ value instanceof Byte+ || value instanceof Short+ || value instanceof Integer+ || value instanceof Long+ || value instanceof Float+ || value instanceof Double+ || value instanceof BigInteger+ || value instanceof BigDecimal;+ Preconditions.checkArgument(+ supported,+ "Additional property %s has non-JSON-compatible number type: %s",+ path,+ value.getClass().getName());+ if (value instanceof BigInteger || value instanceof BigDecimal) {+ return value;+ }+ if (value instanceof Byte+ || value instanceof Short+ || value instanceof Integer+ || value instanceof Long) {+ return BigInteger.valueOf(value.longValue());+ }+ if (value instanceof Double) {+ double number = value.doubleValue();+ Preconditions.checkArgument(+ !Double.isNaN(number) && !Double.isInfinite(number),+ "Additional property %s must contain a finite number",+ path);+ } else {+ float number = value.floatValue();+ Preconditions.checkArgument(+ !Float.isNaN(number) && !Float.isInfinite(number),+ "Additional property %s must contain a finite number",+ path);+ }+ return new BigDecimal(value.toString());+ }++ private static void enterContainer(+ Object value, String path, IdentityHashMap<Object, Boolean> visiting, int containerDepth) {+ Preconditions.checkArgument(+ containerDepth <= MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH,+ "Additional property %s exceeds maximum nesting depth of %s",+ path,+ MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH);+ Preconditions.checkArgument(+ !visiting.containsKey(value), "Additional property %s contains a cyclic value", path);+ visiting.put(value, Boolean.TRUE);+ }++ private static boolean isStandardProperty(String name) {+ return "instructions".equals(name) || "synonyms".equals(name) || "examples".equals(name);+ }+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/CustomExtension.java b/api/src/main/java/org/apache/gravitino/semantic/CustomExtension.javanew file mode 100644index 0000000000..1b0b8a8e6c--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/CustomExtension.java@@ -0,0 +1,145 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import com.google.common.base.Preconditions;+import java.util.Objects;+import javax.annotation.Nullable;+import org.apache.gravitino.annotation.Evolving;++/** Vendor-specific Semantic Model attributes retained for extensibility. */+@Evolving+public final class CustomExtension {++ private final String vendorName;+ private final String data;++ private CustomExtension(Builder builder) {+ this.vendorName = builder.vendorName;+ this.data = builder.data;+ }++ /**+ * Creates a builder for a custom extension.+ *+ * @return A new builder.+ */+ public static Builder builder() {+ return new Builder();+ }++ /**+ * Returns the vendor name associated with this extension.+ *+ * @return The vendor name.+ */+ public String vendorName() {+ return vendorName;+ }++ /**+ * Returns the vendor-specific data encoded as a JSON string.+ *+ * @return The extension data.+ */+ public String data() {+ return data;+ }++ /**+ * Compares this custom extension with another object.+ *+ * @param other The object to compare.+ * @return {@code true} if the object has the same vendor name and data.+ */+ @Override+ public boolean equals(@Nullable Object other) {+ if (this == other) {+ return true;+ }+ if (!(other instanceof CustomExtension)) {+ return false;+ }+ CustomExtension that = (CustomExtension) other;+ return vendorName.equals(that.vendorName) && data.equals(that.data);+ }++ /**+ * Returns the hash code of this custom extension.+ *+ * @return The hash code.+ */+ @Override+ public int hashCode() {+ return Objects.hash(vendorName, data);+ }++ /**+ * Returns a string representation of this custom extension.+ *+ * @return The string representation.+ */+ @Override+ public String toString() {+ return "CustomExtension{" + "vendorName='" + vendorName + '\'' + ", data='" + data + '\'' + '}';+ }++ /** A builder for {@link CustomExtension}. */+ public static final class Builder {++ private String vendorName;+ private String data;++ private Builder() {}++ /**+ * Sets the vendor name.+ *+ * @param vendorName The vendor name.+ * @return This builder.+ */+ public Builder withVendorName(String vendorName) {+ this.vendorName = vendorName;+ return this;+ }++ /**+ * Sets the vendor-specific data encoded as a JSON string.+ *+ * @param data The extension data.+ * @return This builder.+ */+ public Builder withData(String data) {+ this.data = data;+ return this;+ }++ /**+ * Builds a custom extension.+ *+ * @return The immutable custom extension.+ * @throws IllegalArgumentException If the vendor name or data is null.+ */+ public CustomExtension build() {+ Preconditions.checkArgument(vendorName != null, "vendorName must not be null");+ Preconditions.checkArgument(data != null, "data must not be null");+ return new CustomExtension(this);+ }+ }+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/DataType.java b/api/src/main/java/org/apache/gravitino/semantic/DataType.javanew file mode 100644index 0000000000..9266720747--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/DataType.java@@ -0,0 +1,59 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import org.apache.gravitino.annotation.Evolving;++/**+ * Logical data types for Semantic Model fields and metrics, derived from the Apache Ossie logical+ * type vocabulary. These types are independent of physical relational column types and are not+ * inferred from source schemas.+ */+@Evolving+public enum DataType {+ /** A string value. */+ STRING,++ /** An integer value. */+ INTEGER,++ /** An exact base-10 decimal value with unspecified precision and scale. */+ DECIMAL,++ /** An approximate floating-point value. */+ FLOAT,++ /** A boolean value. */+ BOOLEAN,++ /** A date without a time of day. */+ DATE,++ /** A time of day without a date. */+ TIME,++ /** A date and time without a timezone or offset. */+ DATE_TIME,++ /** A date and time that identifies an instant using timezone or offset context. */+ DATE_TIME_TZ,++ /** A known logical type outside the portable type vocabulary. */+ OPAQUE+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/Dataset.java b/api/src/main/java/org/apache/gravitino/semantic/Dataset.javanew file mode 100644index 0000000000..d7e7c7336f--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/Dataset.java@@ -0,0 +1,364 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import com.google.common.base.Preconditions;+import java.util.Arrays;+import java.util.Objects;+import javax.annotation.Nullable;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.annotation.Evolving;++/**+ * An immutable dataset in a semantic model. A dataset binds a semantic name and optional semantic+ * metadata to a governed Gravitino table or logical view identified by {@link NameIdentifier}.+ */+@Evolving+public final class Dataset {++ private final String name;+ private final NameIdentifier source;++ @Nullable private final String[] primaryKey;+ @Nullable private final String[][] uniqueKeys;+ @Nullable private final String description;+ @Nullable private final AIContext aiContext;+ @Nullable private final Field[] fields;+ @Nullable private final CustomExtension[] customExtensions;++ private Dataset(Builder builder) {+ this.name = builder.name;+ this.source = builder.source;+ this.primaryKey = SemanticModelDefinition.copyOrNull(builder.primaryKey);+ this.uniqueKeys = copyUniqueKeys(builder.uniqueKeys);+ this.description = builder.description;+ this.aiContext = builder.aiContext;+ this.fields = SemanticModelDefinition.copyOrNull(builder.fields);+ this.customExtensions = SemanticModelDefinition.copyOrNull(builder.customExtensions);+ }++ /**+ * Creates a builder for an immutable {@link Dataset}.+ *+ * @return A new builder.+ */+ public static Builder builder() {+ return new Builder();+ }++ /**+ * Returns the dataset name.+ *+ * @return The dataset name.+ */+ public String name() {+ return name;+ }++ /**+ * Returns the governed table or logical view that backs this dataset.+ *+ * @return The source identifier.+ */+ public NameIdentifier source() {+ return source;+ }++ /**+ * Returns a copy of the primary key columns.+ *+ * @return The primary key columns, or {@code null} if they are not set.+ */+ @Nullable+ public String[] primaryKey() {+ return SemanticModelDefinition.copyOrNull(primaryKey);+ }++ /**+ * Returns a deep copy of the unique key definitions.+ *+ * @return The unique keys, or {@code null} if they are not set.+ */+ @Nullable+ public String[][] uniqueKeys() {+ return copyUniqueKeys(uniqueKeys);+ }++ /**+ * Returns the dataset description.+ *+ * @return The dataset description, or {@code null} if it is not set.+ */+ @Nullable+ public String description() {+ return description;+ }++ /**+ * Returns the AI context associated with the dataset.+ *+ * @return The AI context, or {@code null} if it is not set.+ */+ @Nullable+ public AIContext aiContext() {+ return aiContext;+ }++ /**+ * Returns a copy of the fields defined by the dataset.+ *+ * @return The fields, or {@code null} if they are not set.+ */+ @Nullable+ public Field[] fields() {+ return SemanticModelDefinition.copyOrNull(fields);+ }++ /**+ * Returns a copy of the custom extensions associated with the dataset.+ *+ * @return The custom extensions, or {@code null} if they are not set.+ */+ @Nullable+ public CustomExtension[] customExtensions() {+ return SemanticModelDefinition.copyOrNull(customExtensions);+ }++ /**+ * Compares this dataset with another object for value equality.+ *+ * @param other The object to compare with.+ * @return {@code true} if the objects are equal, otherwise {@code false}.+ */+ @Override+ public boolean equals(@Nullable Object other) {+ if (this == other) {+ return true;+ }+ if (!(other instanceof Dataset)) {+ return false;+ }+ Dataset that = (Dataset) other;+ return name.equals(that.name)+ && source.equals(that.source)+ && Arrays.equals(primaryKey, that.primaryKey)+ && Arrays.deepEquals(uniqueKeys, that.uniqueKeys)+ && Objects.equals(description, that.description)+ && Objects.equals(aiContext, that.aiContext)+ && Arrays.equals(fields, that.fields)+ && Arrays.equals(customExtensions, that.customExtensions);+ }++ /**+ * Returns the value-based hash code for this dataset.+ *+ * @return The hash code.+ */+ @Override+ public int hashCode() {+ return Objects.hash(+ name,+ source,+ Arrays.hashCode(primaryKey),+ Arrays.deepHashCode(uniqueKeys),+ description,+ aiContext,+ Arrays.hashCode(fields),+ Arrays.hashCode(customExtensions));+ }++ /**+ * Returns a string representation of this dataset.+ *+ * @return The string representation.+ */+ @Override+ public String toString() {+ return "Dataset{"+ + "name='"+ + name+ + '\''+ + ", source="+ + source+ + ", primaryKey="+ + Arrays.toString(primaryKey)+ + ", uniqueKeys="+ + Arrays.deepToString(uniqueKeys)+ + ", description='"+ + description+ + '\''+ + ", aiContext="+ + aiContext+ + ", fields="+ + Arrays.toString(fields)+ + ", customExtensions="+ + Arrays.toString(customExtensions)+ + '}';+ }++ /** A builder for immutable {@link Dataset} values. */+ public static final class Builder {++ private String name;+ private NameIdentifier source;++ @Nullable private String[] primaryKey;+ @Nullable private String[][] uniqueKeys;+ @Nullable private String description;+ @Nullable private AIContext aiContext;+ @Nullable private Field[] fields;+ @Nullable private CustomExtension[] customExtensions;++ private Builder() {}++ /**+ * Sets the dataset name.+ *+ * @param name The non-empty dataset name.+ * @return This builder.+ */+ public Builder withName(String name) {+ this.name = name;+ return this;+ }++ /**+ * Sets the governed table or logical view that backs this dataset.+ *+ * @param source The source identifier.+ * @return This builder.+ */+ public Builder withSource(NameIdentifier source) {+ this.source = source;+ return this;+ }++ /**+ * Sets the optional primary key columns.+ *+ * @param primaryKey The primary key columns, or {@code null} to leave them unset.+ * @return This builder.+ */+ public Builder withPrimaryKey(@Nullable String[] primaryKey) {+ this.primaryKey = primaryKey;+ return this;+ }++ /**+ * Sets the optional unique key definitions.+ *+ * @param uniqueKeys The unique keys, or {@code null} to leave them unset.+ * @return This builder.+ */+ public Builder withUniqueKeys(@Nullable String[][] uniqueKeys) {+ this.uniqueKeys = uniqueKeys;+ return this;+ }++ /**+ * Sets the optional dataset description.+ *+ * @param description The description, or {@code null} to leave it unset.+ * @return This builder.+ */+ public Builder withDescription(@Nullable String description) {+ this.description = description;+ return this;+ }++ /**+ * Sets the optional AI context.+ *+ * @param aiContext The AI context, or {@code null} to leave it unset.+ * @return This builder.+ */+ public Builder withAIContext(@Nullable AIContext aiContext) {+ this.aiContext = aiContext;+ return this;+ }++ /**+ * Sets the optional semantic fields.+ *+ * @param fields The fields, or {@code null} to leave them unset.+ * @return This builder.+ */+ public Builder withFields(@Nullable Field[] fields) {+ this.fields = fields;+ return this;+ }++ /**+ * Sets the optional custom extensions.+ *+ * @param customExtensions The custom extensions, or {@code null} to leave them unset.+ * @return This builder.+ */+ public Builder withCustomExtensions(@Nullable CustomExtension[] customExtensions) {+ this.customExtensions = customExtensions;+ return this;+ }++ /**+ * Builds an immutable {@link Dataset}.+ *+ * @return The new dataset.+ * @throws IllegalArgumentException If the name is null or empty, the source is null, or an+ * optional array contains an invalid element.+ */+ public Dataset build() {+ Preconditions.checkArgument(+ name != null && !name.isEmpty(), "name must not be null or empty");+ Preconditions.checkArgument(source != null, "source must not be null");+ SemanticModelDefinition.validateNonEmptyStringElements("primaryKey", primaryKey);+ validateUniqueKeys(uniqueKeys);+ SemanticModelDefinition.validateNoNullElements("fields", fields);+ SemanticModelDefinition.validateNoNullElements("customExtensions", customExtensions);+ return new Dataset(this);+ }+ }++ @Nullable+ private static String[][] copyUniqueKeys(@Nullable String[][] uniqueKeys) {+ if (uniqueKeys == null) {+ return null;+ }++ String[][] copy = new String[uniqueKeys.length][];+ for (int index = 0; index < uniqueKeys.length; index++) {+ copy[index] = Arrays.copyOf(uniqueKeys[index], uniqueKeys[index].length);+ }+ return copy;+ }++ 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);+ SemanticModelDefinition.validateNonEmptyStringElements(+ "uniqueKeys[" + index + "]", uniqueKey);+ }+ }+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/DialectExpression.java b/api/src/main/java/org/apache/gravitino/semantic/DialectExpression.javanew file mode 100644index 0000000000..07abe3ad86--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/DialectExpression.java@@ -0,0 +1,147 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import com.google.common.base.Preconditions;+import java.util.Objects;+import javax.annotation.Nullable;+import org.apache.gravitino.annotation.Evolving;++/** An expression written in a specific dialect. */+@Evolving+public final class DialectExpression {++ private final String dialect;+ private final String expression;++ private DialectExpression(Builder builder) {+ this.dialect = builder.dialect;+ this.expression = builder.expression;+ }++ /**+ * Creates a builder for a dialect expression.+ *+ * @return A new builder.+ */+ public static Builder builder() {+ return new Builder();+ }++ /**+ * Returns the dialect in which the expression is written.+ *+ * @return The expression dialect identifier.+ */+ public String dialect() {+ return dialect;+ }++ /**+ * Returns the dialect-specific expression text.+ *+ * @return The non-empty expression text.+ */+ public String expression() {+ return expression;+ }++ /**+ * Compares this dialect expression with another object.+ *+ * @param other The object to compare.+ * @return {@code true} if the object has the same dialect and expression text.+ */+ @Override+ public boolean equals(@Nullable Object other) {+ if (this == other) {+ return true;+ }+ if (!(other instanceof DialectExpression)) {+ return false;+ }+ DialectExpression that = (DialectExpression) other;+ return dialect.equals(that.dialect) && expression.equals(that.expression);+ }++ /**+ * Returns the hash code of this dialect expression.+ *+ * @return The hash code.+ */+ @Override+ public int hashCode() {+ return Objects.hash(dialect, expression);+ }++ /**+ * Returns a string representation of this dialect expression.+ *+ * @return The string representation.+ */+ @Override+ public String toString() {+ return "DialectExpression{" + "dialect=" + dialect + ", expression='" + expression + '\'' + '}';+ }++ /** A builder for {@link DialectExpression}. */+ public static final class Builder {++ private String dialect;+ private String expression;++ private Builder() {}++ /**+ * Sets the expression dialect.+ *+ * @param dialect The non-empty expression dialect identifier.+ * @return This builder.+ */+ public Builder withDialect(String dialect) {+ this.dialect = dialect;+ return this;+ }++ /**+ * Sets the dialect-specific expression text.+ *+ * @param expression The non-empty expression text.+ * @return This builder.+ */+ public Builder withExpression(String expression) {+ this.expression = expression;+ return this;+ }++ /**+ * Builds a dialect expression.+ *+ * @return The immutable dialect expression.+ * @throws IllegalArgumentException If the dialect or expression is null or empty.+ */+ public DialectExpression build() {+ Preconditions.checkArgument(+ dialect != null && !dialect.isEmpty(), "dialect must not be null or empty");+ Preconditions.checkArgument(+ expression != null && !expression.isEmpty(), "expression must not be null or empty");+ return new DialectExpression(this);+ }+ }+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/Dialects.java b/api/src/main/java/org/apache/gravitino/semantic/Dialects.javanew file mode 100644index 0000000000..3c052c9824--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/Dialects.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.semantic;++import org.apache.gravitino.annotation.Evolving;++/**+ * Well-known dialect identifiers for Semantic Model expressions.+ *+ * <p>These constants match the dialects defined by the pinned Apache Ossie schema. Applications may+ * use other non-empty identifiers; Gravitino preserves them without implicit conversion or fallback+ * so consumers can select the dialects they support.+ */+@Evolving+public final class Dialects {++ /** ANSI SQL. */+ public static final String ANSI_SQL = "ANSI_SQL";++ /** Snowflake SQL. */+ public static final String SNOWFLAKE = "SNOWFLAKE";++ /** Multidimensional Expressions (MDX). */+ public static final String MDX = "MDX";++ /** Tableau expression syntax. */+ public static final String TABLEAU = "TABLEAU";++ /** Databricks SQL. */+ public static final String DATABRICKS = "DATABRICKS";++ /** Multi-Dimensional Analytical Query Language (MAQL). */+ public static final String MAQL = "MAQL";++ /** Google BigQuery SQL. */+ public static final String BIGQUERY = "BIGQUERY";++ private Dialects() {}+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/Dimension.java b/api/src/main/java/org/apache/gravitino/semantic/Dimension.javanew file mode 100644index 0000000000..b1a1d11b91--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/Dimension.java@@ -0,0 +1,120 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import java.util.Objects;+import javax.annotation.Nullable;+import org.apache.gravitino.annotation.Evolving;++/** Metadata that identifies a Semantic Model field as a dimension. */+@Evolving+public final class Dimension {++ @Nullable private final Boolean isTime;++ private Dimension(Builder builder) {+ this.isTime = builder.isTime;+ }++ /**+ * Creates a builder for dimension metadata.+ *+ * @return A new builder.+ */+ public static Builder builder() {+ return new Builder();+ }++ /**+ * Returns the explicit time-dimension role marker.+ *+ * @return {@code true} or {@code false} when explicitly set, or null when the role should use the+ * datatype-dependent default.+ */+ @Nullable+ public Boolean isTime() {+ return isTime;+ }++ /**+ * Compares this dimension metadata with another object.+ *+ * @param other The object to compare.+ * @return {@code true} if the object has the same explicit time-dimension marker.+ */+ @Override+ public boolean equals(@Nullable Object other) {+ if (this == other) {+ return true;+ }+ if (!(other instanceof Dimension)) {+ return false;+ }+ Dimension that = (Dimension) other;+ return Objects.equals(isTime, that.isTime);+ }++ /**+ * Returns the hash code of this dimension metadata.+ *+ * @return The hash code.+ */+ @Override+ public int hashCode() {+ return Objects.hash(isTime);+ }++ /**+ * Returns a string representation of this dimension metadata.+ *+ * @return The string representation.+ */+ @Override+ public String toString() {+ return "Dimension{" + "isTime=" + isTime + '}';+ }++ /** A builder for {@link Dimension}. */+ public static final class Builder {++ @Nullable private Boolean isTime;++ private Builder() {}++ /**+ * Sets or clears the explicit time-dimension role marker.+ *+ * @param isTime The explicit marker, or null to leave it unset.+ * @return This builder.+ */+ public Builder withIsTime(@Nullable Boolean isTime) {+ this.isTime = isTime;+ return this;+ }++ /**+ * Builds dimension metadata.+ *+ * @return The immutable dimension metadata.+ */+ public Dimension build() {+ return new Dimension(this);+ }+ }+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/Expression.java b/api/src/main/java/org/apache/gravitino/semantic/Expression.javanew file mode 100644index 0000000000..6987195879--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/Expression.java@@ -0,0 +1,134 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import com.google.common.base.Preconditions;+import java.util.Arrays;+import java.util.HashSet;+import java.util.Set;+import javax.annotation.Nullable;+import org.apache.gravitino.annotation.Evolving;++/** A Semantic Model expression with one representation per dialect identifier. */+@Evolving+public final class Expression {++ private final DialectExpression[] dialects;++ private Expression(Builder builder) {+ this.dialects = Arrays.copyOf(builder.dialects, builder.dialects.length);+ }++ /**+ * Creates a builder for an expression.+ *+ * @return A new builder.+ */+ public static Builder builder() {+ return new Builder();+ }++ /**+ * Returns the ordered dialect-specific representations of this expression.+ *+ * @return A defensive copy of the non-empty dialect expression array.+ */+ public DialectExpression[] dialects() {+ return Arrays.copyOf(dialects, dialects.length);+ }++ /**+ * Compares this expression with another object.+ *+ * @param other The object to compare.+ * @return {@code true} if the object has the same ordered dialect expressions.+ */+ @Override+ public boolean equals(@Nullable Object other) {+ if (this == other) {+ return true;+ }+ if (!(other instanceof Expression)) {+ return false;+ }+ Expression that = (Expression) other;+ return Arrays.equals(dialects, that.dialects);+ }++ /**+ * Returns the hash code of this expression.+ *+ * @return The hash code.+ */+ @Override+ public int hashCode() {+ return Arrays.hashCode(dialects);+ }++ /**+ * Returns a string representation of this expression.+ *+ * @return The string representation.+ */+ @Override+ public String toString() {+ return "Expression{" + "dialects=" + Arrays.toString(dialects) + '}';+ }++ /** A builder for {@link Expression}. */+ public static final class Builder {++ private DialectExpression[] dialects;++ private Builder() {}++ /**+ * Sets the ordered dialect-specific representations of the expression.+ *+ * @param dialects The non-empty dialect expression array. Each dialect may occur at most once.+ * @return This builder.+ */+ public Builder withDialects(DialectExpression[] dialects) {+ this.dialects = dialects;+ return this;+ }++ /**+ * Builds an expression.+ *+ * @return The immutable expression.+ * @throws IllegalArgumentException If the array is null or empty, contains null, or contains a+ * duplicate dialect.+ */+ public Expression build() {+ Preconditions.checkArgument(+ dialects != null && dialects.length > 0, "dialects must not be null or empty");+ SemanticModelDefinition.validateNoNullElements("dialects", dialects);++ Set<String> seenDialects = new HashSet<>();+ for (DialectExpression dialectExpression : dialects) {+ Preconditions.checkArgument(+ seenDialects.add(dialectExpression.dialect()),+ "dialects must not contain duplicate dialect: %s",+ dialectExpression.dialect());+ }+ return new Expression(this);+ }+ }+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/Field.java b/api/src/main/java/org/apache/gravitino/semantic/Field.javanew file mode 100644index 0000000000..074826b5e4--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/Field.java@@ -0,0 +1,333 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import com.google.common.base.Preconditions;+import java.util.Arrays;+import java.util.Objects;+import javax.annotation.Nullable;+import org.apache.gravitino.annotation.Evolving;++/**+ * An immutable semantic field in a {@link Dataset}. A field gives a name to an {@link Expression}+ * and may carry dimension, display, type, AI, and extension metadata.+ */+@Evolving+public final class Field {++ private final String name;+ private final Expression expression;++ @Nullable private final Dimension dimension;+ @Nullable private final String label;+ @Nullable private final String description;+ @Nullable private final DataType datatype;+ @Nullable private final AIContext aiContext;+ @Nullable private final CustomExtension[] customExtensions;++ private Field(Builder builder) {+ this.name = builder.name;+ this.expression = builder.expression;+ this.dimension = builder.dimension;+ this.label = builder.label;+ this.description = builder.description;+ this.datatype = builder.datatype;+ this.aiContext = builder.aiContext;+ this.customExtensions = SemanticModelDefinition.copyOrNull(builder.customExtensions);+ }++ /**+ * Creates a builder for an immutable {@link Field}.+ *+ * @return A new builder.+ */+ public static Builder builder() {+ return new Builder();+ }++ /**+ * Returns the field name.+ *+ * @return The field name.+ */+ public String name() {+ return name;+ }++ /**+ * Returns the expression that defines the field.+ *+ * @return The field expression.+ */+ public Expression expression() {+ return expression;+ }++ /**+ * Returns the dimension metadata for the field.+ *+ * @return The dimension metadata, or {@code null} if it is not set.+ */+ @Nullable+ public Dimension dimension() {+ return dimension;+ }++ /**+ * Returns the display label for the field.+ *+ * @return The field label, or {@code null} if it is not set.+ */+ @Nullable+ public String label() {+ return label;+ }++ /**+ * Returns the field description.+ *+ * @return The field description, or {@code null} if it is not set.+ */+ @Nullable+ public String description() {+ return description;+ }++ /**+ * Returns the semantic data type of the field.+ *+ * @return The semantic data type, or {@code null} if it is not set.+ */+ @Nullable+ public DataType datatype() {+ return datatype;+ }++ /**+ * Returns the AI context associated with the field.+ *+ * @return The AI context, or {@code null} if it is not set.+ */+ @Nullable+ public AIContext aiContext() {+ return aiContext;+ }++ /**+ * Returns a copy of the custom extensions associated with the field.+ *+ * @return The custom extensions, or {@code null} if they are not set.+ */+ @Nullable+ public CustomExtension[] customExtensions() {+ return SemanticModelDefinition.copyOrNull(customExtensions);+ }++ /**+ * Compares this field with another object for value equality.+ *+ * @param other The object to compare with.+ * @return {@code true} if the objects are equal, otherwise {@code false}.+ */+ @Override+ public boolean equals(@Nullable Object other) {+ if (this == other) {+ return true;+ }+ if (!(other instanceof Field)) {+ return false;+ }+ Field that = (Field) other;+ return name.equals(that.name)+ && expression.equals(that.expression)+ && Objects.equals(dimension, that.dimension)+ && Objects.equals(label, that.label)+ && Objects.equals(description, that.description)+ && datatype == that.datatype+ && Objects.equals(aiContext, that.aiContext)+ && Arrays.equals(customExtensions, that.customExtensions);+ }++ /**+ * Returns the value-based hash code for this field.+ *+ * @return The hash code.+ */+ @Override+ public int hashCode() {+ return Objects.hash(+ name,+ expression,+ dimension,+ label,+ description,+ datatype,+ aiContext,+ Arrays.hashCode(customExtensions));+ }++ /**+ * Returns a string representation of this field.+ *+ * @return The string representation.+ */+ @Override+ public String toString() {+ return "Field{"+ + "name='"+ + name+ + '\''+ + ", expression="+ + expression+ + ", dimension="+ + dimension+ + ", label='"+ + label+ + '\''+ + ", description='"+ + description+ + '\''+ + ", datatype="+ + datatype+ + ", aiContext="+ + aiContext+ + ", customExtensions="+ + Arrays.toString(customExtensions)+ + '}';+ }++ /** A builder for immutable {@link Field} values. */+ public static final class Builder {++ private String name;+ private Expression expression;++ @Nullable private Dimension dimension;+ @Nullable private String label;+ @Nullable private String description;+ @Nullable private DataType datatype;+ @Nullable private AIContext aiContext;+ @Nullable private CustomExtension[] customExtensions;++ private Builder() {}++ /**+ * Sets the field name.+ *+ * @param name The non-empty field name.+ * @return This builder.+ */+ public Builder withName(String name) {+ this.name = name;+ return this;+ }++ /**+ * Sets the expression that defines the field.+ *+ * @param expression The field expression.+ * @return This builder.+ */+ public Builder withExpression(Expression expression) {+ this.expression = expression;+ return this;+ }++ /**+ * Sets the optional dimension metadata.+ *+ * @param dimension The dimension metadata, or {@code null} to leave it unset.+ * @return This builder.+ */+ public Builder withDimension(@Nullable Dimension dimension) {+ this.dimension = dimension;+ return this;+ }++ /**+ * Sets the optional display label.+ *+ * @param label The display label, or {@code null} to leave it unset.+ * @return This builder.+ */+ public Builder withLabel(@Nullable String label) {+ this.label = label;+ return this;+ }++ /**+ * Sets the optional field description.+ *+ * @param description The field description, or {@code null} to leave it unset.+ * @return This builder.+ */+ public Builder withDescription(@Nullable String description) {+ this.description = description;+ return this;+ }++ /**+ * Sets the optional semantic data type.+ *+ * @param datatype The semantic data type, or {@code null} to leave it unset.+ * @return This builder.+ */+ public Builder withDatatype(@Nullable DataType datatype) {+ this.datatype = datatype;+ return this;+ }++ /**+ * Sets the optional AI context.+ *+ * @param aiContext The AI context, or {@code null} to leave it unset.+ * @return This builder.+ */+ public Builder withAIContext(@Nullable AIContext aiContext) {+ this.aiContext = aiContext;+ return this;+ }++ /**+ * Sets the optional custom extensions.+ *+ * @param customExtensions The custom extensions, or {@code null} to leave them unset.+ * @return This builder.+ */+ public Builder withCustomExtensions(@Nullable CustomExtension[] customExtensions) {+ this.customExtensions = customExtensions;+ return this;+ }++ /**+ * Builds an immutable {@link Field}.+ *+ * @return The new field.+ * @throws IllegalArgumentException If the name is null or empty, the expression is null, or the+ * custom extension array contains null.+ */+ public Field build() {+ Preconditions.checkArgument(+ name != null && !name.isEmpty(), "name must not be null or empty");+ Preconditions.checkArgument(expression != null, "expression must not be null");+ SemanticModelDefinition.validateNoNullElements("customExtensions", customExtensions);+ return new Field(this);+ }+ }+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/Metric.java b/api/src/main/java/org/apache/gravitino/semantic/Metric.javanew file mode 100644index 0000000000..64f7f5eeef--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/Metric.java@@ -0,0 +1,272 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import com.google.common.base.Preconditions;+import java.util.Arrays;+import java.util.Objects;+import javax.annotation.Nullable;+import org.apache.gravitino.annotation.Evolving;++/**+ * An immutable metric in a semantic model. A metric gives a model-scoped name to an aggregate or+ * otherwise calculated {@link Expression} and may carry descriptive, type, AI, and extension+ * metadata.+ */+@Evolving+public final class Metric {++ private final String name;+ private final Expression expression;++ @Nullable private final String description;+ @Nullable private final DataType datatype;+ @Nullable private final AIContext aiContext;+ @Nullable private final CustomExtension[] customExtensions;++ private Metric(Builder builder) {+ this.name = builder.name;+ this.expression = builder.expression;+ this.description = builder.description;+ this.datatype = builder.datatype;+ this.aiContext = builder.aiContext;+ this.customExtensions = SemanticModelDefinition.copyOrNull(builder.customExtensions);+ }++ /**+ * Creates a builder for an immutable {@link Metric}.+ *+ * @return A new builder.+ */+ public static Builder builder() {+ return new Builder();+ }++ /**+ * Returns the metric name.+ *+ * @return The metric name.+ */+ public String name() {+ return name;+ }++ /**+ * Returns the expression that defines the metric.+ *+ * @return The metric expression.+ */+ public Expression expression() {+ return expression;+ }++ /**+ * Returns the metric description.+ *+ * @return The metric description, or {@code null} if it is not set.+ */+ @Nullable+ public String description() {+ return description;+ }++ /**+ * Returns the semantic data type of the metric.+ *+ * @return The semantic data type, or {@code null} if it is not set.+ */+ @Nullable+ public DataType datatype() {+ return datatype;+ }++ /**+ * Returns the AI context associated with the metric.+ *+ * @return The AI context, or {@code null} if it is not set.+ */+ @Nullable+ public AIContext aiContext() {+ return aiContext;+ }++ /**+ * Returns a copy of the custom extensions associated with the metric.+ *+ * @return The custom extensions, or {@code null} if they are not set.+ */+ @Nullable+ public CustomExtension[] customExtensions() {+ return SemanticModelDefinition.copyOrNull(customExtensions);+ }++ /**+ * Compares this metric with another object for value equality.+ *+ * @param other The object to compare with.+ * @return {@code true} if the objects are equal, otherwise {@code false}.+ */+ @Override+ public boolean equals(@Nullable Object other) {+ if (this == other) {+ return true;+ }+ if (!(other instanceof Metric)) {+ return false;+ }+ Metric that = (Metric) other;+ return name.equals(that.name)+ && expression.equals(that.expression)+ && Objects.equals(description, that.description)+ && datatype == that.datatype+ && Objects.equals(aiContext, that.aiContext)+ && Arrays.equals(customExtensions, that.customExtensions);+ }++ /**+ * Returns the value-based hash code for this metric.+ *+ * @return The hash code.+ */+ @Override+ public int hashCode() {+ return Objects.hash(+ name, expression, description, datatype, aiContext, Arrays.hashCode(customExtensions));+ }++ /**+ * Returns a string representation of this metric.+ *+ * @return The string representation.+ */+ @Override+ public String toString() {+ return "Metric{"+ + "name='"+ + name+ + '\''+ + ", expression="+ + expression+ + ", description='"+ + description+ + '\''+ + ", datatype="+ + datatype+ + ", aiContext="+ + aiContext+ + ", customExtensions="+ + Arrays.toString(customExtensions)+ + '}';+ }++ /** A builder for immutable {@link Metric} values. */+ public static final class Builder {++ private String name;+ private Expression expression;++ @Nullable private String description;+ @Nullable private DataType datatype;+ @Nullable private AIContext aiContext;+ @Nullable private CustomExtension[] customExtensions;++ private Builder() {}++ /**+ * Sets the metric name.+ *+ * @param name The non-empty metric name.+ * @return This builder.+ */+ public Builder withName(String name) {+ this.name = name;+ return this;+ }++ /**+ * Sets the expression that defines the metric.+ *+ * @param expression The metric expression.+ * @return This builder.+ */+ public Builder withExpression(Expression expression) {+ this.expression = expression;+ return this;+ }++ /**+ * Sets the optional metric description.+ *+ * @param description The metric description, or {@code null} to leave it unset.+ * @return This builder.+ */+ public Builder withDescription(@Nullable String description) {+ this.description = description;+ return this;+ }++ /**+ * Sets the optional semantic data type.+ *+ * @param datatype The semantic data type, or {@code null} to leave it unset.+ * @return This builder.+ */+ public Builder withDatatype(@Nullable DataType datatype) {+ this.datatype = datatype;+ return this;+ }++ /**+ * Sets the optional AI context.+ *+ * @param aiContext The AI context, or {@code null} to leave it unset.+ * @return This builder.+ */+ public Builder withAIContext(@Nullable AIContext aiContext) {+ this.aiContext = aiContext;+ return this;+ }++ /**+ * Sets the optional custom extensions.+ *+ * @param customExtensions The custom extensions, or {@code null} to leave them unset.+ * @return This builder.+ */+ public Builder withCustomExtensions(@Nullable CustomExtension[] customExtensions) {+ this.customExtensions = customExtensions;+ return this;+ }++ /**+ * Builds an immutable {@link Metric}.+ *+ * @return The new metric.+ * @throws IllegalArgumentException If the name is null or empty, the expression is null, or the+ * custom extension array contains null.+ */+ public Metric build() {+ Preconditions.checkArgument(+ name != null && !name.isEmpty(), "name must not be null or empty");+ Preconditions.checkArgument(expression != null, "expression must not be null");+ SemanticModelDefinition.validateNoNullElements("customExtensions", customExtensions);+ return new Metric(this);+ }+ }+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/Relationship.java b/api/src/main/java/org/apache/gravitino/semantic/Relationship.javanew file mode 100644index 0000000000..e6dc0ba2d0--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/Relationship.java@@ -0,0 +1,314 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import com.google.common.base.Preconditions;+import java.util.Arrays;+import java.util.Objects;+import javax.annotation.Nullable;+import org.apache.gravitino.annotation.Evolving;++/**+ * An immutable relationship between two datasets in the same semantic model. The endpoint column+ * arrays describe the corresponding join columns on the source and target datasets.+ */+@Evolving+public final class Relationship {++ private final String name;+ private final String from;+ private final String to;+ private final String[] fromColumns;+ private final String[] toColumns;++ @Nullable private final AIContext aiContext;+ @Nullable private final CustomExtension[] customExtensions;++ private Relationship(Builder builder) {+ this.name = builder.name;+ this.from = builder.from;+ this.to = builder.to;+ this.fromColumns = Arrays.copyOf(builder.fromColumns, builder.fromColumns.length);+ this.toColumns = Arrays.copyOf(builder.toColumns, builder.toColumns.length);+ this.aiContext = builder.aiContext;+ this.customExtensions = SemanticModelDefinition.copyOrNull(builder.customExtensions);+ }++ /**+ * Creates a builder for an immutable {@link Relationship}.+ *+ * @return A new builder.+ */+ public static Builder builder() {+ return new Builder();+ }++ /**+ * Returns the relationship name.+ *+ * @return The relationship name.+ */+ public String name() {+ return name;+ }++ /**+ * Returns the name of the source dataset.+ *+ * @return The source dataset name.+ */+ public String from() {+ return from;+ }++ /**+ * Returns the name of the target dataset.+ *+ * @return The target dataset name.+ */+ public String to() {+ return to;+ }++ /**+ * Returns a copy of the source dataset columns.+ *+ * @return The source columns.+ */+ public String[] fromColumns() {+ return Arrays.copyOf(fromColumns, fromColumns.length);+ }++ /**+ * Returns a copy of the target dataset columns.+ *+ * @return The target columns.+ */+ public String[] toColumns() {+ return Arrays.copyOf(toColumns, toColumns.length);+ }++ /**+ * Returns the AI context associated with the relationship.+ *+ * @return The AI context, or {@code null} if it is not set.+ */+ @Nullable+ public AIContext aiContext() {+ return aiContext;+ }++ /**+ * Returns a copy of the custom extensions associated with the relationship.+ *+ * @return The custom extensions, or {@code null} if they are not set.+ */+ @Nullable+ public CustomExtension[] customExtensions() {+ return SemanticModelDefinition.copyOrNull(customExtensions);+ }++ /**+ * Compares this relationship with another object for value equality.+ *+ * @param other The object to compare with.+ * @return {@code true} if the objects are equal, otherwise {@code false}.+ */+ @Override+ public boolean equals(@Nullable Object other) {+ if (this == other) {+ return true;+ }+ if (!(other instanceof Relationship)) {+ return false;+ }+ Relationship that = (Relationship) other;+ return name.equals(that.name)+ && from.equals(that.from)+ && to.equals(that.to)+ && Arrays.equals(fromColumns, that.fromColumns)+ && Arrays.equals(toColumns, that.toColumns)+ && Objects.equals(aiContext, that.aiContext)+ && Arrays.equals(customExtensions, that.customExtensions);+ }++ /**+ * Returns the value-based hash code for this relationship.+ *+ * @return The hash code.+ */+ @Override+ public int hashCode() {+ return Objects.hash(+ name,+ from,+ to,+ Arrays.hashCode(fromColumns),+ Arrays.hashCode(toColumns),+ aiContext,+ Arrays.hashCode(customExtensions));+ }++ /**+ * Returns a string representation of this relationship.+ *+ * @return The string representation.+ */+ @Override+ public String toString() {+ return "Relationship{"+ + "name='"+ + name+ + '\''+ + ", from='"+ + from+ + '\''+ + ", to='"+ + to+ + '\''+ + ", fromColumns="+ + Arrays.toString(fromColumns)+ + ", toColumns="+ + Arrays.toString(toColumns)+ + ", aiContext="+ + aiContext+ + ", customExtensions="+ + Arrays.toString(customExtensions)+ + '}';+ }++ /** A builder for immutable {@link Relationship} values. */+ public static final class Builder {++ private String name;+ private String from;+ private String to;+ private String[] fromColumns;+ private String[] toColumns;++ @Nullable private AIContext aiContext;+ @Nullable private CustomExtension[] customExtensions;++ private Builder() {}++ /**+ * Sets the relationship name.+ *+ * @param name The non-empty relationship name.+ * @return This builder.+ */+ public Builder withName(String name) {+ this.name = name;+ return this;+ }++ /**+ * Sets the source dataset name.+ *+ * @param from The non-empty source dataset name.+ * @return This builder.+ */+ public Builder withFrom(String from) {+ this.from = from;+ return this;+ }++ /**+ * Sets the target dataset name.+ *+ * @param to The non-empty target dataset name.+ * @return This builder.+ */+ public Builder withTo(String to) {+ this.to = to;+ return this;+ }++ /**+ * Sets the source dataset columns.+ *+ * @param fromColumns The non-empty source column array.+ * @return This builder.+ */+ public Builder withFromColumns(String[] fromColumns) {+ this.fromColumns = fromColumns;+ return this;+ }++ /**+ * Sets the target dataset columns.+ *+ * @param toColumns The non-empty target column array.+ * @return This builder.+ */+ public Builder withToColumns(String[] toColumns) {+ this.toColumns = toColumns;+ return this;+ }++ /**+ * Sets the optional AI context.+ *+ * @param aiContext The AI context, or {@code null} to leave it unset.+ * @return This builder.+ */+ public Builder withAIContext(@Nullable AIContext aiContext) {+ this.aiContext = aiContext;+ return this;+ }++ /**+ * Sets the optional custom extensions.+ *+ * @param customExtensions The custom extensions, or {@code null} to leave them unset.+ * @return This builder.+ */+ public Builder withCustomExtensions(@Nullable CustomExtension[] customExtensions) {+ this.customExtensions = customExtensions;+ return this;+ }++ /**+ * Builds an immutable {@link Relationship}.+ *+ * @return The new relationship.+ * @throws IllegalArgumentException If a required name is null or empty, a required column array+ * is null or empty, a column name or custom extension is null, or the endpoint column+ * arrays have different lengths.+ */+ public Relationship build() {+ Preconditions.checkArgument(+ name != null && !name.isEmpty(), "name must not be null or empty");+ Preconditions.checkArgument(+ from != null && !from.isEmpty(), "from must not be null or empty");+ Preconditions.checkArgument(to != null && !to.isEmpty(), "to must not be null or empty");+ 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");+ SemanticModelDefinition.validateNonEmptyStringElements("fromColumns", fromColumns);+ SemanticModelDefinition.validateNonEmptyStringElements("toColumns", toColumns);+ Preconditions.checkArgument(+ fromColumns.length == toColumns.length,+ "fromColumns and toColumns must have the same length");+ SemanticModelDefinition.validateNoNullElements("customExtensions", customExtensions);+ return new Relationship(this);+ }+ }+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java b/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.javanew file mode 100644index 0000000000..f0650155be--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/SemanticModel.java@@ -0,0 +1,74 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import java.util.Collections;+import java.util.Map;+import javax.annotation.Nullable;+import org.apache.gravitino.Audit;+import org.apache.gravitino.Auditable;+import org.apache.gravitino.annotation.Evolving;++/**+ * A schema-scoped analytical Semantic Model managed by Gravitino. The entity composes its immutable+ * Ossie-compatible definition with Gravitino properties and audit information.+ */+@Evolving+public interface SemanticModel extends Auditable {++ /**+ * Returns the Semantic Model name.+ *+ * @return The Semantic Model name.+ */+ String name();++ /**+ * Returns the Semantic Model comment.+ *+ * @return The comment, or {@code null} if it is not set.+ */+ @Nullable+ String comment();++ /**+ * Returns the immutable Semantic Model definition.+ *+ * @return The Semantic Model definition.+ */+ SemanticModelDefinition definition();++ /**+ * Returns the Gravitino-specific properties of the Semantic Model. Implementations must return an+ * immutable map or a defensive copy.+ *+ * @return The Semantic Model properties, or an empty map if no properties are set.+ */+ default Map<String, String> properties() {+ return Collections.emptyMap();+ }++ /**+ * Returns the audit information for the Semantic Model.+ *+ * @return The audit information.+ */+ @Override+ Audit auditInfo();+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.java b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.javanew file mode 100644index 0000000000..eb1a7b19db--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelCatalog.java@@ -0,0 +1,112 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import java.util.Map;+import javax.annotation.Nullable;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.annotation.Evolving;+import org.apache.gravitino.exceptions.IllegalSemanticModelException;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.exceptions.NoSuchSemanticModelException;+import org.apache.gravitino.exceptions.SemanticModelAlreadyExistsException;++/** The public catalog API for managing Semantic Models in a schema. */+@Evolving+public interface SemanticModelCatalog {++ /**+ * Lists the Semantic Models in a schema namespace.+ *+ * @param namespace The schema namespace.+ * @return The identifiers of the Semantic Models in the namespace.+ * @throws NoSuchSchemaException If the schema does not exist.+ */+ NameIdentifier[] listSemanticModels(Namespace namespace) throws NoSuchSchemaException;++ /**+ * Loads a Semantic Model by identifier.+ *+ * @param ident The Semantic Model identifier.+ * @return The loaded Semantic Model.+ * @throws NoSuchSemanticModelException If the Semantic Model does not exist.+ */+ SemanticModel loadSemanticModel(NameIdentifier ident) throws NoSuchSemanticModelException;++ /**+ * Returns whether a Semantic Model exists.+ *+ * @param ident The Semantic Model identifier.+ * @return {@code true} if the Semantic Model exists, otherwise {@code false}.+ */+ default boolean semanticModelExists(NameIdentifier ident) {+ try {+ loadSemanticModel(ident);+ return true;+ } catch (NoSuchSemanticModelException e) {+ return false;+ }+ }++ /**+ * Creates a Semantic Model in a schema.+ *+ * @param ident The Semantic Model identifier.+ * @param comment The Semantic Model comment, or {@code null} if it has no comment.+ * @param definition The complete Semantic Model definition.+ * @param properties The Gravitino-specific Semantic Model properties.+ * @return The created Semantic Model.+ * @throws NoSuchSchemaException If the schema does not exist.+ * @throws SemanticModelAlreadyExistsException If the Semantic Model already exists.+ * @throws IllegalSemanticModelException If the Semantic Model definition is invalid.+ */+ SemanticModel createSemanticModel(+ NameIdentifier ident,+ @Nullable String comment,+ SemanticModelDefinition definition,+ Map<String, String> properties)+ throws NoSuchSchemaException, SemanticModelAlreadyExistsException,+ IllegalSemanticModelException;++ /**+ * Applies changes atomically to a Semantic Model.+ *+ * <p>If any change is rejected or the resulting Semantic Model is invalid, no change is applied.+ *+ * @param ident The Semantic Model identifier.+ * @param changes The changes to apply.+ * @return The altered Semantic Model.+ * @throws NoSuchSemanticModelException If the Semantic Model does not exist.+ * @throws SemanticModelAlreadyExistsException If a rename conflicts with an existing Semantic+ * Model.+ * @throws IllegalSemanticModelException If a change or the resulting Semantic Model is invalid.+ */+ SemanticModel alterSemanticModel(NameIdentifier ident, SemanticModelChange... changes)+ throws NoSuchSemanticModelException, SemanticModelAlreadyExistsException,+ IllegalSemanticModelException;++ /**+ * Drops a Semantic Model.+ *+ * @param ident The Semantic Model identifier.+ * @return {@code true} if the Semantic Model was dropped, or {@code false} if it did not exist.+ */+ boolean dropSemanticModel(NameIdentifier ident);+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/SemanticModelChange.java b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelChange.javanew file mode 100644index 0000000000..aa47d0ed69--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelChange.java@@ -0,0 +1,325 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import com.google.common.base.Preconditions;+import java.util.Objects;+import javax.annotation.Nullable;+import org.apache.commons.lang3.StringUtils;+import org.apache.gravitino.annotation.Evolving;++/**+ * A change that can be applied to a Semantic Model through {@link+ * SemanticModelCatalog#alterSemanticModel}.+ */+@Evolving+public interface SemanticModelChange {++ /**+ * Creates a change that renames a Semantic Model.+ *+ * @param newName The new Semantic Model name.+ * @return The rename change.+ */+ static SemanticModelChange rename(String newName) {+ return new RenameSemanticModel(newName);+ }++ /**+ * Creates a change that replaces a Semantic Model comment.+ *+ * @param newComment The new comment, or {@code null} to remove the current comment.+ * @return The comment change.+ */+ static SemanticModelChange updateComment(@Nullable String newComment) {+ return new UpdateComment(newComment);+ }++ /**+ * Creates a change that sets a Gravitino-specific Semantic Model property.+ *+ * <p>If the property already exists, its value is replaced.+ *+ * @param property The property name.+ * @param value The property value.+ * @return The property change.+ */+ static SemanticModelChange setProperty(String property, String value) {+ return new SetProperty(property, value);+ }++ /**+ * Creates a change that removes a Gravitino-specific Semantic Model property.+ *+ * <p>If the property does not exist, applying the change succeeds without modifying the model.+ *+ * @param property The property name.+ * @return The property removal change.+ */+ static SemanticModelChange removeProperty(String property) {+ return new RemoveProperty(property);+ }++ /**+ * Creates a change that atomically replaces the complete Semantic Model definition.+ *+ * <p>The Semantic Model name, comment, and Gravitino-specific properties are not affected.+ *+ * @param definition The replacement definition.+ * @return The definition replacement change.+ */+ static SemanticModelChange replaceDefinition(SemanticModelDefinition definition) {+ return new ReplaceDefinition(definition);+ }++ /** A change that renames a Semantic Model. */+ final class RenameSemanticModel implements SemanticModelChange {+ private final String newName;++ private RenameSemanticModel(String newName) {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(newName), "New name must not be null or blank");+ this.newName = newName;+ }++ /**+ * Returns the new Semantic Model name.+ *+ * @return The new name.+ */+ public String getNewName() {+ return newName;+ }++ /** {@inheritDoc} */+ @Override+ public boolean equals(Object obj) {+ if (this == obj) {+ return true;+ }+ if (!(obj instanceof RenameSemanticModel)) {+ return false;+ }+ RenameSemanticModel that = (RenameSemanticModel) obj;+ return newName.equals(that.newName);+ }++ /** {@inheritDoc} */+ @Override+ public int hashCode() {+ return Objects.hash(newName);+ }++ /** {@inheritDoc} */+ @Override+ public String toString() {+ return "RenameSemanticModel{newName='" + newName + "'}";+ }+ }++ /** A change that replaces a Semantic Model comment. */+ final class UpdateComment implements SemanticModelChange {+ @Nullable private final String newComment;++ private UpdateComment(@Nullable String newComment) {+ this.newComment = newComment;+ }++ /**+ * Returns the new Semantic Model comment.+ *+ * @return The new comment, or {@code null} if the current comment should be removed.+ */+ @Nullable+ public String getNewComment() {+ return newComment;+ }++ /** {@inheritDoc} */+ @Override+ public boolean equals(Object obj) {+ if (this == obj) {+ return true;+ }+ if (!(obj instanceof UpdateComment)) {+ return false;+ }+ UpdateComment that = (UpdateComment) obj;+ return Objects.equals(newComment, that.newComment);+ }++ /** {@inheritDoc} */+ @Override+ public int hashCode() {+ return Objects.hash(newComment);+ }++ /** {@inheritDoc} */+ @Override+ public String toString() {+ return "UpdateComment{newComment='" + newComment + "'}";+ }+ }++ /** A change that sets a Gravitino-specific Semantic Model property. */+ final class SetProperty implements SemanticModelChange {+ private final String property;+ private final String value;++ private SetProperty(String property, String value) {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(property), "Property name must not be null or blank");+ Preconditions.checkArgument(value != null, "Property value must not be null");+ this.property = property;+ this.value = value;+ }++ /**+ * Returns the property name.+ *+ * @return The property name.+ */+ public String getProperty() {+ return property;+ }++ /**+ * Returns the property value.+ *+ * @return The property value.+ */+ public String getValue() {+ return value;+ }++ /** {@inheritDoc} */+ @Override+ public boolean equals(Object obj) {+ if (this == obj) {+ return true;+ }+ if (!(obj instanceof SetProperty)) {+ return false;+ }+ SetProperty that = (SetProperty) obj;+ return property.equals(that.property) && value.equals(that.value);+ }++ /** {@inheritDoc} */+ @Override+ public int hashCode() {+ return Objects.hash(property, value);+ }++ /** {@inheritDoc} */+ @Override+ public String toString() {+ return "SetProperty{property='" + property + "', value='" + value + "'}";+ }+ }++ /** A change that removes a Gravitino-specific Semantic Model property. */+ final class RemoveProperty implements SemanticModelChange {+ private final String property;++ private RemoveProperty(String property) {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(property), "Property name must not be null or blank");+ this.property = property;+ }++ /**+ * Returns the property name.+ *+ * @return The property name.+ */+ public String getProperty() {+ return property;+ }++ /** {@inheritDoc} */+ @Override+ public boolean equals(Object obj) {+ if (this == obj) {+ return true;+ }+ if (!(obj instanceof RemoveProperty)) {+ return false;+ }+ RemoveProperty that = (RemoveProperty) obj;+ return property.equals(that.property);+ }++ /** {@inheritDoc} */+ @Override+ public int hashCode() {+ return Objects.hash(property);+ }++ /** {@inheritDoc} */+ @Override+ public String toString() {+ return "RemoveProperty{property='" + property + "'}";+ }+ }++ /** A change that atomically replaces the complete Semantic Model definition. */+ final class ReplaceDefinition implements SemanticModelChange {+ private final SemanticModelDefinition definition;++ private ReplaceDefinition(SemanticModelDefinition definition) {+ Preconditions.checkArgument(definition != null, "Definition must not be null");+ this.definition = definition;+ }++ /**+ * Returns the immutable replacement definition.+ *+ * @return The replacement definition.+ */+ public SemanticModelDefinition getDefinition() {+ return definition;+ }++ /** {@inheritDoc} */+ @Override+ public boolean equals(Object obj) {+ if (this == obj) {+ return true;+ }+ if (!(obj instanceof ReplaceDefinition)) {+ return false;+ }+ ReplaceDefinition that = (ReplaceDefinition) obj;+ return definition.equals(that.definition);+ }++ /** {@inheritDoc} */+ @Override+ public int hashCode() {+ return Objects.hash(definition);+ }++ /** {@inheritDoc} */+ @Override+ public String toString() {+ return "ReplaceDefinition{definition=" + definition + "}";+ }+ }+}diff --git a/api/src/main/java/org/apache/gravitino/semantic/SemanticModelDefinition.java b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelDefinition.javanew file mode 100644index 0000000000..2bf8bf2f0a--- /dev/null+++ b/api/src/main/java/org/apache/gravitino/semantic/SemanticModelDefinition.java@@ -0,0 +1,276 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import com.google.common.base.Preconditions;+import java.util.Arrays;+import java.util.Objects;+import javax.annotation.Nullable;+import org.apache.gravitino.annotation.Evolving;++/**+ * An immutable Semantic Model definition. This value groups the Ossie-compatible definition fields+ * used when creating or replacing a Semantic Model and has no name or independent lifecycle.+ */+@Evolving+public final class SemanticModelDefinition {++ private final Dataset[] datasets;++ @Nullable private final AIContext aiContext;+ @Nullable private final Relationship[] relationships;+ @Nullable private final Metric[] metrics;+ @Nullable private final CustomExtension[] customExtensions;++ private SemanticModelDefinition(Builder builder) {+ this.aiContext = builder.aiContext;+ this.datasets = Arrays.copyOf(builder.datasets, builder.datasets.length);+ this.relationships = copyOrNull(builder.relationships);+ this.metrics = copyOrNull(builder.metrics);+ this.customExtensions = copyOrNull(builder.customExtensions);+ }++ /**+ * Creates a builder for an immutable {@link SemanticModelDefinition}.+ *+ * @return A new builder.+ */+ public static Builder builder() {+ return new Builder();+ }++ /**+ * Returns the AI context associated with the Semantic Model definition.+ *+ * @return The AI context, or {@code null} if it is not set.+ */+ @Nullable+ public AIContext aiContext() {+ return aiContext;+ }++ /**+ * Returns a copy of the datasets in the Semantic Model definition.+ *+ * @return The non-empty dataset array.+ */+ public Dataset[] datasets() {+ return Arrays.copyOf(datasets, datasets.length);+ }++ /**+ * Returns a copy of the relationships in the Semantic Model definition.+ *+ * @return The relationships, or {@code null} if they are not set.+ */+ @Nullable+ public Relationship[] relationships() {+ return copyOrNull(relationships);+ }++ /**+ * Returns a copy of the metrics in the Semantic Model definition.+ *+ * @return The metrics, or {@code null} if they are not set.+ */+ @Nullable+ public Metric[] metrics() {+ return copyOrNull(metrics);+ }++ /**+ * Returns a copy of the custom extensions in the Semantic Model definition.+ *+ * @return The custom extensions, or {@code null} if they are not set.+ */+ @Nullable+ public CustomExtension[] customExtensions() {+ return copyOrNull(customExtensions);+ }++ /**+ * Compares this definition with another object for value equality.+ *+ * @param other The object to compare with.+ * @return {@code true} if the objects are equal, otherwise {@code false}.+ */+ @Override+ public boolean equals(@Nullable Object other) {+ if (this == other) {+ return true;+ }+ if (!(other instanceof SemanticModelDefinition)) {+ return false;+ }+ SemanticModelDefinition that = (SemanticModelDefinition) other;+ return Objects.equals(aiContext, that.aiContext)+ && Arrays.equals(datasets, that.datasets)+ && Arrays.equals(relationships, that.relationships)+ && Arrays.equals(metrics, that.metrics)+ && Arrays.equals(customExtensions, that.customExtensions);+ }++ /**+ * Returns the value-based hash code for this definition.+ *+ * @return The hash code.+ */+ @Override+ public int hashCode() {+ return Objects.hash(+ aiContext,+ Arrays.hashCode(datasets),+ Arrays.hashCode(relationships),+ Arrays.hashCode(metrics),+ Arrays.hashCode(customExtensions));+ }++ /**+ * Returns a string representation of this definition.+ *+ * @return The string representation.+ */+ @Override+ public String toString() {+ return "SemanticModelDefinition{"+ + "aiContext="+ + aiContext+ + ", datasets="+ + Arrays.toString(datasets)+ + ", relationships="+ + Arrays.toString(relationships)+ + ", metrics="+ + Arrays.toString(metrics)+ + ", customExtensions="+ + Arrays.toString(customExtensions)+ + '}';+ }++ @Nullable+ static <T> T[] copyOrNull(@Nullable T[] values) {+ return values == null ? null : Arrays.copyOf(values, values.length);+ }++ 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);+ }+ }++ 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);+ }+ }++ /** A builder for immutable {@link SemanticModelDefinition} values. */+ public static final class Builder {++ private Dataset[] datasets;++ @Nullable private AIContext aiContext;+ @Nullable private Relationship[] relationships;+ @Nullable private Metric[] metrics;+ @Nullable private CustomExtension[] customExtensions;++ private Builder() {}++ /**+ * Sets the optional AI context.+ *+ * @param aiContext The AI context, or {@code null} to leave it unset.+ * @return This builder.+ */+ public Builder withAIContext(@Nullable AIContext aiContext) {+ this.aiContext = aiContext;+ return this;+ }++ /**+ * Sets the datasets in the Semantic Model definition.+ *+ * @param datasets The non-empty dataset array.+ * @return This builder.+ */+ public Builder withDatasets(Dataset[] datasets) {+ this.datasets = datasets;+ return this;+ }++ /**+ * Sets the optional relationships.+ *+ * @param relationships The relationships, or {@code null} to leave them unset.+ * @return This builder.+ */+ public Builder withRelationships(@Nullable Relationship[] relationships) {+ this.relationships = relationships;+ return this;+ }++ /**+ * Sets the optional metrics.+ *+ * @param metrics The metrics, or {@code null} to leave them unset.+ * @return This builder.+ */+ public Builder withMetrics(@Nullable Metric[] metrics) {+ this.metrics = metrics;+ return this;+ }++ /**+ * Sets the optional custom extensions.+ *+ * @param customExtensions The custom extensions, or {@code null} to leave them unset.+ * @return This builder.+ */+ public Builder withCustomExtensions(@Nullable CustomExtension[] customExtensions) {+ this.customExtensions = customExtensions;+ return this;+ }++ /**+ * Builds an immutable {@link SemanticModelDefinition}.+ *+ * @return The new definition.+ * @throws IllegalArgumentException If the dataset array is null or empty, or any definition+ * array contains null.+ */+ public SemanticModelDefinition build() {+ 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);+ return new SemanticModelDefinition(this);+ }+ }+}diff --git a/api/src/test/java/org/apache/gravitino/TestMetadataObjects.java b/api/src/test/java/org/apache/gravitino/TestMetadataObjects.javaindex bb01469dbe..95861fd7c6 100644--- a/api/src/test/java/org/apache/gravitino/TestMetadataObjects.java+++ b/api/src/test/java/org/apache/gravitino/TestMetadataObjects.java@@ -222,4 +222,26 @@ public class TestMetadataObjects {IllegalArgumentException.class,() -> MetadataObjects.parse("catalog.schema", MetadataObject.Type.FUNCTION));}++ @Test+ public void testSemanticModelObject() {+ MetadataObject semanticModel =+ MetadataObjects.of("catalog.schema", "sales_model", MetadataObject.Type.SEMANTIC_MODEL);+ Assertions.assertEquals("catalog.schema", semanticModel.parent());+ Assertions.assertEquals("sales_model", semanticModel.name());+ Assertions.assertEquals(MetadataObject.Type.SEMANTIC_MODEL, semanticModel.type());+ Assertions.assertEquals("catalog.schema.sales_model", semanticModel.fullName());++ MetadataObject parsed =+ MetadataObjects.parse("catalog.schema.sales_model", MetadataObject.Type.SEMANTIC_MODEL);+ Assertions.assertEquals(semanticModel, parsed);++ MetadataObject parent = MetadataObjects.parent(semanticModel);+ Assertions.assertEquals("catalog.schema", parent.fullName());+ Assertions.assertEquals(MetadataObject.Type.SCHEMA, parent.type());++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> MetadataObjects.parse("schema.sales_model", MetadataObject.Type.SEMANTIC_MODEL));+ }}diff --git a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelCatalog.java b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelCatalog.javanew file mode 100644index 0000000000..5939490a50--- /dev/null+++ b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelCatalog.java@@ -0,0 +1,75 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.util.Map;+import javax.annotation.Nullable;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.exceptions.NoSuchSemanticModelException;+import org.junit.jupiter.api.Test;++public class TestSemanticModelCatalog {++ @Test+ public void testSemanticModelExists() {+ SemanticModelCatalog catalog = new ExistsOnlySemanticModelCatalog();++ assertTrue(catalog.semanticModelExists(NameIdentifier.of("schema", "existing")));+ assertFalse(catalog.semanticModelExists(NameIdentifier.of("schema", "missing")));+ }++ private static class ExistsOnlySemanticModelCatalog implements SemanticModelCatalog {++ @Override+ public NameIdentifier[] listSemanticModels(Namespace namespace) {+ throw new UnsupportedOperationException();+ }++ @Override+ public SemanticModel loadSemanticModel(NameIdentifier ident) {+ if ("missing".equals(ident.name())) {+ throw new NoSuchSemanticModelException("Semantic Model does not exist: %s", ident);+ }+ return null;+ }++ @Override+ public SemanticModel createSemanticModel(+ NameIdentifier ident,+ @Nullable String comment,+ SemanticModelDefinition definition,+ Map<String, String> properties) {+ throw new UnsupportedOperationException();+ }++ @Override+ public SemanticModel alterSemanticModel(NameIdentifier ident, SemanticModelChange... changes) {+ throw new UnsupportedOperationException();+ }++ @Override+ public boolean dropSemanticModel(NameIdentifier ident) {+ throw new UnsupportedOperationException();+ }+ }+}diff --git a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelChange.java b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelChange.javanew file mode 100644index 0000000000..04fb92e8f2--- /dev/null+++ b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelChange.java@@ -0,0 +1,90 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;++import org.apache.gravitino.NameIdentifier;+import org.junit.jupiter.api.Test;++public class TestSemanticModelChange {++ @Test+ public void testCreateChanges() {+ SemanticModelDefinition definition = definition("orders");++ SemanticModelChange.RenameSemanticModel rename =+ (SemanticModelChange.RenameSemanticModel) SemanticModelChange.rename("new_name");+ SemanticModelChange.UpdateComment updateComment =+ (SemanticModelChange.UpdateComment) SemanticModelChange.updateComment(null);+ SemanticModelChange.SetProperty setProperty =+ (SemanticModelChange.SetProperty) SemanticModelChange.setProperty("owner", "analytics");+ SemanticModelChange.RemoveProperty removeProperty =+ (SemanticModelChange.RemoveProperty) SemanticModelChange.removeProperty("owner");+ SemanticModelChange.ReplaceDefinition replaceDefinition =+ (SemanticModelChange.ReplaceDefinition) SemanticModelChange.replaceDefinition(definition);++ assertEquals("new_name", rename.getNewName());+ assertNull(updateComment.getNewComment());+ assertEquals("owner", setProperty.getProperty());+ assertEquals("analytics", setProperty.getValue());+ assertEquals("owner", removeProperty.getProperty());+ assertEquals(definition, replaceDefinition.getDefinition());+ }++ @Test+ public void testChangesUseValueSemantics() {+ assertEquals(SemanticModelChange.rename("new_name"), SemanticModelChange.rename("new_name"));+ assertEquals(+ SemanticModelChange.updateComment("comment"), SemanticModelChange.updateComment("comment"));+ assertEquals(+ SemanticModelChange.setProperty("key", "value"),+ SemanticModelChange.setProperty("key", "value"));+ assertEquals(+ SemanticModelChange.removeProperty("key"), SemanticModelChange.removeProperty("key"));+ assertEquals(+ SemanticModelChange.replaceDefinition(definition("orders")),+ SemanticModelChange.replaceDefinition(definition("orders")));+ }++ @Test+ public void testRejectInvalidChanges() {+ assertThrows(IllegalArgumentException.class, () -> SemanticModelChange.rename(""));+ assertThrows(+ IllegalArgumentException.class, () -> SemanticModelChange.setProperty("", "value"));+ assertThrows(+ IllegalArgumentException.class, () -> SemanticModelChange.setProperty("key", null));+ assertThrows(IllegalArgumentException.class, () -> SemanticModelChange.removeProperty(""));+ assertThrows(IllegalArgumentException.class, () -> SemanticModelChange.replaceDefinition(null));+ }++ private static SemanticModelDefinition definition(String datasetName) {+ return SemanticModelDefinition.builder()+ .withDatasets(+ new Dataset[] {+ Dataset.builder()+ .withName(datasetName)+ .withSource(NameIdentifier.of("sales", "mart", datasetName))+ .build()+ })+ .build();+ }+}diff --git a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelDefinition.java b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelDefinition.javanew file mode 100644index 0000000000..a3a85d8e11--- /dev/null+++ b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelDefinition.java@@ -0,0 +1,178 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertNotSame;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;++import java.util.Collections;+import org.apache.gravitino.Audit;+import org.apache.gravitino.NameIdentifier;+import org.junit.jupiter.api.Test;++public class TestSemanticModelDefinition {++ @Test+ public void testBuildDefinitionAndDefensivelyCopyCollections() {+ Dataset dataset = dataset("orders");+ Relationship relationship =+ Relationship.builder()+ .withName("orders_to_customers")+ .withFrom("orders")+ .withTo("customers")+ .withFromColumns(new String[] {"customer_id"})+ .withToColumns(new String[] {"id"})+ .build();+ Metric metric =+ Metric.builder().withName("count").withExpression(expression("COUNT(*)")).build();+ CustomExtension extension =+ CustomExtension.builder().withVendorName("example").withData("{}").build();+ Dataset[] datasets = {dataset};+ Relationship[] relationships = {relationship};+ Metric[] metrics = {metric};+ CustomExtension[] extensions = {extension};++ SemanticModelDefinition definition =+ SemanticModelDefinition.builder()+ .withAIContext(AIContext.of("Certified"))+ .withDatasets(datasets)+ .withRelationships(relationships)+ .withMetrics(metrics)+ .withCustomExtensions(extensions)+ .build();++ datasets[0] = dataset("changed");+ relationships[0] = relationship;+ metrics[0] = metric;+ extensions[0] = extension;++ assertEquals("Certified", definition.aiContext().text());+ assertEquals("orders", definition.datasets()[0].name());+ assertArrayEquals(new Relationship[] {relationship}, definition.relationships());+ assertArrayEquals(new Metric[] {metric}, definition.metrics());+ assertArrayEquals(new CustomExtension[] {extension}, definition.customExtensions());+ assertNotSame(definition.datasets(), definition.datasets());+ }++ @Test+ public void testOptionalCollectionsPreserveNullAndEmpty() {+ Dataset dataset = dataset("orders");+ SemanticModelDefinition unset =+ SemanticModelDefinition.builder().withDatasets(new Dataset[] {dataset}).build();+ SemanticModelDefinition empty =+ SemanticModelDefinition.builder()+ .withDatasets(new Dataset[] {dataset})+ .withRelationships(new Relationship[0])+ .withMetrics(new Metric[0])+ .withCustomExtensions(new CustomExtension[0])+ .build();+ SemanticModel semanticModel = semanticModel(unset);++ assertNull(unset.relationships());+ assertNull(unset.metrics());+ assertNull(unset.customExtensions());+ assertArrayEquals(new Relationship[0], empty.relationships());+ assertArrayEquals(new Metric[0], empty.metrics());+ assertArrayEquals(new CustomExtension[0], empty.customExtensions());+ assertNotEquals(unset, empty);+ assertEquals(unset, semanticModel.definition());+ assertEquals(Collections.emptyMap(), semanticModel.properties());+ }++ @Test+ public void testDefinitionRequiresDatasets() {+ assertThrows(IllegalArgumentException.class, () -> SemanticModelDefinition.builder().build());+ assertThrows(+ IllegalArgumentException.class,+ () -> SemanticModelDefinition.builder().withDatasets(new Dataset[0]).build());+ assertThrows(+ IllegalArgumentException.class,+ () -> SemanticModelDefinition.builder().withDatasets(new Dataset[] {null}).build());++ Dataset dataset = dataset("orders");+ assertThrows(+ IllegalArgumentException.class,+ () ->+ SemanticModelDefinition.builder()+ .withDatasets(new Dataset[] {dataset})+ .withRelationships(new Relationship[] {null})+ .build());+ assertThrows(+ IllegalArgumentException.class,+ () ->+ SemanticModelDefinition.builder()+ .withDatasets(new Dataset[] {dataset})+ .withMetrics(new Metric[] {null})+ .build());+ assertThrows(+ IllegalArgumentException.class,+ () ->+ SemanticModelDefinition.builder()+ .withDatasets(new Dataset[] {dataset})+ .withCustomExtensions(new CustomExtension[] {null})+ .build());+ }++ private static Dataset dataset(String name) {+ return Dataset.builder()+ .withName(name)+ .withSource(NameIdentifier.of("sales", "mart", name))+ .build();+ }++ private static Expression expression(String value) {+ return Expression.builder()+ .withDialects(+ new DialectExpression[] {+ DialectExpression.builder()+ .withDialect(Dialects.ANSI_SQL)+ .withExpression(value)+ .build()+ })+ .build();+ }++ private static SemanticModel semanticModel(SemanticModelDefinition definition) {+ return new SemanticModel() {+ @Override+ public String name() {+ return "sales";+ }++ @Override+ public String comment() {+ return null;+ }++ @Override+ public SemanticModelDefinition definition() {+ return definition;+ }++ @Override+ public Audit auditInfo() {+ return null;+ }+ };+ }+}diff --git a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelMembers.java b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelMembers.javanew file mode 100644index 0000000000..984834f832--- /dev/null+++ b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelMembers.java@@ -0,0 +1,270 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertNotSame;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;++import org.apache.gravitino.NameIdentifier;+import org.junit.jupiter.api.Test;++public class TestSemanticModelMembers {++ @Test+ public void testBuildMembers() {+ Expression expression = expression("order_amount");+ AIContext aiContext = AIContext.of("Use certified fields");+ CustomExtension extension =+ CustomExtension.builder().withVendorName("example").withData("{\"key\":\"value\"}").build();+ Field field =+ Field.builder()+ .withName("order_amount")+ .withExpression(expression)+ .withDimension(Dimension.builder().withIsTime(false).build())+ .withLabel("Order amount")+ .withDescription("Gross order amount")+ .withDatatype(DataType.DECIMAL)+ .withAIContext(aiContext)+ .withCustomExtensions(new CustomExtension[] {extension})+ .build();+ Dataset dataset =+ Dataset.builder()+ .withName("orders")+ .withSource(NameIdentifier.of("sales", "mart", "orders"))+ .withPrimaryKey(new String[] {"order_id"})+ .withUniqueKeys(new String[][] {{"order_id"}})+ .withDescription("Orders")+ .withAIContext(aiContext)+ .withFields(new Field[] {field})+ .withCustomExtensions(new CustomExtension[] {extension})+ .build();+ Relationship relationship =+ Relationship.builder()+ .withName("orders_to_customers")+ .withFrom("orders")+ .withTo("customers")+ .withFromColumns(new String[] {"customer_id"})+ .withToColumns(new String[] {"id"})+ .withAIContext(aiContext)+ .build();+ Metric metric =+ Metric.builder()+ .withName("total_revenue")+ .withExpression(expression)+ .withDescription("Total revenue")+ .withDatatype(DataType.DECIMAL)+ .withAIContext(aiContext)+ .build();++ assertEquals("orders", dataset.name());+ assertEquals(NameIdentifier.of("sales", "mart", "orders"), dataset.source());+ assertEquals("order_amount", dataset.fields()[0].name());+ assertEquals("orders", relationship.from());+ assertEquals("customers", relationship.to());+ assertEquals(DataType.DECIMAL, metric.datatype());+ }++ @Test+ public void testCollectionsAreDefensivelyCopied() {+ Expression expression = expression("order_id");+ String[] primaryKey = {"order_id"};+ String[][] uniqueKeys = {{"order_id"}};+ Field[] fields = {Field.builder().withName("order_id").withExpression(expression).build()};+ Dataset dataset =+ Dataset.builder()+ .withName("orders")+ .withSource(NameIdentifier.of("sales", "mart", "orders"))+ .withPrimaryKey(primaryKey)+ .withUniqueKeys(uniqueKeys)+ .withFields(fields)+ .build();+ String[] fromColumns = {"customer_id"};+ String[] toColumns = {"id"};+ Relationship relationship =+ Relationship.builder()+ .withName("orders_to_customers")+ .withFrom("orders")+ .withTo("customers")+ .withFromColumns(fromColumns)+ .withToColumns(toColumns)+ .build();++ primaryKey[0] = "changed";+ uniqueKeys[0][0] = "changed";+ fields[0] = Field.builder().withName("changed").withExpression(expression).build();+ fromColumns[0] = "changed";+ toColumns[0] = "changed";++ assertArrayEquals(new String[] {"order_id"}, dataset.primaryKey());+ assertArrayEquals(new String[] {"order_id"}, dataset.uniqueKeys()[0]);+ assertEquals("order_id", dataset.fields()[0].name());+ assertArrayEquals(new String[] {"customer_id"}, relationship.fromColumns());+ assertArrayEquals(new String[] {"id"}, relationship.toColumns());+ assertNotSame(dataset.uniqueKeys(), dataset.uniqueKeys());+ assertNotSame(dataset.uniqueKeys()[0], dataset.uniqueKeys()[0]);+ }++ @Test+ public void testOptionalCollectionsPreserveNullAndEmpty() {+ Expression expression = expression("id");+ Field unsetField = Field.builder().withName("id").withExpression(expression).build();+ Field emptyField =+ Field.builder()+ .withName("id")+ .withExpression(expression)+ .withCustomExtensions(new CustomExtension[0])+ .build();+ Dataset unsetDataset = datasetBuilder().build();+ Dataset emptyDataset =+ datasetBuilder()+ .withPrimaryKey(new String[0])+ .withUniqueKeys(new String[0][])+ .withFields(new Field[0])+ .withCustomExtensions(new CustomExtension[0])+ .build();+ Relationship unsetRelationship = relationshipBuilder().build();+ Relationship emptyRelationship =+ relationshipBuilder().withCustomExtensions(new CustomExtension[0]).build();+ Metric unsetMetric = Metric.builder().withName("count").withExpression(expression).build();+ Metric emptyMetric =+ Metric.builder()+ .withName("count")+ .withExpression(expression)+ .withCustomExtensions(new CustomExtension[0])+ .build();++ assertNull(unsetDataset.primaryKey());+ assertNull(unsetDataset.uniqueKeys());+ assertNull(unsetDataset.fields());+ assertNull(unsetDataset.customExtensions());+ assertNull(unsetField.customExtensions());+ assertNull(unsetRelationship.customExtensions());+ assertNull(unsetMetric.customExtensions());++ assertArrayEquals(new String[0], emptyDataset.primaryKey());+ assertEquals(0, emptyDataset.uniqueKeys().length);+ assertArrayEquals(new Field[0], emptyDataset.fields());+ assertArrayEquals(new CustomExtension[0], emptyDataset.customExtensions());+ assertArrayEquals(new CustomExtension[0], emptyField.customExtensions());+ assertArrayEquals(new CustomExtension[0], emptyRelationship.customExtensions());+ assertArrayEquals(new CustomExtension[0], emptyMetric.customExtensions());++ assertNotEquals(unsetDataset, emptyDataset);+ assertNotEquals(unsetField, emptyField);+ assertNotEquals(unsetRelationship, emptyRelationship);+ assertNotEquals(unsetMetric, emptyMetric);+ }++ @Test+ public void testRequiredBuilderFields() {+ assertThrows(IllegalArgumentException.class, () -> Field.builder().build());+ assertThrows(IllegalArgumentException.class, () -> Dataset.builder().build());+ assertThrows(IllegalArgumentException.class, () -> Relationship.builder().build());+ assertThrows(IllegalArgumentException.class, () -> Metric.builder().build());+ }++ @Test+ public void testArrayElementValidation() {+ Expression expression = expression("id");++ assertThrows(+ IllegalArgumentException.class,+ () -> datasetBuilder().withPrimaryKey(new String[] {null}).build());+ assertThrows(+ IllegalArgumentException.class,+ () -> datasetBuilder().withPrimaryKey(new String[] {""}).build());+ assertThrows(+ IllegalArgumentException.class,+ () -> datasetBuilder().withUniqueKeys(new String[][] {null}).build());+ assertThrows(+ IllegalArgumentException.class,+ () -> datasetBuilder().withUniqueKeys(new String[][] {new String[0]}).build());+ assertThrows(+ IllegalArgumentException.class,+ () -> datasetBuilder().withUniqueKeys(new String[][] {{null}}).build());+ assertThrows(+ IllegalArgumentException.class,+ () -> datasetBuilder().withFields(new Field[] {null}).build());+ assertThrows(+ IllegalArgumentException.class,+ () -> datasetBuilder().withCustomExtensions(new CustomExtension[] {null}).build());+ assertThrows(+ IllegalArgumentException.class,+ () ->+ Field.builder()+ .withName("id")+ .withExpression(expression)+ .withCustomExtensions(new CustomExtension[] {null})+ .build());+ assertThrows(+ IllegalArgumentException.class,+ () ->+ Metric.builder()+ .withName("count")+ .withExpression(expression)+ .withCustomExtensions(new CustomExtension[] {null})+ .build());+ assertThrows(+ IllegalArgumentException.class,+ () -> relationshipBuilder().withFromColumns(new String[] {null}).build());+ assertThrows(+ IllegalArgumentException.class,+ () -> relationshipBuilder().withToColumns(new String[] {""}).build());+ assertThrows(+ IllegalArgumentException.class,+ () ->+ relationshipBuilder()+ .withFromColumns(new String[] {"tenant_id", "customer_id"})+ .build());+ assertThrows(+ IllegalArgumentException.class,+ () -> relationshipBuilder().withCustomExtensions(new CustomExtension[] {null}).build());+ }++ private static Dataset.Builder datasetBuilder() {+ return Dataset.builder()+ .withName("orders")+ .withSource(NameIdentifier.of("sales", "mart", "orders"));+ }++ private static Relationship.Builder relationshipBuilder() {+ return Relationship.builder()+ .withName("orders_to_customers")+ .withFrom("orders")+ .withTo("customers")+ .withFromColumns(new String[] {"customer_id"})+ .withToColumns(new String[] {"id"});+ }++ private static Expression expression(String value) {+ return Expression.builder()+ .withDialects(+ new DialectExpression[] {+ DialectExpression.builder()+ .withDialect(Dialects.ANSI_SQL)+ .withExpression(value)+ .build()+ })+ .build();+ }+}diff --git a/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelSupportingTypes.java b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelSupportingTypes.javanew file mode 100644index 0000000000..5389f214e7--- /dev/null+++ b/api/src/test/java/org/apache/gravitino/semantic/TestSemanticModelSupportingTypes.java@@ -0,0 +1,260 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.semantic;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertNotSame;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.math.BigDecimal;+import java.math.BigInteger;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.atomic.AtomicInteger;+import org.junit.jupiter.api.Test;++public class TestSemanticModelSupportingTypes {++ @Test+ public void testBuildSupportingTypes() {+ DialectExpression dialectExpression =+ DialectExpression.builder()+ .withDialect(Dialects.ANSI_SQL)+ .withExpression("order_amount")+ .build();+ Expression expression =+ Expression.builder().withDialects(new DialectExpression[] {dialectExpression}).build();+ Dimension dimension = Dimension.builder().withIsTime(false).build();+ AIContextObject contextObject =+ AIContextObject.builder()+ .withInstructions("Use certified fields")+ .withSynonyms(new String[] {"amount"})+ .withExamples(new String[] {"Revenue by month"})+ .withAdditionalProperties(Map.of("priority", 1))+ .build();+ CustomExtension extension =+ CustomExtension.builder().withVendorName("example").withData("{\"key\":\"value\"}").build();++ assertArrayEquals(new DialectExpression[] {dialectExpression}, expression.dialects());+ assertEquals(Boolean.FALSE, dimension.isTime());+ assertEquals("Use certified fields", contextObject.instructions());+ assertArrayEquals(new String[] {"amount"}, contextObject.synonyms());+ assertArrayEquals(new String[] {"Revenue by month"}, contextObject.examples());+ assertEquals(BigInteger.ONE, contextObject.additionalProperties().get("priority"));+ assertEquals("example", extension.vendorName());+ assertEquals("{\"key\":\"value\"}", extension.data());+ }++ @Test+ public void testExpressionDefensivelyCopiesDialects() {+ DialectExpression ansi =+ DialectExpression.builder().withDialect(Dialects.ANSI_SQL).withExpression("id").build();+ DialectExpression[] dialects = {ansi};+ Expression expression = Expression.builder().withDialects(dialects).build();++ dialects[0] =+ DialectExpression.builder()+ .withDialect(Dialects.BIGQUERY)+ .withExpression("changed")+ .build();++ assertEquals(Dialects.ANSI_SQL, expression.dialects()[0].dialect());+ assertNotSame(expression.dialects(), expression.dialects());+ }++ @Test+ @SuppressWarnings("unchecked")+ public void testAIContextVariantsAndAdditionalPropertiesAreImmutable() {+ List<Object> nestedValues = new ArrayList<>();+ nestedValues.add("first");+ Map<String, Object> nested = new LinkedHashMap<>();+ nested.put("values", nestedValues);+ Map<String, Object> additionalProperties = new LinkedHashMap<>();+ additionalProperties.put("nested", nested);++ AIContextObject contextObject =+ AIContextObject.builder().withAdditionalProperties(additionalProperties).build();+ AIContext objectContext = AIContext.of(contextObject);+ AIContext textContext = AIContext.of("Use certified metrics");++ nestedValues.add("changed");+ nested.put("extra", true);+ additionalProperties.put("new", "value");++ assertTrue(textContext.isText());+ assertEquals("Use certified metrics", textContext.text());+ assertNull(textContext.object());+ assertFalse(objectContext.isText());+ assertNull(objectContext.text());+ assertEquals(contextObject, objectContext.object());++ Map<String, Object> storedNested =+ (Map<String, Object>) contextObject.additionalProperties().get("nested");+ assertEquals(List.of("first"), storedNested.get("values"));+ assertThrows(+ UnsupportedOperationException.class,+ () -> contextObject.additionalProperties().put("another", "value"));+ assertThrows(+ UnsupportedOperationException.class,+ () -> ((List<Object>) storedNested.get("values")).add("value"));+ }++ @Test+ public void testOptionalAIContextCollectionsPreserveNullAndEmpty() {+ AIContextObject unset = AIContextObject.builder().build();+ AIContextObject empty =+ AIContextObject.builder().withSynonyms(new String[0]).withExamples(new String[0]).build();++ assertNull(unset.synonyms());+ assertNull(unset.examples());+ assertArrayEquals(new String[0], empty.synonyms());+ assertArrayEquals(new String[0], empty.examples());+ assertNotEquals(unset, empty);+ }++ @Test+ @SuppressWarnings("unchecked")+ public void testAIContextNumbersAreCanonicalized() {+ Map<String, Object> nested = new LinkedHashMap<>();+ nested.put("short", (short) 2);+ nested.put("float", 0.25F);++ Map<String, Object> additionalProperties = new LinkedHashMap<>();+ additionalProperties.put("byte", (byte) 1);+ additionalProperties.put("integer", 2);+ additionalProperties.put("long", 3L);+ additionalProperties.put("bigInteger", new BigInteger("123456789012345678901234567890"));+ additionalProperties.put("double", 0.125D);+ additionalProperties.put("bigDecimal", new BigDecimal("0.123456789012345678901234567890"));+ additionalProperties.put("nested", nested);+ additionalProperties.put("array", new Number[] {4, 5L, 0.5F});++ AIContextObject contextObject =+ AIContextObject.builder().withAdditionalProperties(additionalProperties).build();+ Map<String, Object> values = contextObject.additionalProperties();++ assertEquals(BigInteger.ONE, values.get("byte"));+ assertEquals(BigInteger.valueOf(2), values.get("integer"));+ assertEquals(BigInteger.valueOf(3), values.get("long"));+ assertEquals(new BigInteger("123456789012345678901234567890"), values.get("bigInteger"));+ assertEquals(new BigDecimal("0.125"), values.get("double"));+ assertEquals(new BigDecimal("0.123456789012345678901234567890"), values.get("bigDecimal"));+ assertEquals(BigInteger.valueOf(2), ((Map<String, Object>) values.get("nested")).get("short"));+ assertEquals(new BigDecimal("0.25"), ((Map<String, Object>) values.get("nested")).get("float"));+ assertEquals(+ List.of(BigInteger.valueOf(4), BigInteger.valueOf(5), new BigDecimal("0.5")),+ values.get("array"));++ AIContextObject equivalentContext =+ AIContextObject.builder()+ .withAdditionalProperties(Map.of("number", Integer.valueOf(1)))+ .build();+ AIContextObject equivalentLongContext =+ AIContextObject.builder()+ .withAdditionalProperties(Map.of("number", Long.valueOf(1)))+ .build();+ assertEquals(equivalentContext, equivalentLongContext);+ assertEquals(equivalentContext.hashCode(), equivalentLongContext.hashCode());+ }++ @Test+ public void testAIContextAdditionalPropertyBounds() {+ Object maximumDepthValue = "value";+ for (int depth = 0; depth < AIContextObject.MAX_ADDITIONAL_PROPERTY_NESTING_DEPTH; depth++) {+ maximumDepthValue = Map.of("nested", maximumDepthValue);+ }+ AIContextObject.builder()+ .withAdditionalProperties(Map.of("maximumDepth", maximumDepthValue))+ .build();++ Object excessiveDepthValue = Map.of("nested", maximumDepthValue);+ assertThrows(+ IllegalArgumentException.class,+ () ->+ AIContextObject.builder()+ .withAdditionalProperties(Map.of("excessiveDepth", excessiveDepthValue))+ .build());+ assertThrows(+ IllegalArgumentException.class,+ () ->+ AIContextObject.builder()+ .withAdditionalProperties(Map.of("unsupportedNumber", new AtomicInteger(1)))+ .build());+ }++ @Test+ public void testSupportingTypeValidation() {+ assertThrows(IllegalArgumentException.class, () -> DialectExpression.builder().build());+ assertThrows(IllegalArgumentException.class, () -> Expression.builder().build());+ assertEquals("", AIContext.of("").text());++ DialectExpression ansi =+ DialectExpression.builder().withDialect(Dialects.ANSI_SQL).withExpression("id").build();+ DialectExpression custom =+ DialectExpression.builder().withDialect("TRINO").withExpression("id").build();+ assertEquals("TRINO", custom.dialect());+ assertEquals("ANSI_SQL", Dialects.ANSI_SQL);+ assertThrows(+ IllegalArgumentException.class,+ () -> DialectExpression.builder().withDialect("").withExpression("id").build());+ assertThrows(+ IllegalArgumentException.class,+ () -> Expression.builder().withDialects(new DialectExpression[] {ansi, ansi}).build());+ assertThrows(+ IllegalArgumentException.class,+ () -> Expression.builder().withDialects(new DialectExpression[] {ansi, null}).build());+ assertThrows(+ IllegalArgumentException.class,+ () -> AIContextObject.builder().withSynonyms(new String[] {null}).build());+ assertThrows(+ IllegalArgumentException.class,+ () -> AIContextObject.builder().withExamples(new String[] {null}).build());+ assertThrows(+ IllegalArgumentException.class,+ () ->+ AIContextObject.builder()+ .withAdditionalProperties(Map.of("instructions", "duplicate"))+ .build());+ assertThrows(+ IllegalArgumentException.class,+ () ->+ AIContextObject.builder()+ .withAdditionalProperties(Map.of("unsupported", new Object()))+ .build());+ assertThrows(+ IllegalArgumentException.class,+ () ->+ AIContextObject.builder()+ .withAdditionalProperties(Map.of("not_finite", Double.NaN))+ .build());++ Map<String, Object> cyclic = new LinkedHashMap<>();+ cyclic.put("self", cyclic);+ assertThrows(+ IllegalArgumentException.class,+ () -> AIContextObject.builder().withAdditionalProperties(cyclic).build());+ }+}diff --git a/design-docs/gravitino-semantic-model-design.md b/design-docs/gravitino-semantic-model-design.mdindex 3bd96e8d39..a65069ef21 100644--- a/design-docs/gravitino-semantic-model-design.md+++ b/design-docs/gravitino-semantic-model-design.md@@ -124,11 +124,12 @@ The Gravitino entity combines common metadata with the Ossie-compatible definitiSemanticModelname: stringcomment?: string- ai_context?: AIContext- datasets: Dataset[1..*]- relationships?: Relationship[]- metrics?: Metric[]- custom_extensions?: CustomExtension[]+ definition: SemanticModelDefinition+ ai_context?: AIContext+ datasets: Dataset[1..*]+ relationships?: Relationship[]+ metrics?: Metric[]+ custom_extensions?: CustomExtension[]properties: map<string, string>audit_info: AuditInfo```@@ -136,6 +137,8 @@ SemanticModel- `name` is the Gravitino entity name and maps to Ossie `SemanticModel.name`.- `comment` follows the common Gravitino entity convention and maps to Ossie`SemanticModel.description`.+- `definition` is the immutable Ossie-compatible definition used by create, load, and replace+ operations.- `properties` stores Gravitino-specific metadata and is not part of an exported Ossie model.- `custom_extensions` is part of the semantic definition and is preserved for Ossie interchange.- Collection order is preserved so consumers can produce stable serialized output.@@ -337,7 +340,7 @@ SemanticModelCatalog```Expected exceptions include `NoSuchSemanticModelException`,-`SemanticModelAlreadyExistsException`, and `InvalidSemanticModelException`.+`SemanticModelAlreadyExistsException`, and `IllegalSemanticModelException`.`listSemanticModels` returns identifiers rather than complete definitions so listing a schema doesnot transfer every model body. Callers use `loadSemanticModel` to retrieve selected models.@@ -453,9 +456,9 @@ SemanticModel updated =boolean dropped = catalog.asSemanticModelCatalog().dropSemanticModel(ident);```-`SemanticModelDefinition` is an immutable request value that groups the definition fields. It has no-name or independent lifecycle and is not another metadata object. The returned `SemanticModel`-exposes its definition fields directly.+`SemanticModelDefinition` is an immutable value that groups the definition fields. It has no name or+independent lifecycle and is not another metadata object. The returned `SemanticModel` composes the+same value through `definition()` alongside the managed entity metadata.#### REST API