mchades commented on code in PR #12602: URL: https://github.com/apache/gravitino/pull/12602#discussion_r3881104162
########## core/src/main/java/org/apache/gravitino/storage/relational/service/SemanticModelMetaService.java: ########## @@ -0,0 +1,161 @@ +/* + * 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 java.io.IOException; +import java.util.Locale; +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.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. + * @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()); + SessionUtils.doMultipleWithCommit( + () -> + SchemaMetaService.getInstance() + .lockSchemaForEntityWrite( + semanticModelEntity.nameIdentifier(), + po.getSchemaId(), + po.getCatalogId(), + po.getMetalakeId()), + () -> + SessionUtils.doWithoutCommit( + SemanticModelMetaMapper.class, mapper -> ops.insertPO(mapper, po, overwrite)), + () -> + SessionUtils.doWithoutCommit( + SemanticModelVersionInfoMapper.class, + mapper -> { + if (overwrite) { + mapper.insertSemanticModelVersionInfoOnDuplicateKeyUpdate( Review Comment: This was not implemented when the comment was posted. It is fixed in [`3be4e12521`](https://github.com/apache/gravitino/commit/3be4e1252108629d40dc090e45fff4899d2e51ac). Replace now locks the persisted Semantic Model identity, advances `current_version` and `last_version` from N to N + 1, and writes snapshot N + 1 in the same transaction. Previous snapshots remain retained. The same-ID, natural-key, and concurrent overwrite cases pass on H2, MySQL, and PostgreSQL. ########## core/src/test/java/org/apache/gravitino/storage/relational/TestSemanticModelJDBCBackend.java: ########## @@ -0,0 +1,264 @@ +/* + * 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; + +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 static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.common.collect.ImmutableMap; +import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import org.apache.gravitino.Entity; +import org.apache.gravitino.EntityAlreadyExistsException; +import org.apache.gravitino.NameIdentifier; +import org.apache.gravitino.Namespace; +import org.apache.gravitino.exceptions.NoSuchEntityException; +import org.apache.gravitino.meta.SemanticModelEntity; +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; +import org.apache.gravitino.storage.RandomIdGenerator; +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.session.SqlSessionFactoryHelper; +import org.apache.gravitino.storage.relational.utils.SessionUtils; +import org.apache.gravitino.utils.NamespaceUtil; +import org.apache.ibatis.session.SqlSession; +import org.junit.jupiter.api.TestTemplate; + +/** Tests Semantic Model create and load persistence through {@link JDBCBackend}. */ +public class TestSemanticModelJDBCBackend extends TestJDBCBackend { + + @TestTemplate + public void testCreateAndLoadRoundTrip() throws IOException { + Namespace namespace = createParents("round_trip"); + SemanticModelEntity absent = + semanticModel( + RandomIdGenerator.INSTANCE.nextId(), + namespace, + "absent_optional_model", + false, + ImmutableMap.of("domain", "sales")); + SemanticModelEntity empty = + semanticModel( + RandomIdGenerator.INSTANCE.nextId(), + namespace, + "empty_optional_model", + true, + ImmutableMap.of()); + + backend.insert(absent, false); + backend.insert(empty, false); + + SemanticModelEntity loadedAbsent = + backend.get(absent.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL); + SemanticModelEntity loadedEmpty = + backend.get(empty.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL); + + assertEquals(absent, loadedAbsent); + assertEquals(empty, loadedEmpty); + assertNull(loadedAbsent.definition().relationships()); + assertNull(loadedAbsent.definition().metrics()); + assertEquals(0, loadedEmpty.definition().relationships().length); + assertEquals(0, loadedEmpty.definition().metrics().length); + assertTrue(loadedEmpty.properties().isEmpty()); + assertEquals( + new BigDecimal("1.50"), + loadedAbsent.definition().aiContext().object().additionalProperties().get("threshold")); + assertNull(loadedAbsent.definition().aiContext().object().examples()); + assertEquals(0, loadedAbsent.definition().aiContext().object().synonyms().length); + } + + @TestTemplate + public void testDuplicateAndMissingEntities() throws IOException { + Namespace namespace = createParents("duplicate"); + SemanticModelEntity original = + semanticModel( + RandomIdGenerator.INSTANCE.nextId(), + namespace, + "sales_model", + false, + ImmutableMap.of("owner", "analytics")); + backend.insert(original, false); + + SemanticModelEntity duplicate = + semanticModel( + RandomIdGenerator.INSTANCE.nextId(), + namespace, + original.name(), + true, + ImmutableMap.of()); + assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(duplicate, false)); + assertEquals( + original, backend.get(original.nameIdentifier(), Entity.EntityType.SEMANTIC_MODEL)); + + NameIdentifier missingModel = NameIdentifier.of(namespace, "missing_model"); + assertThrows( + NoSuchEntityException.class, + () -> backend.get(missingModel, Entity.EntityType.SEMANTIC_MODEL)); + + String suffix = Long.toUnsignedString(RandomIdGenerator.INSTANCE.nextId()); + String metalakeName = "missing_parent_metalake_" + suffix; + String catalogName = "missing_parent_catalog_" + suffix; + createAndInsertMakeLake(metalakeName); + createAndInsertCatalog(metalakeName, catalogName); + Namespace missingParentNamespace = + NamespaceUtil.ofSemanticModel(metalakeName, catalogName, "missing_schema"); + SemanticModelEntity missingParent = + semanticModel( + RandomIdGenerator.INSTANCE.nextId(), + missingParentNamespace, + "orphan_model", + false, + ImmutableMap.of()); + + assertThrows(NoSuchEntityException.class, () -> backend.insert(missingParent, false)); + assertEquals(0, countRows(SemanticModelMetaMapper.TABLE_NAME, missingParent.id())); + assertEquals(0, countRows(SemanticModelVersionInfoMapper.TABLE_NAME, missingParent.id())); + } + + @TestTemplate + public void testCreateRollsBackIdentityWhenSnapshotInsertFails() throws IOException { + Namespace namespace = createParents("transaction"); + SemanticModelEntity semanticModel = + semanticModel( + RandomIdGenerator.INSTANCE.nextId(), + namespace, + "transaction_model", + false, + ImmutableMap.of("domain", "finance")); + SemanticModelPO po = + SemanticModelPO.initializeSemanticModelPO(semanticModel, SemanticModelPO.builder()); + SessionUtils.doWithCommit( + SemanticModelVersionInfoMapper.class, + mapper -> mapper.insertSemanticModelVersionInfo(po.getSemanticModelVersionInfoPO())); + + assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(semanticModel, false)); + assertEquals(0, countRows(SemanticModelMetaMapper.TABLE_NAME, semanticModel.id())); + assertEquals(1, countRows(SemanticModelVersionInfoMapper.TABLE_NAME, semanticModel.id())); + } Review Comment: Implemented in [`3be4e12521`](https://github.com/apache/gravitino/commit/3be4e1252108629d40dc090e45fff4899d2e51ac). - Added same-ID and natural-key overwrite coverage, including monotonic version advancement, retained snapshots, and orphan-snapshot prevention. - Covered both read routes, missing parent/model cases, and the Semantic Model branch of `RelationalEntityStoreIdResolver`. - Added focused SerDe coverage for fully populated definitions, both AI context forms, all `DataType` values, multiple dialects, nested additional properties, null-vs-empty arrays, and a golden JSON fixture. - Added duplicate-create, overwrite-race, change-log atomicity, and create-vs-schema-drop coverage. Validation passed with 24 persistence and concurrency tests across H2, MySQL, and PostgreSQL, plus 3 focused SerDe tests. -- 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]
