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


##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.service;
+
+import static 
org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static 
org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static 
org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import 
org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model 
metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new 
SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new 
SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String 
semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, 
semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier 
identifier) {
+    SemanticModelPO semanticModelPO = 
getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts a Semantic Model identity and its version-one snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or 
natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, 
boolean overwrite)
+      throws IOException {
+    
NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, 
SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>();
+      AtomicReference<SemanticModelVersionInfoPO> persistedVersionInfoPO =
+          new AtomicReference<>(po.getSemanticModelVersionInfoPO());
+      SessionUtils.doMultipleWithCommit(
+          () ->
+              SchemaMetaService.getInstance()
+                  .lockSchemaForEntityWrite(
+                      semanticModelEntity.nameIdentifier(),
+                      po.getSchemaId(),
+                      po.getCatalogId(),
+                      po.getMetalakeId()),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelMetaMapper.class,
+                  mapper -> {
+                    if (overwrite) {

Review Comment:
   Fixed. The missing-row path now uses a strict insert, so a concurrent 
natural-key collision fails instead of upserting with a different ID. Existing 
rows are locked by natural key and updated using the persisted ID and next 
version, keeping the identity and snapshot consistent.



##########
core/src/main/java/org/apache/gravitino/cache/BaseEntityCache.java:
##########
@@ -58,6 +58,7 @@ public abstract class BaseEntityCache implements EntityCache {
           Entity.EntityType.CATALOG,
           Entity.EntityType.SCHEMA,
           Entity.EntityType.TABLE,
+          Entity.EntityType.SEMANTIC_MODEL,

Review Comment:
   Fixed. Removed `SEMANTIC_MODEL` from `CACHEABLE_TYPES` and updated the cache 
documentation and tests. Local-cache deployments now read Semantic Models from 
the store, avoiding stale definitions during the cross-node invalidation window.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.service;
+
+import static 
org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static 
org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static 
org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import 
org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model 
metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new 
SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new 
SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String 
semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, 
semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier 
identifier) {
+    SemanticModelPO semanticModelPO = 
getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts a Semantic Model identity and its version-one snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or 
natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, 
boolean overwrite)
+      throws IOException {
+    
NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, 
SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>();
+      AtomicReference<SemanticModelVersionInfoPO> persistedVersionInfoPO =
+          new AtomicReference<>(po.getSemanticModelVersionInfoPO());
+      SessionUtils.doMultipleWithCommit(
+          () ->
+              SchemaMetaService.getInstance()
+                  .lockSchemaForEntityWrite(
+                      semanticModelEntity.nameIdentifier(),
+                      po.getSchemaId(),
+                      po.getCatalogId(),
+                      po.getMetalakeId()),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelMetaMapper.class,
+                  mapper -> {
+                    if (overwrite) {
+                      Long persistedId =
+                          mapper.selectSemanticModelIdBySchemaIdAndName(
+                              po.getSchemaId(), po.getSemanticModelName());
+                      SemanticModelPO existingPO =
+                          mapper.selectSemanticModelMetaByIdForUpdate(
+                              persistedId == null ? po.getSemanticModelId() : 
persistedId);
+                      persistedPO.set(existingPO);
+                      if (existingPO != null) {
+                        persistedVersionInfoPO.set(
+                            versionInfoForOverwrite(
+                                po.getSemanticModelVersionInfoPO(), 
existingPO));
+                      }
+                    }
+                    ops.insertPO(
+                        mapper,
+                        persistedPO.get() == null
+                            ? po
+                            : identityForOverwrite(po, persistedPO.get()),
+                        overwrite);
+                  }),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelVersionInfoMapper.class,
+                  mapper -> {
+                    if (overwrite) {
+                      
mapper.insertSemanticModelVersionInfoOnDuplicateKeyUpdate(
+                          persistedVersionInfoPO.get());
+                    } else {
+                      
mapper.insertSemanticModelVersionInfo(po.getSemanticModelVersionInfoPO());
+                    }
+                  }));
+    } catch (RuntimeException re) {
+      ExceptionUtils.checkSQLException(
+          re, Entity.EntityType.SEMANTIC_MODEL, 
semanticModelEntity.nameIdentifier().toString());
+      throw re;
+    }
+  }
+
+  /** Returns the persistent-object operations used by this service. */
+  public BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops() {
+    return ops;
+  }
+
+  private static SemanticModelPO identityForOverwrite(
+      SemanticModelPO source, SemanticModelPO persistedPO) {
+    return SemanticModelPO.builder()
+        .withSemanticModelId(persistedPO.getSemanticModelId())
+        .withSemanticModelName(source.getSemanticModelName())
+        .withMetalakeId(source.getMetalakeId())
+        .withCatalogId(source.getCatalogId())
+        .withSchemaId(source.getSchemaId())
+        .withAuditInfo(source.getAuditInfo())
+        .withCurrentVersion(source.getCurrentVersion())

Review Comment:
   Fixed. Overwrites now derive one `nextVersion` from the persisted current 
and last versions and use it for both the identity row and version snapshot.



##########
core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java:
##########
@@ -0,0 +1,226 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.storage.relational.service;
+
+import static 
org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static 
org.apache.gravitino.storage.relational.po.SemanticModelPO.fromSemanticModelPO;
+import static 
org.apache.gravitino.storage.relational.po.SemanticModelPO.initializeSemanticModelPO;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Locale;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.SemanticModelEntity;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.SemanticModelMetaMapper;
+import 
org.apache.gravitino.storage.relational.mapper.SemanticModelVersionInfoMapper;
+import org.apache.gravitino.storage.relational.po.SemanticModelPO;
+import org.apache.gravitino.storage.relational.po.SemanticModelVersionInfoPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+
+/** Provides relational create and load operations for Semantic Model 
metadata. */
+public class SemanticModelMetaService {
+
+  private static final SemanticModelMetaService INSTANCE = new 
SemanticModelMetaService();
+
+  private final BasePOStorageOps<SemanticModelPO, SemanticModelMetaMapper> ops;
+
+  /** Returns the singleton Semantic Model metadata service. */
+  public static SemanticModelMetaService getInstance() {
+    return INSTANCE;
+  }
+
+  private SemanticModelMetaService() {
+    this.ops = new HierarchicalConversionPOStorageOps<>(new 
SemanticModelPOStorageOps());
+  }
+
+  /**
+   * Resolves a Semantic Model stable ID by schema ID and name.
+   *
+   * @param schemaId The parent schema ID.
+   * @param semanticModelName The Semantic Model name.
+   * @return The stable Semantic Model ID.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelIdBySchemaIdAndName")
+  public Long getSemanticModelIdBySchemaIdAndName(long schemaId, String 
semanticModelName) {
+    Long semanticModelId =
+        SessionUtils.getWithoutCommit(
+            SemanticModelMetaMapper.class,
+            mapper -> mapper.selectSemanticModelIdBySchemaIdAndName(schemaId, 
semanticModelName));
+    if (semanticModelId == null) {
+      throw new NoSuchEntityException(
+          NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+          Entity.EntityType.SEMANTIC_MODEL.name().toLowerCase(Locale.ROOT),
+          semanticModelName);
+    }
+    return semanticModelId;
+  }
+
+  /**
+   * Loads the current Semantic Model by identifier.
+   *
+   * @param identifier The Semantic Model identifier.
+   * @return The current Semantic Model entity.
+   * @throws NoSuchEntityException If the Semantic Model does not exist.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "getSemanticModelByIdentifier")
+  public SemanticModelEntity getSemanticModelByIdentifier(NameIdentifier 
identifier) {
+    SemanticModelPO semanticModelPO = 
getSemanticModelPOByIdentifier(identifier);
+    return fromSemanticModelPO(semanticModelPO, identifier.namespace());
+  }
+
+  /**
+   * Inserts a Semantic Model identity and its version-one snapshot atomically.
+   *
+   * @param semanticModelEntity The Semantic Model entity.
+   * @param overwrite Whether to overwrite rows for the same stable ID or 
natural key.
+   * @throws IOException If relational persistence fails.
+   */
+  @Monitored(
+      metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+      baseMetricName = "insertSemanticModel")
+  public void insertSemanticModel(SemanticModelEntity semanticModelEntity, 
boolean overwrite)
+      throws IOException {
+    
NameIdentifierUtil.checkSemanticModel(semanticModelEntity.nameIdentifier());
+    try {
+      SemanticModelPO po =
+          initializeSemanticModelPO(semanticModelEntity, 
SemanticModelPO.builder());
+      AtomicReference<SemanticModelPO> persistedPO = new AtomicReference<>();
+      AtomicReference<SemanticModelVersionInfoPO> persistedVersionInfoPO =
+          new AtomicReference<>(po.getSemanticModelVersionInfoPO());
+      SessionUtils.doMultipleWithCommit(
+          () ->
+              SchemaMetaService.getInstance()
+                  .lockSchemaForEntityWrite(
+                      semanticModelEntity.nameIdentifier(),
+                      po.getSchemaId(),
+                      po.getCatalogId(),
+                      po.getMetalakeId()),
+          () ->
+              SessionUtils.doWithoutCommit(
+                  SemanticModelMetaMapper.class,
+                  mapper -> {
+                    if (overwrite) {
+                      Long persistedId =

Review Comment:
   Fixed. Removed the separate ID lookup and duplicated upsert version bump. 
The overwrite path now uses one natural-key locking read followed by a 
version-checked update, sharing the same `nextVersion` with the snapshot insert.



##########
core/src/main/java/org/apache/gravitino/storage/relational/po/SemanticModelDefinitionSerDe.java:
##########
@@ -0,0 +1,265 @@
+/*
+ * 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)
+            .setDefaultPropertyInclusion(
+                JsonInclude.Value.construct(
+                    JsonInclude.Include.NON_NULL, JsonInclude.Include.ALWAYS))
+            .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> {

Review Comment:
   Fixed. Removed `SemanticModelDefinitionSerDe` and now serialize and 
deserialize through `SemanticModelDefinitionDTO` in `SemanticModelPO`.



-- 
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