Copilot commented on code in PR #12602:
URL: https://github.com/apache/gravitino/pull/12602#discussion_r3870624155


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java:
##########
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.service;
+
+import java.util.Locale;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+
+/** Provides relational persistent-object operations required to create and 
load Semantic Models. */
+public class SemanticModelPOStorageOps
+    extends BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> {
+
+  /** Creates Semantic Model persistent-object operations. */
+  public SemanticModelPOStorageOps() {}
+
+  @Override
+  public void insertPO(
+      SemanticModelMetaMapper mapper, SemanticModelPO semanticModelPO, boolean 
overwrite) {
+    if (overwrite) {
+      mapper.insertSemanticModelMetaOnDuplicateKeyUpdate(semanticModelPO);
+    } else {
+      mapper.insertSemanticModelMeta(semanticModelPO);
+    }
+  }
+
+  @Override
+  public SemanticModelPO getPO(
+      SemanticModelMetaMapper mapper, Long parentId, String semanticModelName) 
{
+    return mapper.selectSemanticModelMetaBySchemaIdAndName(parentId, 
semanticModelName);
+  }
+
+  @Override
+  public SemanticModelPO getPOByFullName(
+      SemanticModelMetaMapper mapper, NameIdentifier identifier) {
+    Namespace namespace = identifier.namespace();
+    SemanticModelPO po =
+        mapper.selectSemanticModelByFullQualifiedName(
+            namespace.level(0), namespace.level(1), namespace.level(2), 
identifier.name());
+    if (po == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,

Review Comment:
   `po == null` can happen when the metalake does not exist (because the SQL 
uses an INNER JOIN from metalake -> catalog). Throwing `NoSuchEntityException` 
for `catalog` in that case is misleading and breaks expected error semantics. A 
concrete fix is to adjust the SQL in `selectSemanticModelByFullQualifiedName` 
to `LEFT JOIN` the catalog table (similar to how schema is handled) so the 
query still returns a row when the metalake exists but the catalog does not; 
then you can throw `METALAKE` vs `CATALOG` based on which ID column is null. 
Alternatively, perform a separate existence check for metalake before running 
the current query.



##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelDefinitionSerDe.java:
##########
@@ -0,0 +1,263 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.po;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.PropertyNamingStrategies;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
+import com.fasterxml.jackson.databind.cfg.JsonNodeFeature;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.google.common.base.CaseFormat;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.semantic.AIContext;
+import org.apache.gravitino.semantic.AIContextObject;
+import org.apache.gravitino.semantic.CustomExtension;
+import org.apache.gravitino.semantic.DataType;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.DialectExpression;
+import org.apache.gravitino.semantic.Dimension;
+import org.apache.gravitino.semantic.Expression;
+import org.apache.gravitino.semantic.Field;
+import org.apache.gravitino.semantic.Metric;
+import org.apache.gravitino.semantic.Relationship;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+
+/**
+ * Serializes immutable Semantic Model API values for relational storage 
without depending on REST
+ * DTOs.
+ */
+final class SemanticModelDefinitionSerDe {
+
+  private static final ObjectMapper MAPPER = createMapper();
+
+  private SemanticModelDefinitionSerDe() {}
+
+  static String serialize(SemanticModelDefinition definition) throws 
JsonProcessingException {
+    return MAPPER.writeValueAsString(definition);
+  }
+
+  static SemanticModelDefinition deserialize(String json) throws 
JsonProcessingException {
+    return MAPPER.readValue(json, SemanticModelDefinition.class);
+  }
+
+  private static ObjectMapper createMapper() {
+    SimpleModule module =
+        new SimpleModule()
+            .addSerializer(AIContext.class, new AIContextSerializer())
+            .addDeserializer(AIContext.class, new AIContextDeserializer())
+            .addSerializer(DataType.class, new DataTypeSerializer())
+            .addDeserializer(DataType.class, new DataTypeDeserializer())
+            .addSerializer(NameIdentifier.class, new 
JsonUtils.NameIdentifierSerializer())
+            .addDeserializer(NameIdentifier.class, new 
JsonUtils.NameIdentifierDeserializer());
+
+    ObjectMapper mapper =
+        JsonUtils.anyFieldMapper()
+            .copy()
+            .setVisibility(PropertyAccessor.GETTER, 
JsonAutoDetect.Visibility.NONE)
+            .setVisibility(PropertyAccessor.IS_GETTER, 
JsonAutoDetect.Visibility.NONE)
+            .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
+            .setSerializationInclusion(JsonInclude.Include.NON_NULL)
+            .configure(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES, false)
+            .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
+            .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)
+            .registerModule(module);
+    addBuilderMixIns(
+        mapper,
+        SemanticModelDefinition.class,
+        SemanticModelDefinitionMixIn.class,
+        SemanticModelDefinition.Builder.class);
+    addBuilderMixIns(mapper, Dataset.class, DatasetMixIn.class, 
Dataset.Builder.class);
+    addBuilderMixIns(
+        mapper, Relationship.class, RelationshipMixIn.class, 
Relationship.Builder.class);
+    addBuilderMixIns(mapper, Metric.class, MetricMixIn.class, 
Metric.Builder.class);
+    addBuilderMixIns(mapper, Field.class, FieldMixIn.class, 
Field.Builder.class);
+    addBuilderMixIns(mapper, Expression.class, ExpressionMixIn.class, 
Expression.Builder.class);
+    addBuilderMixIns(
+        mapper,
+        DialectExpression.class,
+        DialectExpressionMixIn.class,
+        DialectExpression.Builder.class);
+    addBuilderMixIns(mapper, Dimension.class, DimensionMixIn.class, 
Dimension.Builder.class);
+    addBuilderMixIns(
+        mapper, CustomExtension.class, CustomExtensionMixIn.class, 
CustomExtension.Builder.class);
+    return mapper;
+  }
+
+  private static void addBuilderMixIns(
+      ObjectMapper mapper, Class<?> valueClass, Class<?> mixInClass, Class<?> 
builderClass) {
+    mapper.addMixIn(valueClass, mixInClass);
+    mapper.addMixIn(builderClass, BuilderMixIn.class);
+  }
+
+  @JsonPOJOBuilder(withPrefix = "with")
+  private abstract static class BuilderMixIn {}
+
+  @JsonDeserialize(builder = SemanticModelDefinition.Builder.class)
+  private abstract static class SemanticModelDefinitionMixIn {}
+
+  @JsonDeserialize(builder = Dataset.Builder.class)
+  private abstract static class DatasetMixIn {}
+
+  @JsonDeserialize(builder = Relationship.Builder.class)
+  private abstract static class RelationshipMixIn {}
+
+  @JsonDeserialize(builder = Metric.Builder.class)
+  private abstract static class MetricMixIn {}
+
+  @JsonDeserialize(builder = Field.Builder.class)
+  private abstract static class FieldMixIn {}
+
+  @JsonDeserialize(builder = Expression.Builder.class)
+  private abstract static class ExpressionMixIn {}
+
+  @JsonDeserialize(builder = DialectExpression.Builder.class)
+  private abstract static class DialectExpressionMixIn {}
+
+  @JsonDeserialize(builder = Dimension.Builder.class)
+  private abstract static class DimensionMixIn {}
+
+  @JsonDeserialize(builder = CustomExtension.Builder.class)
+  private abstract static class CustomExtensionMixIn {}
+
+  private static final class AIContextSerializer extends 
JsonSerializer<AIContext> {
+
+    @Override
+    public void serialize(AIContext value, JsonGenerator generator, 
SerializerProvider serializers)
+        throws IOException {
+      if (value.isText()) {
+        generator.writeString(value.text());
+        return;
+      }
+
+      AIContextObject object = value.object();
+      if (object == null) {
+        throw JsonMappingException.from(generator, "Structured AI context must 
not be null");
+      }
+      generator.writeStartObject();
+      writeOptionalField(generator, "instructions", object.instructions());
+      writeOptionalField(generator, "synonyms", object.synonyms());
+      writeOptionalField(generator, "examples", object.examples());
+      for (Map.Entry<String, Object> entry : 
object.additionalProperties().entrySet()) {
+        generator.writeObjectField(entry.getKey(), entry.getValue());
+      }

Review Comment:
   If `additionalProperties` contains reserved keys (`instructions`, 
`synonyms`, `examples`), this serializer will emit duplicate JSON fields, and 
the deserializer will treat them as 'standard' fields (and exclude them from 
`additionalProperties`), making round-trips order-dependent and potentially 
lossy. Filter out reserved keys during serialization (or validate and fail 
fast) so the JSON is unambiguous and symmetric with the deserializer.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelPOStorageOps.java:
##########
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.service;
+
+import java.util.Locale;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+
+/** Provides relational persistent-object operations required to create and 
load Semantic Models. */
+public class SemanticModelPOStorageOps
+    extends BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> {
+
+  /** Creates Semantic Model persistent-object operations. */
+  public SemanticModelPOStorageOps() {}
+
+  @Override
+  public void insertPO(
+      SemanticModelMetaMapper mapper, SemanticModelPO semanticModelPO, boolean 
overwrite) {
+    if (overwrite) {
+      mapper.insertSemanticModelMetaOnDuplicateKeyUpdate(semanticModelPO);
+    } else {
+      mapper.insertSemanticModelMeta(semanticModelPO);
+    }
+  }
+
+  @Override
+  public SemanticModelPO getPO(
+      SemanticModelMetaMapper mapper, Long parentId, String semanticModelName) 
{
+    return mapper.selectSemanticModelMetaBySchemaIdAndName(parentId, 
semanticModelName);
+  }
+
+  @Override
+  public SemanticModelPO getPOByFullName(
+      SemanticModelMetaMapper mapper, NameIdentifier identifier) {
+    Namespace namespace = identifier.namespace();
+    SemanticModelPO po =
+        mapper.selectSemanticModelByFullQualifiedName(
+            namespace.level(0), namespace.level(1), namespace.level(2), 
identifier.name());
+    if (po == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.CATALOG.name().toLowerCase(Locale.ROOT),
+          namespace.level(1));

Review Comment:
   Given the conditional behavior here (`po == null` vs `schemaId == null` vs 
`semanticModelId == null`), add a targeted test covering the 'missing metalake' 
and 'missing catalog' cases so the thrown `NoSuchEntityException` type/name are 
asserted. This will prevent regressions when adjusting the query/join strategy 
to fix the metalake-vs-catalog ambiguity.



##########
core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/SemanticModelVersionInfoPostgreSQLProvider.java:
##########
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.mapper.provider.postgresql;
+
+import 
org.apache.gravitino.storage.relational.mapper.provider.base.SemanticModelVersionInfoBaseSQLProvider;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.ibatis.annotations.Param;
+
+/** Provides PostgreSQL SQL for creating Semantic Model version snapshots. */
+public class SemanticModelVersionInfoPostgreSQLProvider
+    extends SemanticModelVersionInfoBaseSQLProvider {
+
+  @Override
+  public String insertSemanticModelVersionInfoOnDuplicateKeyUpdate(
+      @Param("semanticModelVersionInfo") SemanticModelVersionInfoPO 
versionInfoPO) {
+    return insertSemanticModelVersionInfo(versionInfoPO)
+        + " ON CONFLICT (semantic_model_id, version, deleted_at) DO UPDATE SET"
+        + " semantic_model_name = 
#{semanticModelVersionInfo.semanticModelName},"
+        + " semantic_model_comment = 
#{semanticModelVersionInfo.semanticModelComment},"
+        + " semantic_model_definition = 
#{semanticModelVersionInfo.semanticModelDefinition},"
+        + " properties = #{semanticModelVersionInfo.properties},"
+        + " audit_info = #{semanticModelVersionInfo.auditInfo},"
+        + " deleted_at = #{semanticModelVersionInfo.deletedAt}";

Review Comment:
   The upsert updates `deleted_at` even though it's part of the conflict 
target; updating conflict-key columns is unnecessary and can create unexpected 
behavior if `deletedAt` differs from the existing row (e.g., update may violate 
uniqueness against other rows). Prefer omitting `deleted_at` from the `DO 
UPDATE SET` list and treat it as immutable for a given (semantic_model_id, 
version) snapshot row.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to