World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#10878] feat(core): add relational storage for logical views with versioning (#10879)
mchades2c0711ad3020
diff --git a/common/src/main/java/org/apache/gravitino/config/ConfigConstants.java b/common/src/main/java/org/apache/gravitino/config/ConfigConstants.javaindex c6a4872cfc..78e5b69b11 100644--- a/common/src/main/java/org/apache/gravitino/config/ConfigConstants.java+++ b/common/src/main/java/org/apache/gravitino/config/ConfigConstants.java@@ -93,5 +93,5 @@ public final class ConfigConstants {public static final String VERSION_1_3_0 = "1.3.0";/** The current version of backend storage initialization script. */- public static final String CURRENT_SCRIPT_VERSION = VERSION_1_2_0;+ public static final String CURRENT_SCRIPT_VERSION = VERSION_1_3_0;}diff --git a/common/src/main/java/org/apache/gravitino/dto/rel/RepresentationDTO.java b/common/src/main/java/org/apache/gravitino/dto/rel/RepresentationDTO.javanew file mode 100644index 0000000000..69ef28d808--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/rel/RepresentationDTO.java@@ -0,0 +1,61 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.dto.rel;++import com.fasterxml.jackson.annotation.JsonSubTypes;+import com.fasterxml.jackson.annotation.JsonTypeInfo;+import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.SQLRepresentation;++/** DTO for view representation serde. */+@JsonTypeInfo(+ use = JsonTypeInfo.Id.NAME,+ include = JsonTypeInfo.As.PROPERTY,+ property = "type",+ defaultImpl = SQLRepresentationDTO.class)+@JsonSubTypes({+ @JsonSubTypes.Type(value = SQLRepresentationDTO.class, name = Representation.TYPE_SQL)+})+public abstract class RepresentationDTO implements Representation {++ /** Constructor for Jackson. */+ protected RepresentationDTO() {}++ /**+ * Converts this DTO to a representation object.+ *+ * @return The representation object.+ */+ public abstract Representation toRepresentation();++ /**+ * Creates a representation DTO from a representation object.+ *+ * @param representation The representation object.+ * @return The representation DTO.+ */+ public static RepresentationDTO fromRepresentation(Representation representation) {+ if (representation instanceof SQLRepresentation) {+ return SQLRepresentationDTO.fromSQLRepresentation((SQLRepresentation) representation);+ }++ throw new IllegalArgumentException(+ "Unsupported representation type: " + representation.getClass().getName());+ }+}diff --git a/common/src/main/java/org/apache/gravitino/dto/rel/SQLRepresentationDTO.java b/common/src/main/java/org/apache/gravitino/dto/rel/SQLRepresentationDTO.javanew file mode 100644index 0000000000..c53f9798d9--- /dev/null+++ b/common/src/main/java/org/apache/gravitino/dto/rel/SQLRepresentationDTO.java@@ -0,0 +1,70 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.dto.rel;++import com.fasterxml.jackson.annotation.JsonProperty;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.SQLRepresentation;++/** DTO for SQL representation. */+@Getter+@EqualsAndHashCode(callSuper = true)+public class SQLRepresentationDTO extends RepresentationDTO {++ @JsonProperty("dialect")+ private String dialect;++ @JsonProperty("sql")+ private String sql;++ private SQLRepresentationDTO() {}++ /**+ * Creates a SQL representation DTO.+ *+ * @param dialect SQL dialect.+ * @param sql SQL body.+ */+ public SQLRepresentationDTO(String dialect, String sql) {+ this.dialect = dialect;+ this.sql = sql;+ }++ @Override+ public String type() {+ return Representation.TYPE_SQL;+ }++ @Override+ public SQLRepresentation toRepresentation() {+ return SQLRepresentation.builder().withDialect(dialect).withSql(sql).build();+ }++ /**+ * Creates SQL representation DTO from SQL representation.+ *+ * @param representation SQL representation.+ * @return SQL representation DTO.+ */+ public static SQLRepresentationDTO fromSQLRepresentation(SQLRepresentation representation) {+ return new SQLRepresentationDTO(representation.dialect(), representation.sql());+ }+}diff --git a/common/src/test/java/org/apache/gravitino/dto/rel/TestRepresentationDTO.java b/common/src/test/java/org/apache/gravitino/dto/rel/TestRepresentationDTO.javanew file mode 100644index 0000000000..5e00ead7b5--- /dev/null+++ b/common/src/test/java/org/apache/gravitino/dto/rel/TestRepresentationDTO.java@@ -0,0 +1,56 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.dto.rel;++import com.fasterxml.jackson.core.JsonProcessingException;+import org.apache.gravitino.json.JsonUtils;+import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.SQLRepresentation;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestRepresentationDTO {++ @Test+ public void testRepresentationDTOSerDe() throws JsonProcessingException {+ SQLRepresentationDTO sqlRepresentationDTO =+ SQLRepresentationDTO.fromSQLRepresentation(+ SQLRepresentation.builder().withDialect("spark").withSql("SELECT 1").build());++ String json = JsonUtils.objectMapper().writeValueAsString(sqlRepresentationDTO);+ RepresentationDTO deserialized =+ JsonUtils.objectMapper().readValue(json, RepresentationDTO.class);++ Assertions.assertInstanceOf(SQLRepresentationDTO.class, deserialized);+ Assertions.assertEquals(Representation.TYPE_SQL, deserialized.type());+ Assertions.assertEquals("spark", ((SQLRepresentationDTO) deserialized).getDialect());+ Assertions.assertEquals("SELECT 1", ((SQLRepresentationDTO) deserialized).getSql());+ }++ @Test+ public void testRepresentationDTOConversion() {+ Representation representation =+ SQLRepresentation.builder().withDialect("trino").withSql("SELECT c1 FROM t").build();++ RepresentationDTO dto = RepresentationDTO.fromRepresentation(representation);+ Representation converted = dto.toRepresentation();++ Assertions.assertEquals(representation, converted);+ }+}diff --git a/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedView.java b/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedView.javaindex e11f89b2d6..efecf015de 100644--- a/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedView.java+++ b/core/src/main/java/org/apache/gravitino/catalog/EntityCombinedView.java@@ -20,33 +20,33 @@ package org.apache.gravitino.catalog;import java.util.Map;import org.apache.gravitino.Audit;-import org.apache.gravitino.meta.GenericEntity;+import org.apache.gravitino.meta.ViewEntity;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Representation;import org.apache.gravitino.rel.View;/*** A View class to represent a view metadata object that combines the metadata both from {@link- * View} and {@link GenericEntity}.+ * View} and {@link ViewEntity}.*/public final class EntityCombinedView implements View {private final View view;- private final GenericEntity viewEntity;+ private final ViewEntity viewEntity;// Field "imported" is used to indicate whether the entity has been imported to Gravitino// managed storage backend. If "imported" is true, it means that storage backend have stored// the correct entity. Otherwise, we should import the external entity to the storage backend.private boolean imported;- private EntityCombinedView(View view, GenericEntity viewEntity) {+ private EntityCombinedView(View view, ViewEntity viewEntity) {this.view = view;this.viewEntity = viewEntity;this.imported = false;}- public static EntityCombinedView of(View view, GenericEntity viewEntity) {+ public static EntityCombinedView of(View view, ViewEntity viewEntity) {return new EntityCombinedView(view, viewEntity);}@@ -107,7 +107,7 @@ public final class EntityCombinedView implements View {return view;}- public GenericEntity viewFromGravitino() {+ public ViewEntity viewFromGravitino() {return viewEntity;}}diff --git a/core/src/main/java/org/apache/gravitino/catalog/ViewOperationDispatcher.java b/core/src/main/java/org/apache/gravitino/catalog/ViewOperationDispatcher.javaindex 4c334effe6..1c1ad964a0 100644--- a/core/src/main/java/org/apache/gravitino/catalog/ViewOperationDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/catalog/ViewOperationDispatcher.java@@ -21,16 +21,24 @@ package org.apache.gravitino.catalog;import static org.apache.gravitino.utils.NameIdentifierUtil.getCatalogIdentifier;import java.io.IOException;+import java.util.Map;+import javax.annotation.Nullable;+import org.apache.gravitino.Audit;import org.apache.gravitino.Entity;import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.exceptions.NoSuchViewException;import org.apache.gravitino.lock.LockType;import org.apache.gravitino.lock.TreeLockUtils;-import org.apache.gravitino.meta.GenericEntity;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.ViewEntity;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Representation;import org.apache.gravitino.rel.View;+import org.apache.gravitino.rel.ViewChange;import org.apache.gravitino.storage.IdGenerator;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -89,6 +97,33 @@ public class ViewOperationDispatcher extends OperationDispatcher implements Viewreturn entityCombinedView;}+ @Override+ public NameIdentifier[] listViews(Namespace namespace) {+ throw new UnsupportedOperationException("Listing views is not supported yet");+ }++ @Override+ public boolean dropView(NameIdentifier ident) {+ throw new UnsupportedOperationException("Dropping a view is not supported yet");+ }++ @Override+ public View createView(+ NameIdentifier ident,+ String comment,+ Column[] columns,+ Representation[] representations,+ @Nullable String defaultCatalog,+ @Nullable String defaultSchema,+ Map<String, String> properties) {+ throw new UnsupportedOperationException("Creating a view is not supported yet");+ }++ @Override+ public View alterView(NameIdentifier ident, ViewChange... changes) {+ throw new UnsupportedOperationException("Altering a view is not supported yet");+ }+/*** Internal method to load view and check if it exists in entity store.*@@ -106,7 +141,7 @@ public class ViewOperationDispatcher extends OperationDispatcher implements View// Check if view exists in entity storetry {- GenericEntity viewEntity = store.get(ident, Entity.EntityType.VIEW, GenericEntity.class);+ ViewEntity viewEntity = store.get(ident, Entity.EntityType.VIEW, ViewEntity.class);return EntityCombinedView.of(catalogView, viewEntity).withImported(true);} catch (NoSuchEntityException e) {// View not in store yet@@ -135,22 +170,45 @@ public class ViewOperationDispatcher extends OperationDispatcher implements ViewLOG.info("Auto-importing view {} into Gravitino entity store", ident);long uid = idGenerator.nextId();- GenericEntity newViewEntity =- GenericEntity.builder()- .withId(uid)- .withName(ident.name())- .withNamespace(ident.namespace())- .withEntityType(Entity.EntityType.VIEW)- .build();+ View catalogView = entityCombinedView.viewFromCatalog();+ ViewEntity newViewEntity = buildViewEntityForImport(uid, ident, catalogView);try {store.put(newViewEntity, false /* overwrite */);LOG.info("Successfully imported view {} into entity store with id {}", ident, uid);- return EntityCombinedView.of(entityCombinedView.viewFromCatalog(), newViewEntity)- .withImported(true);+ return EntityCombinedView.of(catalogView, newViewEntity).withImported(true);} catch (Exception e) {// Log but don't fail - view import is best-effortLOG.warn("Failed to import view {} into entity store: {}", ident, e.getMessage());- return EntityCombinedView.of(entityCombinedView.viewFromCatalog()).withImported(false);+ return EntityCombinedView.of(catalogView).withImported(false);}}++ private ViewEntity buildViewEntityForImport(Long uid, NameIdentifier ident, View view) {+ return ViewEntity.builder()+ .withId(uid)+ .withName(ident.name())+ .withNamespace(ident.namespace())+ .withComment(view.comment())+ .withColumns(view.columns() == null ? new Column[0] : view.columns())+ .withRepresentations(+ view.representations() == null ? new Representation[0] : view.representations())+ .withDefaultCatalog(view.defaultCatalog())+ .withDefaultSchema(view.defaultSchema())+ .withProperties(view.properties())+ .withAuditInfo(toAuditInfo(view.auditInfo()))+ .build();+ }++ private AuditInfo toAuditInfo(Audit audit) {+ if (audit == null) {+ return AuditInfo.EMPTY;+ }++ return AuditInfo.builder()+ .withCreator(audit.creator())+ .withCreateTime(audit.createTime())+ .withLastModifier(audit.lastModifier())+ .withLastModifiedTime(audit.lastModifiedTime())+ .build();+ }}diff --git a/core/src/main/java/org/apache/gravitino/meta/ViewEntity.java b/core/src/main/java/org/apache/gravitino/meta/ViewEntity.javanew file mode 100644index 0000000000..3ee0d80137--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/meta/ViewEntity.java@@ -0,0 +1,331 @@+/*+ * 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.meta;++import com.google.common.collect.Maps;+import java.util.Arrays;+import java.util.Collections;+import java.util.Map;+import java.util.Objects;+import lombok.ToString;+import org.apache.gravitino.Auditable;+import org.apache.gravitino.Entity;+import org.apache.gravitino.Field;+import org.apache.gravitino.HasIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.View;++/** A class representing a view entity in the metadata store. */+@ToString+public class ViewEntity implements Entity, Auditable, HasIdentifier, View {++ public static final Field ID =+ Field.required("id", Long.class, "The unique id of the view entity.");+ public static final Field NAME =+ Field.required("name", String.class, "The name of the view entity.");+ public static final Field NAMESPACE =+ Field.required("namespace", Namespace.class, "The namespace of the view entity.");+ public static final Field COMMENT =+ Field.optional("comment", String.class, "The comment or description of the view entity.");+ public static final Field COLUMNS =+ Field.required("columns", Column[].class, "The output columns of the view.");+ public static final Field REPRESENTATIONS =+ Field.required("representations", Representation[].class, "The view representations.");+ public static final Field DEFAULT_CATALOG =+ Field.optional(+ "default_catalog",+ String.class,+ "The default catalog used to resolve unqualified identifiers in the view definition.");+ public static final Field DEFAULT_SCHEMA =+ Field.optional(+ "default_schema",+ String.class,+ "The default schema used to resolve unqualified identifiers in the view definition.");+ public static final Field PROPERTIES =+ Field.optional("properties", Map.class, "The properties of the view.");+ public static final Field AUDIT_INFO =+ Field.required("audit_info", AuditInfo.class, "The audit details of the view entity.");++ private Long id;+ private String name;+ private Namespace namespace;+ private String comment;+ private Column[] columns;+ private Representation[] representations;+ private String defaultCatalog;+ private String defaultSchema;+ private Map<String, String> properties;+ private AuditInfo auditInfo;++ private ViewEntity() {}++ @Override+ public Map<Field, Object> fields() {+ Map<Field, Object> fields = Maps.newHashMap();+ fields.put(ID, id);+ fields.put(NAME, name);+ fields.put(NAMESPACE, namespace);+ fields.put(COMMENT, comment);+ fields.put(COLUMNS, columns);+ fields.put(REPRESENTATIONS, representations);+ fields.put(DEFAULT_CATALOG, defaultCatalog);+ fields.put(DEFAULT_SCHEMA, defaultSchema);+ fields.put(PROPERTIES, properties);+ fields.put(AUDIT_INFO, auditInfo);+ return Collections.unmodifiableMap(fields);+ }++ @Override+ public String name() {+ return name;+ }++ @Override+ public Long id() {+ return id;+ }++ @Override+ public Namespace namespace() {+ return namespace;+ }++ @Override+ public String comment() {+ return comment;+ }++ @Override+ public Column[] columns() {+ return columns;+ }++ @Override+ public Representation[] representations() {+ return representations;+ }++ /**+ * Returns the default catalog used to resolve unqualified identifiers in the view definition.+ *+ * @return The default catalog, or {@code null} if not set.+ */+ @Override+ public String defaultCatalog() {+ return defaultCatalog;+ }++ /**+ * Returns the default schema used to resolve unqualified identifiers in the view definition.+ *+ * @return The default schema, or {@code null} if not set.+ */+ @Override+ public String defaultSchema() {+ return defaultSchema;+ }++ @Override+ public Map<String, String> properties() {+ return properties == null ? Collections.emptyMap() : properties;+ }++ @Override+ public AuditInfo auditInfo() {+ return auditInfo;+ }++ @Override+ public EntityType type() {+ return EntityType.VIEW;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) {+ return true;+ }+ if (!(o instanceof ViewEntity)) {+ return false;+ }+ ViewEntity that = (ViewEntity) o;+ return Objects.equals(id, that.id)+ && Objects.equals(name, that.name)+ && Objects.equals(namespace, that.namespace)+ && Objects.equals(comment, that.comment)+ && Arrays.equals(columns, that.columns)+ && Arrays.equals(representations, that.representations)+ && Objects.equals(defaultCatalog, that.defaultCatalog)+ && Objects.equals(defaultSchema, that.defaultSchema)+ && Objects.equals(properties, that.properties)+ && Objects.equals(auditInfo, that.auditInfo);+ }++ @Override+ public int hashCode() {+ int result =+ Objects.hash(+ id, name, namespace, comment, defaultCatalog, defaultSchema, properties, auditInfo);+ result = 31 * result + Arrays.hashCode(columns);+ result = 31 * result + Arrays.hashCode(representations);+ return result;+ }++ /**+ * Creates a new builder for constructing a ViewEntity.+ *+ * @return A new builder instance.+ */+ public static Builder builder() {+ return new Builder();+ }++ /** Builder class for creating instances of {@link ViewEntity}. */+ public static class Builder {+ private final ViewEntity viewEntity;++ private Builder() {+ viewEntity = new ViewEntity();+ }++ /**+ * Sets the unique id of the view entity.+ *+ * @param id The unique id.+ * @return This builder instance.+ */+ public Builder withId(Long id) {+ viewEntity.id = id;+ return this;+ }++ /**+ * Sets the name of the view entity.+ *+ * @param name The name of the view.+ * @return This builder instance.+ */+ public Builder withName(String name) {+ viewEntity.name = name;+ return this;+ }++ /**+ * Sets the namespace of the view entity.+ *+ * @param namespace The namespace.+ * @return This builder instance.+ */+ public Builder withNamespace(Namespace namespace) {+ viewEntity.namespace = namespace;+ return this;+ }++ /**+ * Sets the comment of the view entity.+ *+ * @param comment The comment or description.+ * @return This builder instance.+ */+ public Builder withComment(String comment) {+ viewEntity.comment = comment;+ return this;+ }++ /**+ * Sets the output columns of the view.+ *+ * @param columns The view columns snapshot.+ * @return This builder instance.+ */+ public Builder withColumns(Column[] columns) {+ viewEntity.columns = columns;+ return this;+ }++ /**+ * Sets the representations of the view.+ *+ * @param representations The view representations.+ * @return This builder instance.+ */+ public Builder withRepresentations(Representation[] representations) {+ viewEntity.representations = representations;+ return this;+ }++ /**+ * Sets the default catalog used to resolve unqualified identifiers referenced by the view+ * definition.+ *+ * @param defaultCatalog The default catalog, may be {@code null}.+ * @return This builder instance.+ */+ public Builder withDefaultCatalog(String defaultCatalog) {+ viewEntity.defaultCatalog = defaultCatalog;+ return this;+ }++ /**+ * Sets the default schema used to resolve unqualified identifiers referenced by the view+ * definition.+ *+ * @param defaultSchema The default schema, may be {@code null}.+ * @return This builder instance.+ */+ public Builder withDefaultSchema(String defaultSchema) {+ viewEntity.defaultSchema = defaultSchema;+ return this;+ }++ /**+ * Sets the properties of the view.+ *+ * @param properties The view properties.+ * @return This builder instance.+ */+ public Builder withProperties(Map<String, String> properties) {+ viewEntity.properties = properties;+ return this;+ }++ /**+ * Sets the audit information.+ *+ * @param auditInfo The audit information.+ * @return This builder instance.+ */+ public Builder withAuditInfo(AuditInfo auditInfo) {+ viewEntity.auditInfo = auditInfo;+ return this;+ }++ /**+ * Builds the ViewEntity instance.+ *+ * @return The constructed ViewEntity.+ */+ public ViewEntity build() {+ viewEntity.validate();+ return viewEntity;+ }+ }+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.javaindex 900065f87a..43c7fe2335 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java@@ -60,6 +60,7 @@ import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.meta.TagEntity;import org.apache.gravitino.meta.TopicEntity;import org.apache.gravitino.meta.UserEntity;+import org.apache.gravitino.meta.ViewEntity;import org.apache.gravitino.storage.relational.converters.SQLExceptionConverterFactory;import org.apache.gravitino.storage.relational.database.H2Database;import org.apache.gravitino.storage.relational.service.CatalogMetaService;@@ -211,14 +212,12 @@ public class JDBCBackend implements RelationalBackend {JobTemplateMetaService.getInstance().insertJobTemplate((JobTemplateEntity) e, overwritten);} else if (e instanceof JobEntity) {JobMetaService.getInstance().insertJob((JobEntity) e, overwritten);+ } else if (e instanceof ViewEntity) {+ ViewMetaService.getInstance().insertView((ViewEntity) e, overwritten);} else if (e instanceof GenericEntity) {GenericEntity genericEntity = (GenericEntity) e;- if (genericEntity.type() == Entity.EntityType.VIEW) {- ViewMetaService.getInstance().insertView(genericEntity, overwritten);- } else {- throw new UnsupportedEntityTypeException(- "Unsupported entity type: %s for insert operation", genericEntity.type());- }+ throw new UnsupportedEntityTypeException(+ "Unsupported entity type: %s for insert operation", genericEntity.type());} else {throw new UnsupportedEntityTypeException("Unsupported entity type: %s for insert operation", e.getClass());diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewMetaMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewMetaMapper.javaindex 6c53ca71ad..bbee800fcf 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewMetaMapper.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewMetaMapper.java@@ -21,26 +21,69 @@ package org.apache.gravitino.storage.relational.mapper;import java.util.List;import org.apache.gravitino.storage.relational.po.ViewPO;+import org.apache.gravitino.storage.relational.po.ViewVersionInfoPO;import org.apache.ibatis.annotations.DeleteProvider;import org.apache.ibatis.annotations.InsertProvider;+import org.apache.ibatis.annotations.One;import org.apache.ibatis.annotations.Param;+import org.apache.ibatis.annotations.Result;+import org.apache.ibatis.annotations.ResultMap;+import org.apache.ibatis.annotations.Results;+import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.SelectProvider;import org.apache.ibatis.annotations.UpdateProvider;-/**- * A MyBatis Mapper for view meta operation SQLs.- *- * <p>This interface class is a specification defined by MyBatis. It requires this interface class- * to identify the corresponding SQLs for execution. We can write SQLs in an additional XML file, or- * write SQLs with annotations in this interface Mapper. See: <a- * href="https://mybatis.org/mybatis-3/getting-started.html"></a>- */+/** A MyBatis Mapper for view meta operation SQLs. */public interface ViewMetaMapper {String TABLE_NAME = "view_meta";-+ String VERSION_TABLE_NAME = "view_version_info";++ @Results(+ id = "mapToViewVersionInfoPO",+ value = {+ @Result(property = "id", column = "id", id = true),+ @Result(property = "metalakeId", column = "version_metalake_id"),+ @Result(property = "catalogId", column = "version_catalog_id"),+ @Result(property = "schemaId", column = "version_schema_id"),+ @Result(property = "viewId", column = "version_view_id"),+ @Result(property = "version", column = "version"),+ @Result(property = "viewComment", column = "view_comment"),+ @Result(property = "columns", column = "columns"),+ @Result(property = "properties", column = "properties"),+ @Result(property = "defaultCatalog", column = "default_catalog"),+ @Result(property = "defaultSchema", column = "default_schema"),+ @Result(property = "representations", column = "representations"),+ @Result(property = "auditInfo", column = "version_audit_info"),+ @Result(property = "deletedAt", column = "version_deleted_at")+ })+ @Select("SELECT 1") // Dummy SQL to avoid MyBatis error, never be executed+ ViewVersionInfoPO mapToViewVersionInfoPO();++ @Results(+ id = "viewPOResultMap",+ value = {+ @Result(property = "viewId", column = "view_id", id = true),+ @Result(property = "viewName", column = "view_name"),+ @Result(property = "metalakeId", column = "metalake_id"),+ @Result(property = "catalogId", column = "catalog_id"),+ @Result(property = "schemaId", column = "schema_id"),+ @Result(property = "currentVersion", column = "current_version"),+ @Result(property = "lastVersion", column = "last_version"),+ @Result(property = "auditInfo", column = "audit_info"),+ @Result(property = "deletedAt", column = "deleted_at"),+ @Result(+ property = "viewVersionInfoPO",+ javaType = ViewVersionInfoPO.class,+ column =+ "{id,version_metalake_id,version_catalog_id,version_schema_id,version_view_id,"+ + "version,view_comment,columns,properties,default_catalog,default_schema,"+ + "representations,version_audit_info,version_deleted_at}",+ one = @One(resultMap = "mapToViewVersionInfoPO"))+ })@SelectProvider(type = ViewMetaSQLProviderFactory.class, method = "listViewPOsBySchemaId")List<ViewPO> listViewPOsBySchemaId(@Param("schemaId") Long schemaId);+ @ResultMap("viewPOResultMap")@SelectProvider(type = ViewMetaSQLProviderFactory.class,method = "listViewPOsByFullQualifiedName")@@ -53,15 +96,18 @@ public interface ViewMetaMapper {Long selectViewIdBySchemaIdAndName(@Param("schemaId") Long schemaId, @Param("viewName") String name);+ @ResultMap("viewPOResultMap")@SelectProvider(type = ViewMetaSQLProviderFactory.class, method = "listViewPOsByViewIds")List<ViewPO> listViewPOsByViewIds(@Param("viewIds") List<Long> viewIds);+ @ResultMap("viewPOResultMap")@SelectProvider(type = ViewMetaSQLProviderFactory.class,method = "selectViewMetaBySchemaIdAndName")ViewPO selectViewMetaBySchemaIdAndName(@Param("schemaId") Long schemaId, @Param("viewName") String name);+ @ResultMap("viewPOResultMap")@SelectProvider(type = ViewMetaSQLProviderFactory.class, method = "selectViewByFullQualifiedName")ViewPO selectViewByFullQualifiedName(@Param("metalakeName") String metalakeName,diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewVersionInfoMapper.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewVersionInfoMapper.javanew file mode 100644index 0000000000..65cf74e83a--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewVersionInfoMapper.java@@ -0,0 +1,73 @@+/*+ * 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;++import org.apache.gravitino.storage.relational.po.ViewVersionInfoPO;+import org.apache.ibatis.annotations.DeleteProvider;+import org.apache.ibatis.annotations.InsertProvider;+import org.apache.ibatis.annotations.Param;+import org.apache.ibatis.annotations.SelectProvider;+import org.apache.ibatis.annotations.UpdateProvider;++/** A MyBatis Mapper for view version info operation SQLs. */+public interface ViewVersionInfoMapper {++ String TABLE_NAME = "view_version_info";++ @InsertProvider(type = ViewVersionInfoSQLProviderFactory.class, method = "insertViewVersionInfo")+ void insertViewVersionInfo(@Param("viewVersionInfo") ViewVersionInfoPO viewVersionInfoPO);++ @InsertProvider(+ type = ViewVersionInfoSQLProviderFactory.class,+ method = "insertViewVersionInfoOnDuplicateKeyUpdate")+ void insertViewVersionInfoOnDuplicateKeyUpdate(+ @Param("viewVersionInfo") ViewVersionInfoPO viewVersionInfoPO);++ @SelectProvider(+ type = ViewVersionInfoSQLProviderFactory.class,+ method = "selectViewVersionInfoByViewIdAndVersion")+ ViewVersionInfoPO selectViewVersionInfoByViewIdAndVersion(+ @Param("viewId") Long viewId, @Param("version") Integer version);++ @UpdateProvider(+ type = ViewVersionInfoSQLProviderFactory.class,+ method = "softDeleteViewVersionsByViewId")+ Integer softDeleteViewVersionsByViewId(@Param("viewId") Long viewId);++ @UpdateProvider(+ type = ViewVersionInfoSQLProviderFactory.class,+ method = "softDeleteViewVersionsBySchemaId")+ Integer softDeleteViewVersionsBySchemaId(@Param("schemaId") Long schemaId);++ @UpdateProvider(+ type = ViewVersionInfoSQLProviderFactory.class,+ method = "softDeleteViewVersionsByCatalogId")+ Integer softDeleteViewVersionsByCatalogId(@Param("catalogId") Long catalogId);++ @UpdateProvider(+ type = ViewVersionInfoSQLProviderFactory.class,+ method = "softDeleteViewVersionsByMetalakeId")+ Integer softDeleteViewVersionsByMetalakeId(@Param("metalakeId") Long metalakeId);++ @DeleteProvider(+ type = ViewVersionInfoSQLProviderFactory.class,+ method = "deleteViewVersionsByLegacyTimeline")+ Integer deleteViewVersionsByLegacyTimeline(+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit);+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewVersionInfoSQLProviderFactory.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewVersionInfoSQLProviderFactory.javanew file mode 100644index 0000000000..e04d0237d3--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/ViewVersionInfoSQLProviderFactory.java@@ -0,0 +1,89 @@+/*+ * 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;++import com.google.common.collect.ImmutableMap;+import java.util.Map;+import org.apache.gravitino.storage.relational.JDBCBackend.JDBCBackendType;+import org.apache.gravitino.storage.relational.mapper.provider.base.ViewVersionInfoBaseSQLProvider;+import org.apache.gravitino.storage.relational.mapper.provider.postgresql.ViewVersionInfoPostgreSQLProvider;+import org.apache.gravitino.storage.relational.po.ViewVersionInfoPO;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.ibatis.annotations.Param;++public class ViewVersionInfoSQLProviderFactory {++ static class ViewVersionInfoMySQLProvider extends ViewVersionInfoBaseSQLProvider {}++ static class ViewVersionInfoH2Provider extends ViewVersionInfoBaseSQLProvider {}++ private static final Map<JDBCBackendType, ViewVersionInfoBaseSQLProvider>+ VIEW_VERSION_INFO_SQL_PROVIDER_MAP =+ ImmutableMap.of(+ JDBCBackendType.MYSQL, new ViewVersionInfoMySQLProvider(),+ JDBCBackendType.H2, new ViewVersionInfoH2Provider(),+ JDBCBackendType.POSTGRESQL, new ViewVersionInfoPostgreSQLProvider());++ public static ViewVersionInfoBaseSQLProvider getProvider() {+ String databaseId =+ SqlSessionFactoryHelper.getInstance()+ .getSqlSessionFactory()+ .getConfiguration()+ .getDatabaseId();++ JDBCBackendType jdbcBackendType = JDBCBackendType.fromString(databaseId);+ return VIEW_VERSION_INFO_SQL_PROVIDER_MAP.get(jdbcBackendType);+ }++ public static String insertViewVersionInfo(+ @Param("viewVersionInfo") ViewVersionInfoPO viewVersionInfoPO) {+ return getProvider().insertViewVersionInfo(viewVersionInfoPO);+ }++ public static String insertViewVersionInfoOnDuplicateKeyUpdate(+ @Param("viewVersionInfo") ViewVersionInfoPO viewVersionInfoPO) {+ return getProvider().insertViewVersionInfoOnDuplicateKeyUpdate(viewVersionInfoPO);+ }++ public static String selectViewVersionInfoByViewIdAndVersion(+ @Param("viewId") Long viewId, @Param("version") Integer version) {+ return getProvider().selectViewVersionInfoByViewIdAndVersion(viewId, version);+ }++ public static String softDeleteViewVersionsByViewId(@Param("viewId") Long viewId) {+ return getProvider().softDeleteViewVersionsByViewId(viewId);+ }++ public static String softDeleteViewVersionsBySchemaId(@Param("schemaId") Long schemaId) {+ return getProvider().softDeleteViewVersionsBySchemaId(schemaId);+ }++ public static String softDeleteViewVersionsByCatalogId(@Param("catalogId") Long catalogId) {+ return getProvider().softDeleteViewVersionsByCatalogId(catalogId);+ }++ public static String softDeleteViewVersionsByMetalakeId(@Param("metalakeId") Long metalakeId) {+ return getProvider().softDeleteViewVersionsByMetalakeId(metalakeId);+ }++ public static String deleteViewVersionsByLegacyTimeline(+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {+ return getProvider().deleteViewVersionsByLegacyTimeline(legacyTimeline, limit);+ }+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.javaindex 58f99dd93d..394da706de 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/DefaultMapperPackageProvider.java@@ -50,6 +50,7 @@ import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;import org.apache.gravitino.storage.relational.mapper.UserMetaMapper;import org.apache.gravitino.storage.relational.mapper.UserRoleRelMapper;import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;+import org.apache.gravitino.storage.relational.mapper.ViewVersionInfoMapper;/** The default provider that supplies the primary mapper package for Gravitino. */public class DefaultMapperPackageProvider implements MapperPackageProvider {@@ -86,6 +87,7 @@ public class DefaultMapperPackageProvider implements MapperPackageProvider {UserMetaMapper.class,UserRoleRelMapper.class,TableVersionMapper.class,- ViewMetaMapper.class);+ ViewMetaMapper.class,+ ViewVersionInfoMapper.class);}}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewMetaBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewMetaBaseSQLProvider.javaindex ca7efd6a79..9a3ac0f72d 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewMetaBaseSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewMetaBaseSQLProvider.java@@ -19,6 +19,7 @@package org.apache.gravitino.storage.relational.mapper.provider.base;import static org.apache.gravitino.storage.relational.mapper.ViewMetaMapper.TABLE_NAME;+import static org.apache.gravitino.storage.relational.mapper.ViewMetaMapper.VERSION_TABLE_NAME;import java.util.List;import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;@@ -30,14 +31,19 @@ import org.apache.ibatis.annotations.Param;public class ViewMetaBaseSQLProvider {public String listViewPOsBySchemaId(@Param("schemaId") Long schemaId) {- return "SELECT view_id as viewId, view_name as viewName,"- + " metalake_id as metalakeId, catalog_id as catalogId,"- + " schema_id as schemaId,"- + " current_version as currentVersion, last_version as lastVersion,"- + " deleted_at as deletedAt"+ return "SELECT vm.view_id, vm.view_name, vm.metalake_id, vm.catalog_id, vm.schema_id,"+ + " vm.current_version, vm.last_version, vm.audit_info, vm.deleted_at,"+ + " vi.id, vi.metalake_id as version_metalake_id, vi.catalog_id as version_catalog_id,"+ + " vi.schema_id as version_schema_id, vi.view_id as version_view_id,"+ + " vi.version, vi.view_comment, vi.columns, vi.properties,"+ + " vi.default_catalog, vi.default_schema, vi.representations,"+ + " vi.audit_info as version_audit_info, vi.deleted_at as version_deleted_at"+ " FROM "+ TABLE_NAME- + " WHERE schema_id = #{schemaId} AND deleted_at = 0";+ + " vm INNER JOIN "+ + VERSION_TABLE_NAME+ + " vi ON vm.view_id = vi.view_id AND vm.current_version = vi.version"+ + " WHERE vm.schema_id = #{schemaId} AND vm.deleted_at = 0 AND vi.deleted_at = 0";}public String listViewPOsByFullQualifiedName(@@ -46,14 +52,29 @@ public class ViewMetaBaseSQLProvider {@Param("schemaName") String schemaName) {return """SELECT- sm.schema_id AS schemaId,- cm.catalog_id AS catalogId,- vm.view_id AS viewId,- vm.view_name AS viewName,- vm.metalake_id AS metalakeId,- vm.current_version AS currentVersion,- vm.last_version AS lastVersion,- vm.deleted_at AS deletedAt+ mm.metalake_id,+ cm.catalog_id,+ sm.schema_id,+ vm.view_id,+ vm.view_name,+ vm.current_version,+ vm.last_version,+ vm.audit_info,+ vm.deleted_at,+ vi.id,+ vi.metalake_id as version_metalake_id,+ vi.catalog_id as version_catalog_id,+ vi.schema_id as version_schema_id,+ vi.view_id as version_view_id,+ vi.version,+ vi.view_comment,+ vi.columns,+ vi.properties,+ vi.default_catalog,+ vi.default_schema,+ vi.representations,+ vi.audit_info as version_audit_info,+ vi.deleted_at as version_deleted_atFROM%s mmINNER JOIN@@ -67,15 +88,20 @@ public class ViewMetaBaseSQLProvider {LEFT JOIN%s vm ON sm.schema_id = vm.schema_idAND vm.deleted_at = 0+ LEFT JOIN+ %s vi ON vm.view_id = vi.view_id+ AND vm.current_version = vi.version+ AND vi.deleted_at = 0WHEREmm.metalake_name = #{metalakeName}- AND mm.deleted_at = 0;- """+ AND mm.deleted_at = 0+ """.formatted(MetalakeMetaMapper.TABLE_NAME,CatalogMetaMapper.TABLE_NAME,SchemaMetaMapper.TABLE_NAME,- TABLE_NAME);+ TABLE_NAME,+ VERSION_TABLE_NAME);}public String selectViewIdBySchemaIdAndName(@@ -88,14 +114,20 @@ public class ViewMetaBaseSQLProvider {public String selectViewMetaBySchemaIdAndName(@Param("schemaId") Long schemaId, @Param("viewName") String name) {- return "SELECT view_id as viewId, view_name as viewName,"- + " metalake_id as metalakeId, catalog_id as catalogId,"- + " schema_id as schemaId,"- + " current_version as currentVersion, last_version as lastVersion,"- + " deleted_at as deletedAt"+ return "SELECT vm.view_id, vm.view_name, vm.metalake_id, vm.catalog_id, vm.schema_id,"+ + " vm.current_version, vm.last_version, vm.audit_info, vm.deleted_at,"+ + " vi.id, vi.metalake_id as version_metalake_id, vi.catalog_id as version_catalog_id,"+ + " vi.schema_id as version_schema_id, vi.view_id as version_view_id,"+ + " vi.version, vi.view_comment, vi.columns, vi.properties,"+ + " vi.default_catalog, vi.default_schema, vi.representations,"+ + " vi.audit_info as version_audit_info, vi.deleted_at as version_deleted_at"+ " FROM "+ TABLE_NAME- + " WHERE schema_id = #{schemaId} AND view_name = #{viewName} AND deleted_at = 0";+ + " vm INNER JOIN "+ + VERSION_TABLE_NAME+ + " vi ON vm.view_id = vi.view_id AND vm.current_version = vi.version"+ + " WHERE vm.schema_id = #{schemaId} AND vm.view_name = #{viewName}"+ + " AND vm.deleted_at = 0 AND vi.deleted_at = 0";}public String insertViewMeta(@Param("viewMeta") ViewPO viewPO) {@@ -103,7 +135,7 @@ public class ViewMetaBaseSQLProvider {+ TABLE_NAME+ " (view_id, view_name, metalake_id,"+ " catalog_id, schema_id,"- + " current_version, last_version, deleted_at)"+ + " current_version, last_version, audit_info, deleted_at)"+ " VALUES ("+ " #{viewMeta.viewId},"+ " #{viewMeta.viewName},"@@ -112,6 +144,7 @@ public class ViewMetaBaseSQLProvider {+ " #{viewMeta.schemaId},"+ " #{viewMeta.currentVersion},"+ " #{viewMeta.lastVersion},"+ + " #{viewMeta.auditInfo},"+ " #{viewMeta.deletedAt}"+ " )";}@@ -121,7 +154,7 @@ public class ViewMetaBaseSQLProvider {+ TABLE_NAME+ " (view_id, view_name, metalake_id,"+ " catalog_id, schema_id,"- + " current_version, last_version, deleted_at)"+ + " current_version, last_version, audit_info, deleted_at)"+ " VALUES ("+ " #{viewMeta.viewId},"+ " #{viewMeta.viewName},"@@ -130,6 +163,7 @@ public class ViewMetaBaseSQLProvider {+ " #{viewMeta.schemaId},"+ " #{viewMeta.currentVersion},"+ " #{viewMeta.lastVersion},"+ + " #{viewMeta.auditInfo},"+ " #{viewMeta.deletedAt}"+ " )"+ " ON DUPLICATE KEY UPDATE"@@ -139,6 +173,7 @@ public class ViewMetaBaseSQLProvider {+ " schema_id = #{viewMeta.schemaId},"+ " current_version = #{viewMeta.currentVersion},"+ " last_version = #{viewMeta.lastVersion},"+ + " audit_info = #{viewMeta.auditInfo},"+ " deleted_at = #{viewMeta.deletedAt}";}@@ -150,6 +185,7 @@ public class ViewMetaBaseSQLProvider {+ " schema_id = #{newViewMeta.schemaId}, "+ " current_version = #{newViewMeta.currentVersion}, "+ " last_version = #{newViewMeta.lastVersion}, "+ + " audit_info = #{newViewMeta.auditInfo}, "+ " deleted_at = #{newViewMeta.deletedAt} "+ " WHERE view_id = #{oldViewMeta.viewId} "+ " AND current_version = #{oldViewMeta.currentVersion} "@@ -158,16 +194,23 @@ public class ViewMetaBaseSQLProvider {public String listViewPOsByViewIds(@Param("viewIds") List<Long> viewIds) {return "<script>"- + "SELECT view_id as viewId, view_name as viewName, "- + " metalake_id as metalakeId, catalog_id as catalogId, schema_id as schemaId, "- + " current_version as currentVersion, last_version as lastVersion, deleted_at as deletedAt "+ + "SELECT vm.view_id, vm.view_name, vm.metalake_id, vm.catalog_id, vm.schema_id,"+ + " vm.current_version, vm.last_version, vm.audit_info, vm.deleted_at,"+ + " vi.id, vi.metalake_id as version_metalake_id, vi.catalog_id as version_catalog_id,"+ + " vi.schema_id as version_schema_id, vi.view_id as version_view_id,"+ + " vi.version, vi.view_comment, vi.columns, vi.properties,"+ + " vi.default_catalog, vi.default_schema, vi.representations,"+ + " vi.audit_info as version_audit_info, vi.deleted_at as version_deleted_at"+ " FROM "+ TABLE_NAME- + " WHERE view_id IN "+ + " vm INNER JOIN "+ + VERSION_TABLE_NAME+ + " vi ON vm.view_id = vi.view_id AND vm.current_version = vi.version"+ + " WHERE vm.view_id IN "+ "<foreach item='viewId' index='index' collection='viewIds' open='(' separator=',' close=')'>"+ "#{viewId}"+ "</foreach>"- + " AND deleted_at = 0"+ + " AND vm.deleted_at = 0 AND vi.deleted_at = 0"+ "</script>";}@@ -217,14 +260,29 @@ public class ViewMetaBaseSQLProvider {@Param("viewName") String viewName) {return """SELECT- sm.schema_id AS schemaId,- cm.catalog_id AS catalogId,- vm.view_id AS viewId,- vm.view_name AS viewName,- vm.metalake_id AS metalakeId,- vm.current_version AS currentVersion,- vm.last_version AS lastVersion,- vm.deleted_at AS deletedAt+ mm.metalake_id,+ cm.catalog_id,+ sm.schema_id,+ vm.view_id,+ vm.view_name,+ vm.current_version,+ vm.last_version,+ vm.audit_info,+ vm.deleted_at,+ vi.id,+ vi.metalake_id as version_metalake_id,+ vi.catalog_id as version_catalog_id,+ vi.schema_id as version_schema_id,+ vi.view_id as version_view_id,+ vi.version,+ vi.view_comment,+ vi.columns,+ vi.properties,+ vi.default_catalog,+ vi.default_schema,+ vi.representations,+ vi.audit_info as version_audit_info,+ vi.deleted_at as version_deleted_atFROM%s mmINNER JOIN@@ -239,14 +297,19 @@ public class ViewMetaBaseSQLProvider {%s vm ON sm.schema_id = vm.schema_idAND vm.view_name = #{viewName}AND vm.deleted_at = 0+ LEFT JOIN+ %s vi ON vm.view_id = vi.view_id+ AND vm.current_version = vi.version+ AND vi.deleted_at = 0WHEREmm.metalake_name = #{metalakeName}- AND mm.deleted_at = 0;- """+ AND mm.deleted_at = 0+ """.formatted(MetalakeMetaMapper.TABLE_NAME,CatalogMetaMapper.TABLE_NAME,SchemaMetaMapper.TABLE_NAME,- TABLE_NAME);+ TABLE_NAME,+ VERSION_TABLE_NAME);}}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewVersionInfoBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewVersionInfoBaseSQLProvider.javanew file mode 100644index 0000000000..2e5bf81c91--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/ViewVersionInfoBaseSQLProvider.java@@ -0,0 +1,118 @@+/*+ * 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.base;++import org.apache.gravitino.storage.relational.mapper.ViewVersionInfoMapper;+import org.apache.gravitino.storage.relational.po.ViewVersionInfoPO;+import org.apache.ibatis.annotations.Param;++public class ViewVersionInfoBaseSQLProvider {++ public String insertViewVersionInfo(+ @Param("viewVersionInfo") ViewVersionInfoPO viewVersionInfoPO) {+ return "INSERT INTO "+ + ViewVersionInfoMapper.TABLE_NAME+ + " (metalake_id, catalog_id, schema_id, view_id, version,"+ + " view_comment, columns, properties, default_catalog, default_schema, representations,"+ + " audit_info, deleted_at)"+ + " VALUES (#{viewVersionInfo.metalakeId}, #{viewVersionInfo.catalogId},"+ + " #{viewVersionInfo.schemaId}, #{viewVersionInfo.viewId},"+ + " #{viewVersionInfo.version}, #{viewVersionInfo.viewComment},"+ + " #{viewVersionInfo.columns}, #{viewVersionInfo.properties},"+ + " #{viewVersionInfo.defaultCatalog}, #{viewVersionInfo.defaultSchema},"+ + " #{viewVersionInfo.representations},"+ + " #{viewVersionInfo.auditInfo}, #{viewVersionInfo.deletedAt})";+ }++ public String insertViewVersionInfoOnDuplicateKeyUpdate(+ @Param("viewVersionInfo") ViewVersionInfoPO viewVersionInfoPO) {+ return "INSERT INTO "+ + ViewVersionInfoMapper.TABLE_NAME+ + " (metalake_id, catalog_id, schema_id, view_id, version,"+ + " view_comment, columns, properties, default_catalog, default_schema, representations,"+ + " audit_info, deleted_at)"+ + " VALUES (#{viewVersionInfo.metalakeId}, #{viewVersionInfo.catalogId},"+ + " #{viewVersionInfo.schemaId}, #{viewVersionInfo.viewId},"+ + " #{viewVersionInfo.version}, #{viewVersionInfo.viewComment},"+ + " #{viewVersionInfo.columns}, #{viewVersionInfo.properties},"+ + " #{viewVersionInfo.defaultCatalog}, #{viewVersionInfo.defaultSchema},"+ + " #{viewVersionInfo.representations},"+ + " #{viewVersionInfo.auditInfo}, #{viewVersionInfo.deletedAt})"+ + " ON DUPLICATE KEY UPDATE"+ + " view_comment = #{viewVersionInfo.viewComment},"+ + " columns = #{viewVersionInfo.columns},"+ + " properties = #{viewVersionInfo.properties},"+ + " default_catalog = #{viewVersionInfo.defaultCatalog},"+ + " default_schema = #{viewVersionInfo.defaultSchema},"+ + " representations = #{viewVersionInfo.representations},"+ + " audit_info = #{viewVersionInfo.auditInfo},"+ + " deleted_at = #{viewVersionInfo.deletedAt}";+ }++ public String selectViewVersionInfoByViewIdAndVersion(+ @Param("viewId") Long viewId, @Param("version") Integer version) {+ return "SELECT id as id, metalake_id as metalakeId, catalog_id as catalogId,"+ + " schema_id as schemaId, view_id as viewId, version as version,"+ + " view_comment as viewComment, columns as columns, properties as properties,"+ + " default_catalog as defaultCatalog, default_schema as defaultSchema,"+ + " representations as representations,"+ + " audit_info as auditInfo, deleted_at as deletedAt FROM "+ + ViewVersionInfoMapper.TABLE_NAME+ + " WHERE view_id = #{viewId} AND version = #{version} AND deleted_at = 0";+ }++ public String softDeleteViewVersionsByViewId(@Param("viewId") Long viewId) {+ return "UPDATE "+ + ViewVersionInfoMapper.TABLE_NAME+ + " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"+ + " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"+ + " WHERE view_id = #{viewId} AND deleted_at = 0";+ }++ public String softDeleteViewVersionsBySchemaId(@Param("schemaId") Long schemaId) {+ return "UPDATE "+ + ViewVersionInfoMapper.TABLE_NAME+ + " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"+ + " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"+ + " WHERE schema_id = #{schemaId} AND deleted_at = 0";+ }++ public String softDeleteViewVersionsByCatalogId(@Param("catalogId") Long catalogId) {+ return "UPDATE "+ + ViewVersionInfoMapper.TABLE_NAME+ + " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"+ + " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"+ + " WHERE catalog_id = #{catalogId} AND deleted_at = 0";+ }++ public String softDeleteViewVersionsByMetalakeId(@Param("metalakeId") Long metalakeId) {+ return "UPDATE "+ + ViewVersionInfoMapper.TABLE_NAME+ + " SET deleted_at = (UNIX_TIMESTAMP() * 1000.0)"+ + " + EXTRACT(MICROSECOND FROM CURRENT_TIMESTAMP(3)) / 1000"+ + " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";+ }++ public String deleteViewVersionsByLegacyTimeline(+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {+ return "DELETE FROM "+ + ViewVersionInfoMapper.TABLE_NAME+ + " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit}";+ }+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewMetaPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewMetaPostgreSQLProvider.javaindex 6e92b6739c..ddf09ca5a1 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewMetaPostgreSQLProvider.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewMetaPostgreSQLProvider.java@@ -19,6 +19,7 @@package org.apache.gravitino.storage.relational.mapper.provider.postgresql;import static org.apache.gravitino.storage.relational.mapper.ViewMetaMapper.TABLE_NAME;+import static org.apache.gravitino.storage.relational.mapper.ViewMetaMapper.VERSION_TABLE_NAME;import org.apache.gravitino.storage.relational.mapper.provider.base.ViewMetaBaseSQLProvider;import org.apache.gravitino.storage.relational.po.ViewPO;@@ -32,7 +33,7 @@ public class ViewMetaPostgreSQLProvider extends ViewMetaBaseSQLProvider {+ TABLE_NAME+ " (view_id, view_name, metalake_id,"+ " catalog_id, schema_id,"- + " current_version, last_version, deleted_at)"+ + " current_version, last_version, audit_info, deleted_at)"+ " VALUES ("+ " #{viewMeta.viewId},"+ " #{viewMeta.viewName},"@@ -41,6 +42,7 @@ public class ViewMetaPostgreSQLProvider extends ViewMetaBaseSQLProvider {+ " #{viewMeta.schemaId},"+ " #{viewMeta.currentVersion},"+ " #{viewMeta.lastVersion},"+ + " #{viewMeta.auditInfo},"+ " #{viewMeta.deletedAt}"+ " )"+ " ON CONFLICT (view_id) DO UPDATE SET"@@ -50,9 +52,46 @@ public class ViewMetaPostgreSQLProvider extends ViewMetaBaseSQLProvider {+ " schema_id = #{viewMeta.schemaId},"+ " current_version = #{viewMeta.currentVersion},"+ " last_version = #{viewMeta.lastVersion},"+ + " audit_info = #{viewMeta.auditInfo},"+ " deleted_at = #{viewMeta.deletedAt}";}+ @Override+ public String listViewPOsBySchemaId(@Param("schemaId") Long schemaId) {+ return "SELECT vm.view_id, vm.view_name, vm.metalake_id, vm.catalog_id, vm.schema_id,"+ + " vm.current_version, vm.last_version, vm.audit_info, vm.deleted_at,"+ + " vi.id, vi.metalake_id as version_metalake_id, vi.catalog_id as version_catalog_id,"+ + " vi.schema_id as version_schema_id, vi.view_id as version_view_id,"+ + " vi.version, vi.view_comment, vi.columns, vi.properties,"+ + " vi.default_catalog, vi.default_schema, vi.representations,"+ + " vi.audit_info as version_audit_info, vi.deleted_at as version_deleted_at"+ + " FROM "+ + TABLE_NAME+ + " vm INNER JOIN "+ + VERSION_TABLE_NAME+ + " vi ON vm.view_id = vi.view_id AND vm.current_version = vi.version"+ + " WHERE vm.schema_id = #{schemaId} AND vm.deleted_at = 0 AND vi.deleted_at = 0";+ }++ @Override+ public String selectViewMetaBySchemaIdAndName(+ @Param("schemaId") Long schemaId, @Param("viewName") String name) {+ return "SELECT vm.view_id, vm.view_name, vm.metalake_id, vm.catalog_id, vm.schema_id,"+ + " vm.current_version, vm.last_version, vm.audit_info, vm.deleted_at,"+ + " vi.id, vi.metalake_id as version_metalake_id, vi.catalog_id as version_catalog_id,"+ + " vi.schema_id as version_schema_id, vi.view_id as version_view_id,"+ + " vi.version, vi.view_comment, vi.columns, vi.properties,"+ + " vi.default_catalog, vi.default_schema, vi.representations,"+ + " vi.audit_info as version_audit_info, vi.deleted_at as version_deleted_at"+ + " FROM "+ + TABLE_NAME+ + " vm INNER JOIN "+ + VERSION_TABLE_NAME+ + " vi ON vm.view_id = vi.view_id AND vm.current_version = vi.version"+ + " WHERE vm.schema_id = #{schemaId} AND vm.view_name = #{viewName}"+ + " AND vm.deleted_at = 0 AND vi.deleted_at = 0";+ }+@Overridepublic String softDeleteViewMetasByViewId(@Param("viewId") Long viewId) {return "UPDATE "diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewVersionInfoPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewVersionInfoPostgreSQLProvider.javanew file mode 100644index 0000000000..ae2a5834a2--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/ViewVersionInfoPostgreSQLProvider.java@@ -0,0 +1,95 @@+/*+ * 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.ViewVersionInfoMapper;+import org.apache.gravitino.storage.relational.mapper.provider.base.ViewVersionInfoBaseSQLProvider;+import org.apache.gravitino.storage.relational.po.ViewVersionInfoPO;+import org.apache.ibatis.annotations.Param;++public class ViewVersionInfoPostgreSQLProvider extends ViewVersionInfoBaseSQLProvider {++ @Override+ public String insertViewVersionInfoOnDuplicateKeyUpdate(+ @Param("viewVersionInfo") ViewVersionInfoPO viewVersionInfoPO) {+ return "INSERT INTO "+ + ViewVersionInfoMapper.TABLE_NAME+ + " (metalake_id, catalog_id, schema_id, view_id, version,"+ + " view_comment, columns, properties, default_catalog, default_schema, representations,"+ + " audit_info, deleted_at)"+ + " VALUES (#{viewVersionInfo.metalakeId}, #{viewVersionInfo.catalogId},"+ + " #{viewVersionInfo.schemaId}, #{viewVersionInfo.viewId},"+ + " #{viewVersionInfo.version}, #{viewVersionInfo.viewComment},"+ + " #{viewVersionInfo.columns}, #{viewVersionInfo.properties},"+ + " #{viewVersionInfo.defaultCatalog}, #{viewVersionInfo.defaultSchema},"+ + " #{viewVersionInfo.representations},"+ + " #{viewVersionInfo.auditInfo}, #{viewVersionInfo.deletedAt})"+ + " ON CONFLICT (view_id, version, deleted_at) DO UPDATE SET"+ + " view_comment = #{viewVersionInfo.viewComment},"+ + " columns = #{viewVersionInfo.columns},"+ + " properties = #{viewVersionInfo.properties},"+ + " default_catalog = #{viewVersionInfo.defaultCatalog},"+ + " default_schema = #{viewVersionInfo.defaultSchema},"+ + " representations = #{viewVersionInfo.representations},"+ + " audit_info = #{viewVersionInfo.auditInfo},"+ + " deleted_at = #{viewVersionInfo.deletedAt}";+ }++ @Override+ public String softDeleteViewVersionsByViewId(@Param("viewId") Long viewId) {+ return "UPDATE "+ + ViewVersionInfoMapper.TABLE_NAME+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ + " WHERE view_id = #{viewId} AND deleted_at = 0";+ }++ @Override+ public String softDeleteViewVersionsBySchemaId(@Param("schemaId") Long schemaId) {+ return "UPDATE "+ + ViewVersionInfoMapper.TABLE_NAME+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ + " WHERE schema_id = #{schemaId} AND deleted_at = 0";+ }++ @Override+ public String softDeleteViewVersionsByCatalogId(@Param("catalogId") Long catalogId) {+ return "UPDATE "+ + ViewVersionInfoMapper.TABLE_NAME+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ + " WHERE catalog_id = #{catalogId} AND deleted_at = 0";+ }++ @Override+ public String softDeleteViewVersionsByMetalakeId(@Param("metalakeId") Long metalakeId) {+ return "UPDATE "+ + ViewVersionInfoMapper.TABLE_NAME+ + " SET deleted_at = CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) * 1000 AS BIGINT)"+ + " WHERE metalake_id = #{metalakeId} AND deleted_at = 0";+ }++ @Override+ public String deleteViewVersionsByLegacyTimeline(+ @Param("legacyTimeline") Long legacyTimeline, @Param("limit") int limit) {+ return "DELETE FROM "+ + ViewVersionInfoMapper.TABLE_NAME+ + " WHERE id IN (SELECT id FROM "+ + ViewVersionInfoMapper.TABLE_NAME+ + " WHERE deleted_at > 0 AND deleted_at < #{legacyTimeline} LIMIT #{limit})";+ }+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/ViewPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/ViewPO.javaindex d58f609bda..aff8d39769 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/po/ViewPO.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/ViewPO.java@@ -18,94 +18,223 @@*/package org.apache.gravitino.storage.relational.po;+import static org.apache.gravitino.storage.relational.utils.POConverters.DEFAULT_DELETED_AT;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.type.CollectionType;import com.google.common.base.Preconditions;+import java.util.Arrays;+import java.util.Collections;+import java.util.List;+import java.util.Map;+import java.util.stream.Collectors;import lombok.EqualsAndHashCode;import lombok.Getter;import lombok.ToString;+import org.apache.gravitino.Entity;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.dto.rel.ColumnDTO;+import org.apache.gravitino.dto.rel.RepresentationDTO;+import org.apache.gravitino.json.JsonUtils;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.NamespacedEntityId;+import org.apache.gravitino.meta.ViewEntity;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.storage.relational.service.EntityIdService;@Getter-@EqualsAndHashCode+@EqualsAndHashCode(exclude = "viewVersionInfoPO")@ToStringpublic class ViewPO {++ public static final Long INITIAL_VERSION = 1L;+private Long viewId;private String viewName;private Long metalakeId;private Long catalogId;private Long schemaId;+ private String auditInfo;private Long currentVersion;private Long lastVersion;private Long deletedAt;+ private ViewVersionInfoPO viewVersionInfoPO;- public static class Builder {- private final ViewPO viewPO;+ public ViewPO() {}- private Builder() {- viewPO = new ViewPO();- }+ public static class ViewPOBuilder {+ // Lombok will generate builder methods.+ }- public Builder withViewId(Long viewId) {- viewPO.viewId = viewId;- return this;- }+ @lombok.Builder(setterPrefix = "with")+ private ViewPO(+ Long viewId,+ String viewName,+ Long metalakeId,+ Long catalogId,+ Long schemaId,+ String auditInfo,+ Long currentVersion,+ Long lastVersion,+ Long deletedAt,+ ViewVersionInfoPO viewVersionInfoPO) {+ Preconditions.checkArgument(viewId != null, "View id is required");+ Preconditions.checkArgument(viewName != null, "View name is required");+ Preconditions.checkArgument(metalakeId != null, "Metalake id is required");+ Preconditions.checkArgument(catalogId != null, "Catalog id is required");+ Preconditions.checkArgument(schemaId != null, "Schema id is required");+ Preconditions.checkArgument(auditInfo != null, "Audit info is required");+ Preconditions.checkArgument(currentVersion != null, "Current version is required");+ Preconditions.checkArgument(lastVersion != null, "Last version is required");+ Preconditions.checkArgument(deletedAt != null, "Deleted at is required");- public Builder withViewName(String viewName) {- viewPO.viewName = viewName;- return this;- }+ this.viewId = viewId;+ this.viewName = viewName;+ this.metalakeId = metalakeId;+ this.catalogId = catalogId;+ this.schemaId = schemaId;+ this.auditInfo = auditInfo;+ this.currentVersion = currentVersion;+ this.lastVersion = lastVersion;+ this.deletedAt = deletedAt;+ this.viewVersionInfoPO = viewVersionInfoPO;+ }- public Builder withMetalakeId(Long metalakeId) {- viewPO.metalakeId = metalakeId;- return this;- }+ // ============================ PO Converters ============================- public Builder withCatalogId(Long catalogId) {- viewPO.catalogId = catalogId;- return this;- }+ public static ViewEntity fromViewPO(ViewPO viewPO, Namespace namespace) {+ try {+ ViewVersionInfoPO versionPO = viewPO.getViewVersionInfoPO();+ List<ColumnDTO> columnDTOs =+ JsonUtils.anyFieldMapper()+ .readValue(+ versionPO.columns(),+ JsonUtils.anyFieldMapper()+ .getTypeFactory()+ .constructCollectionType(List.class, ColumnDTO.class));+ Column[] columns = columnDTOs.toArray(new Column[0]);- public Builder withSchemaId(Long schemaId) {- viewPO.schemaId = schemaId;- return this;- }+ Representation[] representations = deserializeRepresentations(versionPO.representations());- public Builder withCurrentVersion(Long currentVersion) {- viewPO.currentVersion = currentVersion;- return this;- }+ Map<String, String> properties =+ versionPO.properties() == null+ ? Collections.emptyMap()+ : JsonUtils.anyFieldMapper()+ .readValue(+ versionPO.properties(),+ JsonUtils.anyFieldMapper()+ .getTypeFactory()+ .constructMapType(Map.class, String.class, String.class));- public Builder withLastVersion(Long lastVersion) {- viewPO.lastVersion = lastVersion;- return this;+ return ViewEntity.builder()+ .withId(viewPO.getViewId())+ .withName(viewPO.getViewName())+ .withNamespace(namespace)+ .withComment(versionPO.viewComment())+ .withColumns(columns)+ .withRepresentations(representations)+ .withDefaultCatalog(versionPO.defaultCatalog())+ .withDefaultSchema(versionPO.defaultSchema())+ .withProperties(properties)+ .withAuditInfo(+ JsonUtils.anyFieldMapper().readValue(viewPO.getAuditInfo(), AuditInfo.class))+ .build();+ } catch (JsonProcessingException e) {+ throw new RuntimeException("Failed to deserialize json object:", e);}+ }- public Builder withDeletedAt(Long deletedAt) {- viewPO.deletedAt = deletedAt;- return this;- }+ public static ViewPO initializeViewPO(ViewEntity viewEntity, ViewPOBuilder builder) {+ builder.withCurrentVersion(INITIAL_VERSION).withLastVersion(INITIAL_VERSION);+ return buildViewPO(viewEntity, builder, INITIAL_VERSION.intValue());+ }- private void validate() {- Preconditions.checkArgument(viewPO.viewId != null, "View id is required");- Preconditions.checkArgument(viewPO.viewName != null, "View name is required");- Preconditions.checkArgument(viewPO.metalakeId != null, "Metalake id is required");- Preconditions.checkArgument(viewPO.catalogId != null, "Catalog id is required");- Preconditions.checkArgument(viewPO.schemaId != null, "Schema id is required");- Preconditions.checkArgument(viewPO.currentVersion != null, "Current version is required");- Preconditions.checkArgument(viewPO.lastVersion != null, "Last version is required");- Preconditions.checkArgument(viewPO.deletedAt != null, "Deleted at is required");+ public static ViewVersionInfoPO initializeViewVersionInfoPO(+ ViewEntity viewEntity, NamespacedEntityId namespacedEntityId, Integer version) {+ try {+ List<ColumnDTO> columnDTOs =+ Arrays.stream(viewEntity.columns() == null ? new Column[0] : viewEntity.columns())+ .map(ViewPO::toColumnDTO)+ .collect(Collectors.toList());+ String propertiesJson =+ viewEntity.properties() == null || viewEntity.properties().isEmpty()+ ? null+ : JsonUtils.anyFieldMapper().writeValueAsString(viewEntity.properties());++ return ViewVersionInfoPO.builder()+ .withViewId(viewEntity.id())+ .withMetalakeId(namespacedEntityId.namespaceIds()[0])+ .withCatalogId(namespacedEntityId.namespaceIds()[1])+ .withSchemaId(namespacedEntityId.entityId())+ .withVersion(version)+ .withViewComment(viewEntity.comment())+ .withColumns(JsonUtils.anyFieldMapper().writeValueAsString(columnDTOs))+ .withProperties(propertiesJson)+ .withDefaultCatalog(viewEntity.defaultCatalog())+ .withDefaultSchema(viewEntity.defaultSchema())+ .withRepresentations(serializeRepresentations(viewEntity.representations()))+ .withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(viewEntity.auditInfo()))+ .withDeletedAt(DEFAULT_DELETED_AT)+ .build();+ } catch (JsonProcessingException e) {+ throw new RuntimeException("Failed to serialize json object:", e);}+ }- public ViewPO build() {- validate();- return viewPO;+ public static ViewPO buildViewPO(ViewEntity viewEntity, ViewPOBuilder builder, Integer version) {+ try {+ NamespacedEntityId namespacedEntityId =+ EntityIdService.getEntityIds(+ NameIdentifier.of(viewEntity.namespace().levels()), Entity.EntityType.SCHEMA);+ ViewVersionInfoPO versionPO =+ initializeViewVersionInfoPO(viewEntity, namespacedEntityId, version);+ return builder+ .withViewId(viewEntity.id())+ .withViewName(viewEntity.name())+ .withMetalakeId(namespacedEntityId.namespaceIds()[0])+ .withCatalogId(namespacedEntityId.namespaceIds()[1])+ .withSchemaId(namespacedEntityId.entityId())+ .withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(viewEntity.auditInfo()))+ .withViewVersionInfoPO(versionPO)+ .withDeletedAt(DEFAULT_DELETED_AT)+ .build();+ } catch (JsonProcessingException e) {+ throw new RuntimeException("Failed to serialize json object:", e);}}- /**- * Creates a new instance of {@link Builder}.- *- * @return The new instance.- */- public static Builder builder() {- return new Builder();+ // ============================ Representation Serde ============================++ static String serializeRepresentations(Representation[] representations)+ throws JsonProcessingException {+ List<RepresentationDTO> out =+ Arrays.stream(representations == null ? new Representation[0] : representations)+ .map(RepresentationDTO::fromRepresentation)+ .collect(Collectors.toList());+ return JsonUtils.anyFieldMapper().writeValueAsString(out);+ }++ static Representation[] deserializeRepresentations(String json) throws JsonProcessingException {+ CollectionType type =+ JsonUtils.anyFieldMapper()+ .getTypeFactory()+ .constructCollectionType(List.class, RepresentationDTO.class);+ List<RepresentationDTO> list = JsonUtils.anyFieldMapper().readValue(json, type);+ return list.stream().map(RepresentationDTO::toRepresentation).toArray(Representation[]::new);+ }++ private static ColumnDTO toColumnDTO(Column column) {+ if (column instanceof ColumnDTO) {+ return (ColumnDTO) column;+ }+ return ColumnDTO.builder()+ .withName(column.name())+ .withDataType(column.dataType())+ .withComment(column.comment())+ .withNullable(column.nullable())+ .withAutoIncrement(column.autoIncrement())+ .build();}}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/ViewVersionInfoPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/ViewVersionInfoPO.javanew file mode 100644index 0000000000..8ab1183b63--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/ViewVersionInfoPO.java@@ -0,0 +1,106 @@+/*+ * 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.google.common.base.Preconditions;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;+import lombok.experimental.Accessors;+import org.apache.commons.lang3.StringUtils;++@EqualsAndHashCode+@Getter+@ToString+@Accessors(fluent = true)+public class ViewVersionInfoPO {++ private Long id;++ private Long metalakeId;++ private Long catalogId;++ private Long schemaId;++ private Long viewId;++ private Integer version;++ private String viewComment;++ private String columns;++ private String properties;++ private String defaultCatalog;++ private String defaultSchema;++ private String representations;++ private String auditInfo;++ private Long deletedAt;++ public ViewVersionInfoPO() {}++ @lombok.Builder(setterPrefix = "with")+ private ViewVersionInfoPO(+ Long id,+ Long metalakeId,+ Long catalogId,+ Long schemaId,+ Long viewId,+ Integer version,+ String viewComment,+ String columns,+ String properties,+ String defaultCatalog,+ String defaultSchema,+ String representations,+ String auditInfo,+ Long deletedAt) {+ Preconditions.checkArgument(metalakeId != null, "Metalake id is required");+ Preconditions.checkArgument(catalogId != null, "Catalog id is required");+ Preconditions.checkArgument(schemaId != null, "Schema id is required");+ Preconditions.checkArgument(viewId != null, "View id is required");+ Preconditions.checkArgument(version != null, "View version is required");+ Preconditions.checkArgument(StringUtils.isNotBlank(columns), "Columns cannot be empty");+ Preconditions.checkArgument(+ StringUtils.isNotBlank(representations), "Representations cannot be empty");+ Preconditions.checkArgument(StringUtils.isNotBlank(auditInfo), "Audit info cannot be empty");+ Preconditions.checkArgument(deletedAt != null, "Deleted at is required");++ this.id = id;+ this.metalakeId = metalakeId;+ this.catalogId = catalogId;+ this.schemaId = schemaId;+ this.viewId = viewId;+ this.version = version;+ this.viewComment = viewComment;+ this.columns = columns;+ this.properties = properties;+ this.defaultCatalog = defaultCatalog;+ this.defaultSchema = defaultSchema;+ this.representations = representations;+ this.auditInfo = auditInfo;+ this.deletedAt = deletedAt;+ }+}diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.javaindex 9784401aae..4bdce7b3e0 100644--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/ViewMetaService.java@@ -19,9 +19,14 @@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.ViewPO.buildViewPO;+import static org.apache.gravitino.storage.relational.po.ViewPO.fromViewPO;+import static org.apache.gravitino.storage.relational.po.ViewPO.initializeViewPO;+import com.google.common.base.Preconditions;import java.io.IOException;import java.util.List;+import java.util.Objects;import java.util.concurrent.atomic.AtomicInteger;import java.util.function.Function;import java.util.stream.Collectors;@@ -33,13 +38,13 @@ import org.apache.gravitino.MetadataObject;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;import org.apache.gravitino.exceptions.NoSuchEntityException;-import org.apache.gravitino.meta.GenericEntity;-import org.apache.gravitino.meta.NamespacedEntityId;+import org.apache.gravitino.meta.ViewEntity;import org.apache.gravitino.metrics.Monitored;import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;+import org.apache.gravitino.storage.relational.mapper.ViewVersionInfoMapper;import org.apache.gravitino.storage.relational.po.ViewPO;import org.apache.gravitino.storage.relational.utils.ExceptionUtils;import org.apache.gravitino.storage.relational.utils.SessionUtils;@@ -48,6 +53,7 @@ import org.apache.gravitino.utils.NamespaceUtil;/** The service class for view metadata. It provides the basic database operations for view. */public class ViewMetaService {+private static final ViewMetaService INSTANCE = new ViewMetaService();public static ViewMetaService getInstance() {@@ -74,188 +80,127 @@ public class ViewMetaService {return viewId;}- @Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME, baseMetricName = "insertView")- public void insertView(ViewPO viewPO, boolean overwrite) throws IOException {- try {- SessionUtils.doWithCommit(- ViewMetaMapper.class,- mapper -> {- if (overwrite) {- mapper.insertViewMetaOnDuplicateKeyUpdate(viewPO);- } else {- mapper.insertViewMeta(viewPO);- }- });- } catch (RuntimeException re) {- ExceptionUtils.checkSQLException(re, Entity.EntityType.VIEW, viewPO.getViewName());- throw re;- }- }-- @Monitored(- metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,- baseMetricName = "deleteViewMetasByLegacyTimeline")- public int deleteViewMetasByLegacyTimeline(Long legacyTimeline, int limit) {- return SessionUtils.doWithCommitAndFetchResult(- ViewMetaMapper.class,- mapper -> mapper.deleteViewMetasByLegacyTimeline(legacyTimeline, limit));- }-- /**- * List views as GenericEntity by namespace.- *- * @param namespace The namespace to list views from.- * @return A list of GenericEntity representing views.- */@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,baseMetricName = "listViewsByNamespace")- public List<GenericEntity> listViewsByNamespace(Namespace namespace) {+ public List<ViewEntity> listViewsByNamespace(Namespace namespace) {NamespaceUtil.checkView(namespace);List<ViewPO> viewPOs = listViewPOsByNamespace(namespace);- return viewPOs.stream()- .map(- viewPO ->- GenericEntity.builder()- .withId(viewPO.getViewId())- .withName(viewPO.getViewName())- .withNamespace(namespace)- .withEntityType(Entity.EntityType.VIEW)- .build())- .collect(Collectors.toList());+ return viewPOs.stream().map(po -> fromViewPO(po, namespace)).collect(Collectors.toList());}- /**- * Get a view as GenericEntity by identifier.- *- * @param identifier The identifier of the view.- * @return The GenericEntity representing the view.- */@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,baseMetricName = "getViewByIdentifier")- public GenericEntity getViewByIdentifier(NameIdentifier identifier) {+ public ViewEntity getViewByIdentifier(NameIdentifier identifier) {NameIdentifierUtil.checkView(identifier);-ViewPO viewPO = viewPOFetcher().apply(identifier);-- return GenericEntity.builder()- .withId(viewPO.getViewId())- .withName(viewPO.getViewName())- .withNamespace(identifier.namespace())- .withEntityType(Entity.EntityType.VIEW)- .build();+ return fromViewPO(viewPO, identifier.namespace());}- /**- * Insert a view from GenericEntity.- *- * @param entity The GenericEntity representing the view.- * @param overwrite Whether to overwrite an existing view.- * @throws IOException If an I/O error occurs.- */- @Monitored(- metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,- baseMetricName = "insertViewFromEntity")- public void insertView(GenericEntity entity, boolean overwrite) throws IOException {- Namespace namespace = entity.namespace();- NamespaceUtil.checkView(namespace);+ @Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME, baseMetricName = "insertView")+ public void insertView(ViewEntity viewEntity, boolean overwrite) throws IOException {+ NameIdentifierUtil.checkView(viewEntity.nameIdentifier());- ViewPO.Builder builder = createViewPOBuilder(namespace);- ViewPO viewPO =- builder- .withViewId(entity.id())- .withViewName(entity.name())- .withCurrentVersion(1L)- .withLastVersion(1L)- .withDeletedAt(0L)- .build();-- insertView(viewPO, overwrite);+ ViewPO.ViewPOBuilder builder = ViewPO.builder();+ try {+ ViewPO po = initializeViewPO(viewEntity, builder);++ SessionUtils.doMultipleWithCommit(+ () ->+ SessionUtils.doWithoutCommit(+ ViewMetaMapper.class,+ mapper -> {+ if (overwrite) {+ mapper.insertViewMetaOnDuplicateKeyUpdate(po);+ } else {+ mapper.insertViewMeta(po);+ }+ }),+ () ->+ SessionUtils.doWithoutCommit(+ ViewVersionInfoMapper.class,+ mapper -> {+ if (overwrite) {+ mapper.insertViewVersionInfoOnDuplicateKeyUpdate(po.getViewVersionInfoPO());+ } else {+ mapper.insertViewVersionInfo(po.getViewVersionInfoPO());+ }+ }));+ } catch (RuntimeException re) {+ ExceptionUtils.checkSQLException(+ re, Entity.EntityType.VIEW, viewEntity.nameIdentifier().toString());+ throw re;+ }}- /**- * Update a view.- *- * @param ident The identifier of the view.- * @param updater The function to update the view entity.- * @return The updated GenericEntity.- * @throws IOException If an I/O error occurs.- */@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,baseMetricName = "updateViewByIdentifier")- public <E extends HasIdentifier> GenericEntity updateView(+ public <E extends Entity & HasIdentifier> ViewEntity updateView(NameIdentifier ident, Function<E, E> updater) throws IOException {NameIdentifierUtil.checkView(ident);ViewPO oldViewPO = viewPOFetcher().apply(ident);-- GenericEntity oldEntity =- GenericEntity.builder()- .withId(oldViewPO.getViewId())- .withName(oldViewPO.getViewName())- .withNamespace(ident.namespace())- .withEntityType(Entity.EntityType.VIEW)- .build();-- GenericEntity newEntity = (GenericEntity) updater.apply((E) oldEntity);-- // Check if the namespace (schema) has changed and resolve new schema ID if needed- boolean isSchemaChanged =- newEntity.namespace() != null && !newEntity.namespace().equals(ident.namespace());- Long schemaId =- isSchemaChanged- ? EntityIdService.getEntityId(- NameIdentifier.of(newEntity.namespace().levels()), Entity.EntityType.SCHEMA)- : oldViewPO.getSchemaId();-- ViewPO newViewPO =- ViewPO.builder()- .withViewId(oldViewPO.getViewId())- .withViewName(newEntity.name())- .withMetalakeId(oldViewPO.getMetalakeId())- .withCatalogId(oldViewPO.getCatalogId())- .withSchemaId(schemaId)- .withDeletedAt(oldViewPO.getDeletedAt())- .withLastVersion(oldViewPO.getLastVersion())- .withCurrentVersion(oldViewPO.getCurrentVersion())- .build();-- updateView(oldViewPO, newViewPO);-- return newEntity;+ ViewEntity oldViewEntity = fromViewPO(oldViewPO, ident.namespace());+ ViewEntity newEntity = (ViewEntity) updater.apply((E) oldViewEntity);+ Preconditions.checkArgument(+ Objects.equals(oldViewEntity.id(), newEntity.id()),+ "The updated view entity id: %s should be same with the entity id before: %s",+ newEntity.id(),+ oldViewEntity.id());++ AtomicInteger updateResult = new AtomicInteger(0);+ try {+ ViewPO newViewPO = updateViewPO(oldViewPO, newEntity);+ SessionUtils.doMultipleWithCommit(+ () ->+ SessionUtils.doWithoutCommit(+ ViewVersionInfoMapper.class,+ mapper -> mapper.insertViewVersionInfo(newViewPO.getViewVersionInfoPO())),+ () -> {+ updateResult.set(+ SessionUtils.getWithoutCommit(+ ViewMetaMapper.class, mapper -> mapper.updateViewMeta(newViewPO, oldViewPO)));+ if (updateResult.get() == 0) {+ throw new RuntimeException("Failed to update the entity: " + ident);+ }+ });+ return newEntity;+ } catch (RuntimeException re) {+ if (updateResult.get() == 0) {+ throw new IOException("Failed to update the entity: " + ident);+ }+ ExceptionUtils.checkSQLException(+ re, Entity.EntityType.VIEW, newEntity.nameIdentifier().toString());+ throw re;+ }}- /**- * Delete a view by identifier.- *- * @param ident The identifier of the view.- * @return true if the view was deleted, false otherwise.- */@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,baseMetricName = "deleteViewByIdentifier")public boolean deleteView(NameIdentifier ident) {NameIdentifierUtil.checkView(ident);-ViewPO viewPO = viewPOFetcher().apply(ident);return deleteView(viewPO.getViewId());}- private ViewPO getViewPOBySchemaIdAndName(Long schemaId, String viewName) {- ViewPO viewPO =- SessionUtils.getWithoutCommit(+ @Monitored(+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,+ baseMetricName = "deleteViewMetasByLegacyTimeline")+ public int deleteViewMetasByLegacyTimeline(Long legacyTimeline, int limit) {+ int versionDeletedCount =+ SessionUtils.doWithCommitAndFetchResult(+ ViewVersionInfoMapper.class,+ mapper -> mapper.deleteViewVersionsByLegacyTimeline(legacyTimeline, limit));++ int metaDeletedCount =+ SessionUtils.doWithCommitAndFetchResult(ViewMetaMapper.class,- mapper -> mapper.selectViewMetaBySchemaIdAndName(schemaId, viewName));+ mapper -> mapper.deleteViewMetasByLegacyTimeline(legacyTimeline, limit));- if (viewPO == null) {- throw new NoSuchEntityException(- NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,- Entity.EntityType.VIEW.name().toLowerCase(),- viewName);- }- return viewPO;+ return versionDeletedCount + metaDeletedCount;}private boolean deleteView(Long viewId) {@@ -267,6 +212,9 @@ public class ViewMetaService {ViewMetaMapper.class, mapper -> mapper.softDeleteViewMetasByViewId(viewId))),() -> {if (deleteResult.get() > 0) {+ SessionUtils.doWithoutCommit(+ ViewVersionInfoMapper.class,+ mapper -> mapper.softDeleteViewVersionsByViewId(viewId));SessionUtils.doWithoutCommit(OwnerMetaMapper.class,mapper ->@@ -287,34 +235,16 @@ public class ViewMetaService {return deleteResult.get() > 0;}- private void updateView(ViewPO oldViewPO, ViewPO newViewPO) throws IOException {- try {- Integer updateResult =- SessionUtils.doWithCommitAndFetchResult(- ViewMetaMapper.class, mapper -> mapper.updateViewMeta(newViewPO, oldViewPO));- if (updateResult == 0) {- throw new IOException("Failed to update the view: " + oldViewPO.getViewName());- }- } catch (RuntimeException re) {- ExceptionUtils.checkSQLException(re, Entity.EntityType.VIEW, newViewPO.getViewName());- throw re;- }- }-- private void fillViewPOBuilderParentEntityId(ViewPO.Builder builder, Namespace namespace) {- NamespaceUtil.checkView(namespace);- NamespacedEntityId namespacedEntityId =- EntityIdService.getEntityIds(- NameIdentifier.of(namespace.levels()), Entity.EntityType.SCHEMA);- builder.withMetalakeId(namespacedEntityId.namespaceIds()[0]);- builder.withCatalogId(namespacedEntityId.namespaceIds()[1]);- builder.withSchemaId(namespacedEntityId.entityId());- }-- private ViewPO.Builder createViewPOBuilder(Namespace namespace) {- ViewPO.Builder builder = ViewPO.builder();- fillViewPOBuilderParentEntityId(builder, namespace);- return builder;+ private ViewPO updateViewPO(ViewPO oldViewPO, ViewEntity newEntity) {+ Long newVersion = oldViewPO.getLastVersion() + 1;+ ViewPO.ViewPOBuilder builder =+ ViewPO.builder()+ .withMetalakeId(oldViewPO.getMetalakeId())+ .withCatalogId(oldViewPO.getCatalogId())+ .withSchemaId(oldViewPO.getSchemaId())+ .withCurrentVersion(newVersion)+ .withLastVersion(newVersion);+ return buildViewPO(newEntity, builder, newVersion.intValue());}private List<ViewPO> listViewPOsByNamespace(Namespace namespace) {@@ -362,7 +292,18 @@ public class ViewMetaService {Long schemaId =EntityIdService.getEntityId(NameIdentifier.of(identifier.namespace().levels()), Entity.EntityType.SCHEMA);- return getViewPOBySchemaIdAndName(schemaId, identifier.name());+ ViewPO viewPO =+ SessionUtils.getWithoutCommit(+ ViewMetaMapper.class,+ mapper -> mapper.selectViewMetaBySchemaIdAndName(schemaId, identifier.name()));++ if (viewPO == null) {+ throw new NoSuchEntityException(+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,+ Entity.EntityType.VIEW.name().toLowerCase(),+ identifier.name());+ }+ return viewPO;}private ViewPO getViewPOByFullQualifiedName(NameIdentifier identifier) {diff --git a/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java b/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.javaindex f73cccb583..3d43cb95d8 100644--- a/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/catalog/TestViewOperationDispatcher.java@@ -48,9 +48,10 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.exceptions.NoSuchViewException;import org.apache.gravitino.lock.LockManager;import org.apache.gravitino.meta.AuditInfo;-import org.apache.gravitino.meta.GenericEntity;+import org.apache.gravitino.meta.ViewEntity;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.SQLRepresentation;import org.apache.gravitino.rel.View;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;@@ -109,7 +110,9 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {@Overridepublic Representation[] representations() {- return new Representation[0];+ return new Representation[] {+ SQLRepresentation.builder().withDialect("unknown").withSql("SELECT 1").build()+ };}@Override@@ -210,14 +213,14 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {// Verify view is not in entity store initiallyAssertions.assertThrows(- NoSuchEntityException.class, () -> entityStore.get(viewIdent, VIEW, GenericEntity.class));+ NoSuchEntityException.class, () -> entityStore.get(viewIdent, VIEW, ViewEntity.class));// Load view - should auto-importView loadedView = viewOperationDispatcher.loadView(viewIdent);Assertions.assertEquals("auto_import_view", loadedView.name());// Verify view was auto-imported into entity store- GenericEntity viewEntity = entityStore.get(viewIdent, VIEW, GenericEntity.class);+ ViewEntity viewEntity = entityStore.get(viewIdent, VIEW, ViewEntity.class);Assertions.assertNotNull(viewEntity);Assertions.assertEquals(viewIdent.name(), viewEntity.name());Assertions.assertEquals(viewIdent.namespace(), viewEntity.namespace());@@ -233,12 +236,17 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {NameIdentifier viewIdent = NameIdentifier.of(viewNs, "already_imported_view");// Pre-populate entity store with view entity- GenericEntity viewEntity =- GenericEntity.builder()+ ViewEntity viewEntity =+ ViewEntity.builder().withId(1L).withName(viewIdent.name()).withNamespace(viewIdent.namespace())- .withEntityType(Entity.EntityType.VIEW)+ .withColumns(new Column[0])+ .withRepresentations(+ new Representation[] {+ SQLRepresentation.builder().withDialect("unknown").withSql("SELECT 1").build()+ })+ .withAuditInfo(AuditInfo.EMPTY).build();entityStore.put(viewEntity, false);@@ -253,7 +261,7 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {testCatalogOperations.views.put(viewIdent, mockView);// Record the initial entity state- GenericEntity initialEntity = entityStore.get(viewIdent, VIEW, GenericEntity.class);+ ViewEntity initialEntity = entityStore.get(viewIdent, VIEW, ViewEntity.class);long initialId = initialEntity.id();// Load view - should load from catalog but skip import since already in entity store@@ -262,7 +270,7 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {// Verify entity is still in store with same ID (no duplicate import)// If import was called, a new entity would be created with a different ID- GenericEntity retrievedEntity = entityStore.get(viewIdent, VIEW, GenericEntity.class);+ ViewEntity retrievedEntity = entityStore.get(viewIdent, VIEW, ViewEntity.class);Assertions.assertNotNull(retrievedEntity);Assertions.assertEquals(initialId, retrievedEntity.id(), "Entity ID should not change");Assertions.assertEquals(1L, retrievedEntity.id(), "Entity ID should remain 1L (no new import)");@@ -361,7 +369,7 @@ public class TestViewOperationDispatcher extends TestOperationDispatcher {Assertions.assertEquals("deleted_view", loadedView2.name());// Verify view was re-imported- GenericEntity viewEntity = entityStore.get(viewIdent, VIEW, GenericEntity.class);+ ViewEntity viewEntity = entityStore.get(viewIdent, VIEW, ViewEntity.class);Assertions.assertNotNull(viewEntity);}}diff --git a/core/src/test/java/org/apache/gravitino/connector/TestCatalogOperations.java b/core/src/test/java/org/apache/gravitino/connector/TestCatalogOperations.javaindex 15c4be23bf..2ec9ec0239 100644--- a/core/src/test/java/org/apache/gravitino/connector/TestCatalogOperations.java+++ b/core/src/test/java/org/apache/gravitino/connector/TestCatalogOperations.java@@ -89,11 +89,13 @@ import org.apache.gravitino.model.ModelChange;import org.apache.gravitino.model.ModelVersion;import org.apache.gravitino.model.ModelVersionChange;import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Representation;import org.apache.gravitino.rel.Table;import org.apache.gravitino.rel.TableCatalog;import org.apache.gravitino.rel.TableChange;import org.apache.gravitino.rel.View;import org.apache.gravitino.rel.ViewCatalog;+import org.apache.gravitino.rel.ViewChange;import org.apache.gravitino.rel.expressions.distributions.Distribution;import org.apache.gravitino.rel.expressions.sorts.SortOrder;import org.apache.gravitino.rel.expressions.transforms.Transform;@@ -302,6 +304,35 @@ public class TestCatalogOperations}}+ @Override+ public View createView(+ NameIdentifier ident,+ String comment,+ Column[] columns,+ Representation[] representations,+ String defaultCatalog,+ String defaultSchema,+ Map<String, String> properties) {+ throw new UnsupportedOperationException("createView not implemented in test");+ }++ @Override+ public View alterView(NameIdentifier ident, ViewChange... changes) {+ throw new UnsupportedOperationException("alterView not implemented in test");+ }++ @Override+ public boolean dropView(NameIdentifier ident) {+ return views.remove(ident) != null;+ }++ @Override+ public NameIdentifier[] listViews(Namespace namespace) {+ return views.keySet().stream()+ .filter(ident -> ident.namespace().equals(namespace))+ .toArray(NameIdentifier[]::new);+ }+@Overridepublic NameIdentifier[] listSchemas(Namespace namespace) throws NoSuchCatalogException {return schemas.keySet().stream()diff --git a/core/src/test/java/org/apache/gravitino/storage/TestEntityStorageRelationCache.java b/core/src/test/java/org/apache/gravitino/storage/TestEntityStorageRelationCache.javaindex b5f2960d10..2e75d6b684 100644--- a/core/src/test/java/org/apache/gravitino/storage/TestEntityStorageRelationCache.java+++ b/core/src/test/java/org/apache/gravitino/storage/TestEntityStorageRelationCache.java@@ -63,8 +63,12 @@ import org.apache.gravitino.meta.RoleEntity;import org.apache.gravitino.meta.SchemaEntity;import org.apache.gravitino.meta.TagEntity;import org.apache.gravitino.meta.UserEntity;+import org.apache.gravitino.meta.ViewEntity;import org.apache.gravitino.policy.Policy;import org.apache.gravitino.policy.PolicyContents;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.SQLRepresentation;import org.apache.gravitino.rel.types.Types;import org.apache.gravitino.storage.relational.RelationalEntityStore;import org.apache.gravitino.utils.NameIdentifierUtil;@@ -942,20 +946,25 @@ public class TestEntityStorageRelationCache extends AbstractEntityStorageTest {store.put(schema, false);Namespace viewNamespace = Namespace.of("metalake", "catalog", "schema");- GenericEntity view =- GenericEntity.builder()+ ViewEntity view =+ ViewEntity.builder().withId(RandomIdGenerator.INSTANCE.nextId()).withName("test_view").withNamespace(viewNamespace)- .withEntityType(Entity.EntityType.VIEW)+ .withColumns(new Column[0])+ .withRepresentations(+ new Representation[] {+ SQLRepresentation.builder().withDialect("unknown").withSql("SELECT 1").build()+ })+ .withAuditInfo(auditInfo).build();// Use store.put() to trigger the actual cache + reverse index flowstore.put(view, false);// Verify view IS in forward cache (performance cache for get operations)- GenericEntity retrievedView =- store.get(view.nameIdentifier(), Entity.EntityType.VIEW, GenericEntity.class);+ ViewEntity retrievedView =+ store.get(view.nameIdentifier(), Entity.EntityType.VIEW, ViewEntity.class);Assertions.assertNotNull(retrievedView);Assertions.assertEquals(view.id(), retrievedView.id());Assertions.assertEquals(view.name(), retrievedView.name());diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestJDBCBackend.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestJDBCBackend.javaindex ff388c3b23..1e4fe8c884 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestJDBCBackend.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestJDBCBackend.java@@ -57,7 +57,6 @@ import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.FilesetEntity;import org.apache.gravitino.meta.FunctionEntity;-import org.apache.gravitino.meta.GenericEntity;import org.apache.gravitino.meta.GroupEntity;import org.apache.gravitino.meta.JobTemplateEntity;import org.apache.gravitino.meta.ModelEntity;@@ -69,9 +68,13 @@ import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.meta.TagEntity;import org.apache.gravitino.meta.TopicEntity;import org.apache.gravitino.meta.UserEntity;+import org.apache.gravitino.meta.ViewEntity;import org.apache.gravitino.policy.Policy;import org.apache.gravitino.policy.PolicyContent;import org.apache.gravitino.policy.PolicyContents;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.SQLRepresentation;import org.apache.gravitino.rel.types.Types;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;@@ -548,12 +551,17 @@ public abstract class TestJDBCBackend {.build();}- protected GenericEntity createViewEntity(Long id, Namespace namespace, String viewName) {- return GenericEntity.builder()+ protected ViewEntity createViewEntity(Long id, Namespace namespace, String viewName) {+ return ViewEntity.builder().withId(id).withName(viewName).withNamespace(namespace)- .withEntityType(Entity.EntityType.VIEW)+ .withColumns(new Column[0])+ .withRepresentations(+ new Representation[] {+ SQLRepresentation.builder().withDialect("unknown").withSql("SELECT 1").build()+ })+ .withAuditInfo(AUDIT_INFO).build();}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/po/TestViewPO.java b/core/src/test/java/org/apache/gravitino/storage/relational/po/TestViewPO.javanew file mode 100644index 0000000000..7a6e92871e--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/storage/relational/po/TestViewPO.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.storage.relational.po;++import com.fasterxml.jackson.core.JsonProcessingException;+import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.SQLRepresentation;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestViewPO {++ @Test+ public void testViewPOBuilder() {+ ViewVersionInfoPO viewVersionInfoPO = buildViewVersionInfoPO(1L, 1);+ ViewPO viewPO =+ ViewPO.builder()+ .withViewId(1L)+ .withViewName("test_view")+ .withMetalakeId(1L)+ .withCatalogId(2L)+ .withSchemaId(3L)+ .withAuditInfo("audit-info")+ .withCurrentVersion(1L)+ .withLastVersion(1L)+ .withDeletedAt(0L)+ .withViewVersionInfoPO(viewVersionInfoPO)+ .build();++ Assertions.assertEquals(1L, viewPO.getViewId());+ Assertions.assertEquals("test_view", viewPO.getViewName());+ Assertions.assertEquals(1L, viewPO.getMetalakeId());+ Assertions.assertEquals(2L, viewPO.getCatalogId());+ Assertions.assertEquals(3L, viewPO.getSchemaId());+ Assertions.assertEquals("audit-info", viewPO.getAuditInfo());+ Assertions.assertEquals(1L, viewPO.getCurrentVersion());+ Assertions.assertEquals(1L, viewPO.getLastVersion());+ Assertions.assertEquals(0L, viewPO.getDeletedAt());+ Assertions.assertEquals(viewVersionInfoPO, viewPO.getViewVersionInfoPO());+ }++ @Test+ public void testEqualsAndHashCodeIgnoreViewVersionInfoPO() {+ ViewPO viewPOWithVersionOne =+ ViewPO.builder()+ .withViewId(1L)+ .withViewName("test_view")+ .withMetalakeId(1L)+ .withCatalogId(2L)+ .withSchemaId(3L)+ .withAuditInfo("audit-info")+ .withCurrentVersion(1L)+ .withLastVersion(1L)+ .withDeletedAt(0L)+ .withViewVersionInfoPO(buildViewVersionInfoPO(1L, 1))+ .build();++ ViewPO viewPOWithVersionTwo =+ ViewPO.builder()+ .withViewId(1L)+ .withViewName("test_view")+ .withMetalakeId(1L)+ .withCatalogId(2L)+ .withSchemaId(3L)+ .withAuditInfo("audit-info")+ .withCurrentVersion(1L)+ .withLastVersion(1L)+ .withDeletedAt(0L)+ .withViewVersionInfoPO(buildViewVersionInfoPO(2L, 2))+ .build();++ Assertions.assertEquals(viewPOWithVersionOne, viewPOWithVersionTwo);+ Assertions.assertEquals(viewPOWithVersionOne.hashCode(), viewPOWithVersionTwo.hashCode());+ }++ @Test+ public void testRepresentationsSerDe() throws JsonProcessingException {+ Representation[] representations =+ new Representation[] {+ SQLRepresentation.builder().withDialect("spark").withSql("SELECT 1").build(),+ SQLRepresentation.builder().withDialect("trino").withSql("SELECT 1").build()+ };++ String json = ViewPO.serializeRepresentations(representations);+ Representation[] deserialized = ViewPO.deserializeRepresentations(json);++ Assertions.assertArrayEquals(representations, deserialized);+ }++ @Test+ public void testDeserializeRepresentationsWithoutType() throws JsonProcessingException {+ String json = "[{\"dialect\":\"spark\",\"sql\":\"SELECT 1\"}]";++ Representation[] deserialized = ViewPO.deserializeRepresentations(json);++ Assertions.assertEquals(1, deserialized.length);+ Assertions.assertTrue(deserialized[0] instanceof SQLRepresentation);+ SQLRepresentation sqlRepresentation = (SQLRepresentation) deserialized[0];+ Assertions.assertEquals("spark", sqlRepresentation.dialect());+ Assertions.assertEquals("SELECT 1", sqlRepresentation.sql());+ }++ private ViewVersionInfoPO buildViewVersionInfoPO(Long id, Integer version) {+ return ViewVersionInfoPO.builder()+ .withId(id)+ .withMetalakeId(1L)+ .withCatalogId(2L)+ .withSchemaId(3L)+ .withViewId(1L)+ .withVersion(version)+ .withColumns("[]")+ .withRepresentations("[{\"dialect\":\"spark\",\"sql\":\"SELECT 1\"}]")+ .withAuditInfo("audit-info")+ .withDeletedAt(0L)+ .build();+ }+}diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOwnerMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOwnerMetaService.javaindex 51b6c9d0d8..46de145356 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOwnerMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestOwnerMetaService.java@@ -38,7 +38,6 @@ import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.FilesetEntity;import org.apache.gravitino.meta.FunctionEntity;-import org.apache.gravitino.meta.GenericEntity;import org.apache.gravitino.meta.GroupEntity;import org.apache.gravitino.meta.ModelEntity;import org.apache.gravitino.meta.RoleEntity;@@ -46,6 +45,7 @@ import org.apache.gravitino.meta.SchemaEntity;import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.meta.TopicEntity;import org.apache.gravitino.meta.UserEntity;+import org.apache.gravitino.meta.ViewEntity;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.TestJDBCBackend;import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;@@ -249,7 +249,7 @@ class TestOwnerMetaService extends TestJDBCBackend {null,AUDIT_INFO);backend.insert(model, false);- GenericEntity view =+ ViewEntity view =createViewEntity(RandomIdGenerator.INSTANCE.nextId(),Namespace.of(TestOwnerMetaService.METALAKE_NAME, CATALOG_NAME, SCHEMA_NAME),diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSecurableObjects.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSecurableObjects.javaindex b93d533b24..6f59f1027c 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSecurableObjects.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSecurableObjects.java@@ -38,12 +38,12 @@ import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.CatalogEntity;import org.apache.gravitino.meta.FilesetEntity;import org.apache.gravitino.meta.FunctionEntity;-import org.apache.gravitino.meta.GenericEntity;import org.apache.gravitino.meta.ModelEntity;import org.apache.gravitino.meta.RoleEntity;import org.apache.gravitino.meta.SchemaEntity;import org.apache.gravitino.meta.TableEntity;import org.apache.gravitino.meta.TopicEntity;+import org.apache.gravitino.meta.ViewEntity;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.TestJDBCBackend;import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;@@ -104,7 +104,7 @@ public class TestSecurableObjects extends TestJDBCBackend {AUDIT_INFO);backend.insert(topic, false);- GenericEntity view =+ ViewEntity view =createViewEntity(RandomIdGenerator.INSTANCE.nextId(),Namespace.of(metalakeName, "catalog", "schema"),@@ -221,7 +221,7 @@ public class TestSecurableObjects extends TestJDBCBackend {AUDIT_INFO);backend.insert(model, false);- GenericEntity view =+ ViewEntity view =createViewEntity(RandomIdGenerator.INSTANCE.nextId(),Namespace.of("metalake", "catalog", "schema"),diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestViewMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestViewMetaService.javaindex d221426b46..2c6488e329 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestViewMetaService.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestViewMetaService.java@@ -19,34 +19,44 @@package org.apache.gravitino.storage.relational.service;import static org.junit.jupiter.api.Assertions.assertEquals;-import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertNotNull;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.sql.Connection;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;import java.time.Instant;+import java.util.HashMap;import java.util.List;-import java.util.function.Function;-import org.apache.gravitino.Entity;+import java.util.Map;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.GenericEntity;+import org.apache.gravitino.integration.test.util.GravitinoITUtils;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.ViewEntity;+import org.apache.gravitino.rel.Column;+import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.SQLRepresentation;+import org.apache.gravitino.rel.types.Types;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.TestJDBCBackend;-import org.apache.gravitino.utils.NameIdentifierUtil;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;import org.apache.gravitino.utils.NamespaceUtil;-import org.junit.jupiter.api.Assertions;+import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.TestTemplate;public class TestViewMetaService extends TestJDBCBackend {- private final String metalakeName = "metalake_for_view_test";- private final String catalogName = "catalog_for_view_test";- private final String schemaName = "schema_for_view_test";+ private final String metalakeName = GravitinoITUtils.genRandomName("tst_metalake");+ private final String catalogName = GravitinoITUtils.genRandomName("tst_view_catalog");+ private final String schemaName = GravitinoITUtils.genRandomName("tst_view_schema");@BeforeEachpublic void prepare() throws IOException {@@ -55,291 +65,272 @@ public class TestViewMetaService extends TestJDBCBackend {createAndInsertSchema(metalakeName, catalogName, schemaName);}- @TestTemplate- public void testInsertAndGetView() throws IOException {- Namespace viewNamespace = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);- GenericEntity view =- createViewEntity(RandomIdGenerator.INSTANCE.nextId(), viewNamespace, "test_view");-- // Insert view- backend.insert(view, false);-- // Get view- NameIdentifier viewIdent = NameIdentifier.of(viewNamespace, "test_view");- GenericEntity retrievedView = backend.get(viewIdent, Entity.EntityType.VIEW);-- assertNotNull(retrievedView);- assertEquals(view.id(), retrievedView.id());- assertEquals(view.name(), retrievedView.name());- assertEquals(viewNamespace, retrievedView.namespace());- assertEquals(Entity.EntityType.VIEW, retrievedView.type());- }-@TestTemplatepublic void testInsertAlreadyExistsException() throws IOException {- Namespace viewNamespace = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);- GenericEntity view =- createViewEntity(RandomIdGenerator.INSTANCE.nextId(), viewNamespace, "view");- GenericEntity viewCopy =- createViewEntity(RandomIdGenerator.INSTANCE.nextId(), viewNamespace, "view");-- backend.insert(view, false);- assertThrows(EntityAlreadyExistsException.class, () -> backend.insert(viewCopy, false));+ Namespace ns = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);+ ViewEntity view =+ createViewEntity(RandomIdGenerator.INSTANCE.nextId(), ns, "test_view", AUDIT_INFO);+ ViewEntity viewCopy =+ createViewEntity(RandomIdGenerator.INSTANCE.nextId(), ns, "test_view", AUDIT_INFO);++ ViewMetaService.getInstance().insertView(view, false);+ assertThrows(+ EntityAlreadyExistsException.class,+ () -> ViewMetaService.getInstance().insertView(viewCopy, false));}@TestTemplate- public void testInsertWithOverwrite() throws IOException {- Namespace viewNamespace = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);- GenericEntity view =- createViewEntity(RandomIdGenerator.INSTANCE.nextId(), viewNamespace, "view_overwrite");-- backend.insert(view, false);-- // Insert with overwrite should succeed- GenericEntity viewOverwrite = createViewEntity(view.id(), viewNamespace, "view_overwrite");- backend.insert(viewOverwrite, true);-- // Verify the view still exists- NameIdentifier viewIdent = NameIdentifier.of(viewNamespace, "view_overwrite");- GenericEntity retrievedView = backend.get(viewIdent, Entity.EntityType.VIEW);- assertNotNull(retrievedView);- assertEquals(view.id(), retrievedView.id());- assertEquals(viewNamespace, retrievedView.namespace());+ public void testInsertAndGetView() throws IOException {+ String viewName = GravitinoITUtils.genRandomName("test_view");+ Namespace ns = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);+ ViewEntity view =+ createViewEntity(RandomIdGenerator.INSTANCE.nextId(), ns, viewName, AUDIT_INFO);++ ViewMetaService.getInstance().insertView(view, false);++ NameIdentifier viewIdent = NameIdentifier.of(metalakeName, catalogName, schemaName, viewName);+ ViewEntity loaded = ViewMetaService.getInstance().getViewByIdentifier(viewIdent);++ assertNotNull(loaded);+ assertEquals(view.id(), loaded.id());+ assertEquals(view.name(), loaded.name());+ assertEquals(view.comment(), loaded.comment());+ assertEquals(view.defaultCatalog(), loaded.defaultCatalog());+ assertEquals(view.defaultSchema(), loaded.defaultSchema());+ assertEquals(view.columns().length, loaded.columns().length);+ assertEquals(view.representations().length, loaded.representations().length);+ assertEquals(view.auditInfo().creator(), loaded.auditInfo().creator());}@TestTemplatepublic void testListViews() throws IOException {- Namespace viewNamespace = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);- GenericEntity view1 =- createViewEntity(RandomIdGenerator.INSTANCE.nextId(), viewNamespace, "view1");- GenericEntity view2 =- createViewEntity(RandomIdGenerator.INSTANCE.nextId(), viewNamespace, "view2");- GenericEntity view3 =- createViewEntity(RandomIdGenerator.INSTANCE.nextId(), viewNamespace, "view3");-- backend.insert(view1, false);- backend.insert(view2, false);- backend.insert(view3, false);-- List<GenericEntity> views = backend.list(viewNamespace, Entity.EntityType.VIEW, true);-- assertEquals(3, views.size());- assertTrue(views.stream().anyMatch(v -> v.name().equals("view1")));- assertTrue(views.stream().anyMatch(v -> v.name().equals("view2")));- assertTrue(views.stream().anyMatch(v -> v.name().equals("view3")));- // Verify all views have namespace set- assertTrue(views.stream().allMatch(v -> viewNamespace.equals(v.namespace())));+ Namespace ns = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);++ String viewName1 = GravitinoITUtils.genRandomName("test_view1");+ ViewEntity view1 =+ createViewEntity(RandomIdGenerator.INSTANCE.nextId(), ns, viewName1, AUDIT_INFO);++ String viewName2 = GravitinoITUtils.genRandomName("test_view2");+ ViewEntity view2 =+ createViewEntity(RandomIdGenerator.INSTANCE.nextId(), ns, viewName2, AUDIT_INFO);++ ViewMetaService.getInstance().insertView(view1, false);+ ViewMetaService.getInstance().insertView(view2, false);++ List<ViewEntity> views = ViewMetaService.getInstance().listViewsByNamespace(ns);++ assertEquals(2, views.size());+ assertTrue(views.stream().anyMatch(v -> v.name().equals(viewName1)));+ assertTrue(views.stream().anyMatch(v -> v.name().equals(viewName2)));}@TestTemplatepublic void testUpdateView() throws IOException {- Namespace viewNamespace = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);- GenericEntity view =- createViewEntity(RandomIdGenerator.INSTANCE.nextId(), viewNamespace, "view_to_update");-- backend.insert(view, false);-- // Update view name- Function<GenericEntity, GenericEntity> updater =- oldView ->- GenericEntity.builder()- .withId(oldView.id())- .withName("view_updated")- .withNamespace(oldView.namespace())- .withEntityType(Entity.EntityType.VIEW)- .build();-- NameIdentifier viewIdent = NameIdentifier.of(viewNamespace, "view_to_update");- GenericEntity updatedView = backend.update(viewIdent, Entity.EntityType.VIEW, updater);-- assertNotNull(updatedView);- assertEquals("view_updated", updatedView.name());- assertEquals(view.id(), updatedView.id());-- // Verify old name no longer exists- assertThrows(NoSuchEntityException.class, () -> backend.get(viewIdent, Entity.EntityType.VIEW));-- // Verify new name exists- NameIdentifier newViewIdent = NameIdentifier.of(viewNamespace, "view_updated");- GenericEntity retrievedView = backend.get(newViewIdent, Entity.EntityType.VIEW);- assertNotNull(retrievedView);- assertEquals("view_updated", retrievedView.name());- assertEquals(viewNamespace, retrievedView.namespace());+ String viewName = GravitinoITUtils.genRandomName("test_view");+ Namespace ns = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);+ ViewEntity view =+ createViewEntity(RandomIdGenerator.INSTANCE.nextId(), ns, viewName, AUDIT_INFO);++ ViewMetaService.getInstance().insertView(view, false);++ NameIdentifier viewIdent = NameIdentifier.of(metalakeName, catalogName, schemaName, viewName);+ ViewEntity updated =+ ViewEntity.builder()+ .withId(view.id())+ .withName(view.name())+ .withNamespace(ns)+ .withComment("updated comment")+ .withColumns(view.columns())+ .withRepresentations(view.representations())+ .withDefaultCatalog("updated_catalog")+ .withDefaultSchema("updated_schema")+ .withProperties(view.properties())+ .withAuditInfo(AUDIT_INFO)+ .build();++ ViewEntity result = ViewMetaService.getInstance().updateView(viewIdent, e -> updated);+ assertEquals("updated comment", result.comment());+ assertEquals("updated_catalog", result.defaultCatalog());+ assertEquals("updated_schema", result.defaultSchema());++ Map<Integer, Long> versions = listViewVersions(view.id());+ assertEquals(2, versions.size());+ assertTrue(versions.containsKey(1));+ assertTrue(versions.containsKey(2));}@TestTemplate- public void testUpdateViewCrossNamespace() throws IOException {- // Create a second schema for cross-namespace rename- String schemaName2 = "schema_for_view_test_2";- createAndInsertSchema(metalakeName, catalogName, schemaName2);-- Namespace viewNamespace1 = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);- Namespace viewNamespace2 = NamespaceUtil.ofView(metalakeName, catalogName, schemaName2);-- GenericEntity view =- createViewEntity(- RandomIdGenerator.INSTANCE.nextId(), viewNamespace1, "view_cross_namespace");-- backend.insert(view, false);-- // Update view to move to different namespace- Function<GenericEntity, GenericEntity> updater =- oldView ->- GenericEntity.builder()- .withId(oldView.id())- .withName("view_cross_namespace_renamed")- .withNamespace(viewNamespace2)- .withEntityType(Entity.EntityType.VIEW)- .build();-- NameIdentifier viewIdent = NameIdentifier.of(viewNamespace1, "view_cross_namespace");- GenericEntity updatedView = backend.update(viewIdent, Entity.EntityType.VIEW, updater);-- assertNotNull(updatedView);- assertEquals("view_cross_namespace_renamed", updatedView.name());- assertEquals(view.id(), updatedView.id());-- // Verify old namespace+name no longer exists- assertThrows(NoSuchEntityException.class, () -> backend.get(viewIdent, Entity.EntityType.VIEW));-- // Verify new namespace+name exists- NameIdentifier newViewIdent = NameIdentifier.of(viewNamespace2, "view_cross_namespace_renamed");- GenericEntity retrievedView = backend.get(newViewIdent, Entity.EntityType.VIEW);- assertNotNull(retrievedView);- assertEquals("view_cross_namespace_renamed", retrievedView.name());- assertEquals(viewNamespace2, retrievedView.namespace());- }+ public void testUpdateViewRollbackWhenMetaUpdateAffectsZeroRows() throws IOException {+ String viewName = GravitinoITUtils.genRandomName("test_view");+ Namespace ns = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);+ ViewEntity view =+ createViewEntity(RandomIdGenerator.INSTANCE.nextId(), ns, viewName, AUDIT_INFO);+ ViewMetaService.getInstance().insertView(view, false);++ NameIdentifier viewIdent = NameIdentifier.of(metalakeName, catalogName, schemaName, viewName);+ ViewEntity updated =+ ViewEntity.builder()+ .withId(view.id())+ .withName(view.name())+ .withNamespace(ns)+ .withComment("updated comment")+ .withColumns(view.columns())+ .withRepresentations(view.representations())+ .withDefaultCatalog("updated_catalog")+ .withDefaultSchema("updated_schema")+ .withProperties(view.properties())+ .withAuditInfo(AUDIT_INFO)+ .build();- @TestTemplate- public void testUpdateAlreadyExistsException() throws IOException {- Namespace viewNamespace = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);- GenericEntity view1 =- createViewEntity(RandomIdGenerator.INSTANCE.nextId(), viewNamespace, "view1");- GenericEntity view2 =- createViewEntity(RandomIdGenerator.INSTANCE.nextId(), viewNamespace, "view2");-- backend.insert(view1, false);- backend.insert(view2, false);-- // Try to update view2's name to view1 (which already exists)- NameIdentifier view2Ident = NameIdentifier.of(viewNamespace, "view2");assertThrows(- EntityAlreadyExistsException.class,+ IOException.class,() ->- backend.update(- view2Ident,- Entity.EntityType.VIEW,- e ->- GenericEntity.builder()- .withId(view2.id())- .withName("view1")- .withNamespace(viewNamespace)- .withEntityType(Entity.EntityType.VIEW)- .build()));+ ViewMetaService.getInstance()+ .updateView(+ viewIdent,+ e -> {+ ViewMetaService.getInstance().deleteView(viewIdent);+ return updated;+ }));++ Map<Integer, Long> versions = listViewVersions(view.id());+ assertEquals(1, versions.size());+ assertTrue(versions.containsKey(1));+ assertTrue(versions.get(1) > 0L);}@TestTemplatepublic void testDeleteView() throws IOException {- Namespace viewNamespace = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);- GenericEntity view =- createViewEntity(RandomIdGenerator.INSTANCE.nextId(), viewNamespace, "view_to_delete");+ String viewName = GravitinoITUtils.genRandomName("test_view");+ Namespace ns = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);+ ViewEntity view =+ createViewEntity(RandomIdGenerator.INSTANCE.nextId(), ns, viewName, AUDIT_INFO);- backend.insert(view, false);+ ViewMetaService.getInstance().insertView(view, false);- NameIdentifier viewIdent = NameIdentifier.of(viewNamespace, "view_to_delete");+ NameIdentifier viewIdent = NameIdentifier.of(metalakeName, catalogName, schemaName, viewName);+ assertTrue(ViewMetaService.getInstance().deleteView(viewIdent));- // Verify view exists- assertTrue(backend.exists(viewIdent, Entity.EntityType.VIEW));-- // Delete view- boolean deleted = backend.delete(viewIdent, Entity.EntityType.VIEW, false);- assertTrue(deleted);-- // Verify view no longer exists- assertFalse(backend.exists(viewIdent, Entity.EntityType.VIEW));+ assertThrows(+ NoSuchEntityException.class,+ () -> ViewMetaService.getInstance().getViewByIdentifier(viewIdent));}@TestTemplate- public void testDeleteNonExistentView() throws IOException {- Namespace viewNamespace = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);- NameIdentifier viewIdent = NameIdentifier.of(viewNamespace, "non_existent_view");-- // Delete should throw exception for non-existent view+ public void testGetNonExistentView() {+ NameIdentifier viewIdent =+ NameIdentifier.of(metalakeName, catalogName, schemaName, "non_existent_view");assertThrows(NoSuchEntityException.class,- () -> backend.delete(viewIdent, Entity.EntityType.VIEW, false));+ () -> ViewMetaService.getInstance().getViewByIdentifier(viewIdent));}@TestTemplate- public void testGetNonExistentView() throws IOException {- Namespace viewNamespace = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);- NameIdentifier viewIdent = NameIdentifier.of(viewNamespace, "non_existent_view");-- assertThrows(NoSuchEntityException.class, () -> backend.get(viewIdent, Entity.EntityType.VIEW));+ public void testInsertViewWithOverwrite() throws IOException {+ String viewName = GravitinoITUtils.genRandomName("test_view");+ Namespace ns = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);+ ViewEntity view =+ createViewEntity(RandomIdGenerator.INSTANCE.nextId(), ns, viewName, AUDIT_INFO);++ ViewMetaService.getInstance().insertView(view, false);++ ViewEntity newView =+ ViewEntity.builder()+ .withId(view.id())+ .withName(view.name())+ .withNamespace(ns)+ .withComment("overwritten comment")+ .withColumns(view.columns())+ .withRepresentations(view.representations())+ .withDefaultCatalog(view.defaultCatalog())+ .withDefaultSchema(view.defaultSchema())+ .withProperties(view.properties())+ .withAuditInfo(AUDIT_INFO)+ .build();++ ViewMetaService.getInstance().insertView(newView, true);++ NameIdentifier viewIdent = NameIdentifier.of(metalakeName, catalogName, schemaName, viewName);+ ViewEntity loaded = ViewMetaService.getInstance().getViewByIdentifier(viewIdent);+ assertEquals("overwritten comment", loaded.comment());}@TestTemplate- public void testMetaLifeCycleFromCreationToDeletion() throws IOException {- Namespace viewNamespace = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);- GenericEntity view =- createViewEntity(RandomIdGenerator.INSTANCE.nextId(), viewNamespace, "lifecycle_view");-- backend.insert(view, false);-- List<GenericEntity> views = backend.list(viewNamespace, Entity.EntityType.VIEW, true);- assertTrue(views.stream().anyMatch(v -> v.name().equals("lifecycle_view")));-- GenericEntity viewEntity =- backend.get(NameIdentifier.of(viewNamespace, "lifecycle_view"), Entity.EntityType.VIEW);- assertEquals(view.id(), viewEntity.id());- assertEquals(view.name(), viewEntity.name());- assertEquals(viewNamespace, viewEntity.namespace());-- // meta data soft delete- backend.delete(- NameIdentifierUtil.ofView(metalakeName, catalogName, schemaName, "lifecycle_view"),- Entity.EntityType.VIEW,- true);-- // check existence after soft delete- NameIdentifier viewIdent = NameIdentifier.of(viewNamespace, "lifecycle_view");- assertFalse(backend.exists(viewIdent, Entity.EntityType.VIEW));-- // check legacy record after soft delete- assertTrue(legacyRecordExistsInDB(view.id(), Entity.EntityType.VIEW));-- // meta data hard delete- backend.hardDeleteLegacyData(Entity.EntityType.VIEW, Instant.now().toEpochMilli() + 3000);- assertFalse(legacyRecordExistsInDB(view.id(), Entity.EntityType.VIEW));+ public void testViewLifeCycle() throws IOException {+ String viewName = GravitinoITUtils.genRandomName("test_view");+ Namespace ns = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);+ ViewEntity view =+ createViewEntity(RandomIdGenerator.INSTANCE.nextId(), ns, viewName, AUDIT_INFO);+ ViewMetaService.getInstance().insertView(view, false);++ NameIdentifier viewIdent = NameIdentifier.of(metalakeName, catalogName, schemaName, viewName);+ ViewEntity v2 =+ ViewEntity.builder()+ .withId(view.id())+ .withName(view.name())+ .withNamespace(ns)+ .withComment("v2")+ .withColumns(view.columns())+ .withRepresentations(view.representations())+ .withDefaultCatalog(view.defaultCatalog())+ .withDefaultSchema(view.defaultSchema())+ .withProperties(view.properties())+ .withAuditInfo(AUDIT_INFO)+ .build();+ ViewMetaService.getInstance().updateView(viewIdent, e -> v2);++ assertTrue(ViewMetaService.getInstance().deleteView(viewIdent));++ int deleted =+ ViewMetaService.getInstance()+ .deleteViewMetasByLegacyTimeline(Instant.now().toEpochMilli() + 1000, 100);+ assertTrue(deleted >= 2);+ assertEquals(0, listViewVersions(view.id()).size());}- @TestTemplate- public void testViewIdBySchemaIdAndName() throws IOException {-- Namespace viewNamespace = NamespaceUtil.ofView(metalakeName, catalogName, schemaName);- long viewId = RandomIdGenerator.INSTANCE.nextId();- GenericEntity view = createViewEntity(viewId, viewNamespace, "id_test_view");-- backend.insert(view, false);-- Long schemaId =- EntityIdService.getEntityId(- NameIdentifier.of(metalakeName, catalogName, schemaName), Entity.EntityType.SCHEMA);- Long retrievedViewId =- ViewMetaService.getInstance().getViewIdBySchemaIdAndName(schemaId, "id_test_view");-- Assertions.assertEquals(viewId, retrievedViewId);+ private ViewEntity createViewEntity(+ Long id, Namespace namespace, String name, AuditInfo auditInfo) {+ Column[] columns =+ new Column[] {+ Column.of("c1", Types.IntegerType.get(), "first column"),+ Column.of("c2", Types.StringType.get(), "second column")+ };+ Representation[] reps =+ new Representation[] {+ SQLRepresentation.builder().withDialect("spark").withSql("SELECT c1, c2 FROM t").build(),+ SQLRepresentation.builder().withDialect("trino").withSql("SELECT c1, c2 FROM t").build()+ };+ return ViewEntity.builder()+ .withId(id)+ .withName(name)+ .withNamespace(namespace)+ .withComment("test view comment")+ .withColumns(columns)+ .withRepresentations(reps)+ .withDefaultCatalog(null)+ .withDefaultSchema(null)+ .withProperties(ImmutableMap.of("k1", "v1"))+ .withAuditInfo(auditInfo)+ .build();}- @TestTemplate- public void testGetViewIdBySchemaIdAndNameNotFound() throws IOException {-- Long schemaId =- EntityIdService.getEntityId(- NameIdentifier.of(metalakeName, catalogName, schemaName), Entity.EntityType.SCHEMA);-- assertThrows(- NoSuchEntityException.class,- () -> ViewMetaService.getInstance().getViewIdBySchemaIdAndName(schemaId, "non_existent"));+ private Map<Integer, Long> listViewVersions(Long viewId) {+ Map<Integer, Long> versionDeletedTime = new HashMap<>();+ try (SqlSession sqlSession =+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);+ Connection connection = sqlSession.getConnection();+ Statement statement = connection.createStatement();+ ResultSet rs =+ statement.executeQuery(+ String.format(+ "SELECT version, deleted_at FROM view_version_info WHERE view_id = %d",+ viewId))) {+ while (rs.next()) {+ versionDeletedTime.put(rs.getInt("version"), rs.getLong("deleted_at"));+ }+ } catch (SQLException e) {+ throw new RuntimeException("SQL execution failed", e);+ }+ return versionDeletedTime;}}diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergViewHookDispatcher.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergViewHookDispatcher.javaindex 5501336af1..edf525dc1f 100644--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergViewHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/dispatcher/IcebergViewHookDispatcher.java@@ -27,7 +27,7 @@ import org.apache.gravitino.catalog.ViewDispatcher;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.iceberg.common.utils.IcebergIdentifierUtils;import org.apache.gravitino.listener.api.event.IcebergRequestContext;-import org.apache.gravitino.meta.GenericEntity;+import org.apache.gravitino.meta.ViewEntity;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;import org.apache.iceberg.rest.requests.CreateViewRequest;@@ -159,14 +159,20 @@ public class IcebergViewHookDispatcher implements IcebergViewOperationDispatcherif (store != null) {store.update(sourceIdent,- GenericEntity.class,+ ViewEntity.class,Entity.EntityType.VIEW,viewEntity ->- GenericEntity.builder()+ ViewEntity.builder().withId(viewEntity.id()).withName(destIdent.name()).withNamespace(destIdent.namespace())- .withEntityType(Entity.EntityType.VIEW)+ .withComment(viewEntity.comment())+ .withColumns(viewEntity.columns())+ .withRepresentations(viewEntity.representations())+ .withDefaultCatalog(viewEntity.defaultCatalog())+ .withDefaultSchema(viewEntity.defaultSchema())+ .withProperties(viewEntity.properties())+ .withAuditInfo(viewEntity.auditInfo()).build());LOG.info("Successfully renamed view in Gravitino entity store from {} to {}",diff --git a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergViewHookDispatcher.java b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergViewHookDispatcher.javaindex 6e524f2e9b..cf74f760b3 100644--- a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergViewHookDispatcher.java+++ b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergViewHookDispatcher.java@@ -40,7 +40,7 @@ import org.apache.gravitino.catalog.ViewDispatcher;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.iceberg.common.utils.IcebergIdentifierUtils;import org.apache.gravitino.listener.api.event.IcebergRequestContext;-import org.apache.gravitino.meta.GenericEntity;+import org.apache.gravitino.meta.ViewEntity;import org.apache.iceberg.Schema;import org.apache.iceberg.catalog.Namespace;import org.apache.iceberg.catalog.TableIdentifier;@@ -255,8 +255,7 @@ public class TestIcebergViewHookDispatcher {NameIdentifier sourceGravitinoIdent =IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, sourceIdent);verify(mockEntityStore, times(1))- .update(- eq(sourceGravitinoIdent), eq(GenericEntity.class), eq(Entity.EntityType.VIEW), any());+ .update(eq(sourceGravitinoIdent), eq(ViewEntity.class), eq(Entity.EntityType.VIEW), any());}@Test@@ -270,7 +269,7 @@ public class TestIcebergViewHookDispatcher {NameIdentifier sourceGravitinoIdent =IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, sourceIdent);when(mockEntityStore.update(- eq(sourceGravitinoIdent), eq(GenericEntity.class), eq(Entity.EntityType.VIEW), any()))+ eq(sourceGravitinoIdent), eq(ViewEntity.class), eq(Entity.EntityType.VIEW), any())).thenThrow(new NoSuchEntityException("Entity not found"));// Should not throw - missing entity is ignored@@ -290,7 +289,7 @@ public class TestIcebergViewHookDispatcher {NameIdentifier sourceGravitinoIdent =IcebergIdentifierUtils.toGravitinoTableIdentifier(METALAKE, CATALOG, sourceIdent);when(mockEntityStore.update(- eq(sourceGravitinoIdent), eq(GenericEntity.class), eq(Entity.EntityType.VIEW), any()))+ eq(sourceGravitinoIdent), eq(ViewEntity.class), eq(Entity.EntityType.VIEW), any())).thenThrow(new IOException("IO error"));// Should throw RuntimeException wrapping the IOException