World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#10987] feat(client-java): add view CRUD to RelationalCatalog (#10988)
mchades3a3feb1367ec
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.javaindex 2dd515eb9a..dc14f4c6d8 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/ErrorHandlers.java@@ -67,6 +67,7 @@ import org.apache.gravitino.exceptions.NoSuchTableException;import org.apache.gravitino.exceptions.NoSuchTagException;import org.apache.gravitino.exceptions.NoSuchTopicException;import org.apache.gravitino.exceptions.NoSuchUserException;+import org.apache.gravitino.exceptions.NoSuchViewException;import org.apache.gravitino.exceptions.NonEmptyCatalogException;import org.apache.gravitino.exceptions.NonEmptyMetalakeException;import org.apache.gravitino.exceptions.NonEmptySchemaException;@@ -85,6 +86,7 @@ import org.apache.gravitino.exceptions.TopicAlreadyExistsException;import org.apache.gravitino.exceptions.UnauthorizedException;import org.apache.gravitino.exceptions.UnmodifiableStatisticException;import org.apache.gravitino.exceptions.UserAlreadyExistsException;+import org.apache.gravitino.exceptions.ViewAlreadyExistsException;/*** Utility class providing error handling for REST requests and specific to Metalake errors.@@ -129,6 +131,15 @@ public class ErrorHandlers {return TableErrorHandler.INSTANCE;}+ /**+ * Creates an error handler specific to View operations.+ *+ * @return A Consumer representing the View error handler.+ */+ public static Consumer<ErrorResponse> viewErrorHandler() {+ return ViewErrorHandler.INSTANCE;+ }+/*** Creates an error handler specific to Partition operations.*@@ -424,6 +435,61 @@ public class ErrorHandlers {}}+ /** Error handler specific to View operations. */+ @SuppressWarnings("FormatStringAnnotation")+ private static class ViewErrorHandler extends RestErrorHandler {+ private static final ErrorHandler INSTANCE = new ViewErrorHandler();++ @Override+ public void accept(ErrorResponse errorResponse) {+ String errorMessage = formatErrorMessage(errorResponse);++ switch (errorResponse.getCode()) {+ case ErrorConstants.ILLEGAL_ARGUMENTS_CODE:+ throw new IllegalArgumentException(errorMessage);++ case ErrorConstants.NOT_FOUND_CODE:+ if (errorResponse.getType().equals(NoSuchSchemaException.class.getSimpleName())) {+ throw new NoSuchSchemaException(errorMessage);+ } else if (errorResponse.getType().equals(NoSuchCatalogException.class.getSimpleName())) {+ throw new NoSuchCatalogException(errorMessage);+ } else if (errorResponse.getType().equals(NoSuchViewException.class.getSimpleName())) {+ throw new NoSuchViewException(errorMessage);+ } else {+ throw new NotFoundException(errorMessage);+ }++ case ErrorConstants.ALREADY_EXISTS_CODE:+ throw new ViewAlreadyExistsException(errorMessage);++ case ErrorConstants.INTERNAL_ERROR_CODE:+ throw new RuntimeException(errorMessage);++ case ErrorConstants.UNSUPPORTED_OPERATION_CODE:+ throw new UnsupportedOperationException(errorMessage);++ case ErrorConstants.FORBIDDEN_CODE:+ throw new ForbiddenException(errorMessage);++ case ErrorConstants.NOT_IN_USE_CODE:+ if (errorResponse.getType().equals(CatalogNotInUseException.class.getSimpleName())) {+ throw new CatalogNotInUseException(errorMessage);++ } else if (errorResponse+ .getType()+ .equals(MetalakeNotInUseException.class.getSimpleName())) {+ throw new MetalakeNotInUseException(errorMessage);++ } else {+ throw new NotInUseException(errorMessage);+ }++ default:+ super.accept(errorResponse);+ }+ }+ }+/** Error handler specific to Schema operations. */@SuppressWarnings("FormatStringAnnotation")private static class SchemaErrorHandler extends RestErrorHandler {diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java b/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.javaindex d587ad9e67..2df786d2d9 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java@@ -39,19 +39,31 @@ import org.apache.gravitino.Namespace;import org.apache.gravitino.authorization.Privilege;import org.apache.gravitino.dto.AuditDTO;import org.apache.gravitino.dto.CatalogDTO;+import org.apache.gravitino.dto.rel.ColumnDTO;+import org.apache.gravitino.dto.rel.RepresentationDTO;import org.apache.gravitino.dto.requests.TableCreateRequest;import org.apache.gravitino.dto.requests.TableUpdateRequest;import org.apache.gravitino.dto.requests.TableUpdatesRequest;+import org.apache.gravitino.dto.requests.ViewCreateRequest;+import org.apache.gravitino.dto.requests.ViewUpdateRequest;+import org.apache.gravitino.dto.requests.ViewUpdatesRequest;import org.apache.gravitino.dto.responses.DropResponse;import org.apache.gravitino.dto.responses.EntityListResponse;import org.apache.gravitino.dto.responses.TableResponse;+import org.apache.gravitino.dto.responses.ViewResponse;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchTableException;+import org.apache.gravitino.exceptions.NoSuchViewException;import org.apache.gravitino.exceptions.TableAlreadyExistsException;+import org.apache.gravitino.exceptions.ViewAlreadyExistsException;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;@@ -63,7 +75,7 @@ import org.apache.gravitino.rest.RESTUtils;* operations, for example, schemas and tables list, creation, update and deletion. A Relational* catalog is under the metalake.*/-class RelationalCatalog extends BaseSchemaCatalog implements TableCatalog {+class RelationalCatalog extends BaseSchemaCatalog implements TableCatalog, ViewCatalog {public static final String PRIVILEGES = "privileges";@@ -84,6 +96,11 @@ class RelationalCatalog extends BaseSchemaCatalog implements TableCatalog {return this;}+ @Override+ public ViewCatalog asViewCatalog() {+ return this;+ }+/*** List all the tables under the given Schema namespace.*@@ -96,7 +113,7 @@ class RelationalCatalog extends BaseSchemaCatalog implements TableCatalog {public NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {checkTableNamespace(namespace);- Namespace fullNamespace = getTableFullNamespace(namespace);+ Namespace fullNamespace = getEntityFullNamespace(namespace);EntityListResponse resp =restClient.get(formatTableRequestPath(fullNamespace),@@ -121,7 +138,7 @@ class RelationalCatalog extends BaseSchemaCatalog implements TableCatalog {public Table loadTable(NameIdentifier ident) throws NoSuchTableException {checkTableNameIdentifier(ident);- Namespace fullNamespace = getTableFullNamespace(ident.namespace());+ Namespace fullNamespace = getEntityFullNamespace(ident.namespace());TableResponse resp =restClient.get(formatTableRequestPath(fullNamespace) + "/" + RESTUtils.encodeString(ident.name()),@@ -138,7 +155,7 @@ class RelationalCatalog extends BaseSchemaCatalog implements TableCatalog {throws NoSuchTableException {checkTableNameIdentifier(ident);- Namespace fullNamespace = getTableFullNamespace(ident.namespace());+ Namespace fullNamespace = getEntityFullNamespace(ident.namespace());Map<String, String> queryParams = Maps.newHashMap();queryParams.put(PRIVILEGES, Joiner.on(",").join(requiredPrivilegeNames));TableResponse resp =@@ -191,7 +208,7 @@ class RelationalCatalog extends BaseSchemaCatalog implements TableCatalog {toDTOs(indexes));req.validate();- Namespace fullNamespace = getTableFullNamespace(ident.namespace());+ Namespace fullNamespace = getEntityFullNamespace(ident.namespace());TableResponse resp =restClient.post(formatTableRequestPath(fullNamespace),@@ -225,7 +242,7 @@ class RelationalCatalog extends BaseSchemaCatalog implements TableCatalog {TableUpdatesRequest updatesRequest = new TableUpdatesRequest(reqs);updatesRequest.validate();- Namespace fullNamespace = getTableFullNamespace(ident.namespace());+ Namespace fullNamespace = getEntityFullNamespace(ident.namespace());TableResponse resp =restClient.put(formatTableRequestPath(fullNamespace) + "/" + RESTUtils.encodeString(ident.name()),@@ -248,7 +265,7 @@ class RelationalCatalog extends BaseSchemaCatalog implements TableCatalog {public boolean dropTable(NameIdentifier ident) {checkTableNameIdentifier(ident);- Namespace fullNamespace = getTableFullNamespace(ident.namespace());+ Namespace fullNamespace = getEntityFullNamespace(ident.namespace());DropResponse resp =restClient.delete(formatTableRequestPath(fullNamespace) + "/" + RESTUtils.encodeString(ident.name()),@@ -269,7 +286,7 @@ class RelationalCatalog extends BaseSchemaCatalog implements TableCatalog {public boolean purgeTable(NameIdentifier ident) throws UnsupportedOperationException {checkTableNameIdentifier(ident);- Namespace fullNamespace = getTableFullNamespace(ident.namespace());+ Namespace fullNamespace = getEntityFullNamespace(ident.namespace());Map<String, String> params = new HashMap<>();params.put("purge", "true");DropResponse resp =@@ -283,8 +300,169 @@ class RelationalCatalog extends BaseSchemaCatalog implements TableCatalog {return resp.dropped();}+ /**+ * List all the views under the given Schema namespace.+ *+ * @param namespace The namespace to list the views under it. This namespace should have 1 level,+ * which is the schema name.+ * @return An array of {@link NameIdentifier} of the views under the given namespace.+ * @throws NoSuchSchemaException if the schema with specified namespace does not exist.+ */+ @Override+ public NameIdentifier[] listViews(Namespace namespace) throws NoSuchSchemaException {+ checkViewNamespace(namespace);++ Namespace fullNamespace = getEntityFullNamespace(namespace);+ EntityListResponse resp =+ restClient.get(+ formatViewRequestPath(fullNamespace),+ EntityListResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.viewErrorHandler());+ resp.validate();++ return Arrays.stream(resp.identifiers())+ .map(ident -> NameIdentifier.of(ident.namespace().level(2), ident.name()))+ .toArray(NameIdentifier[]::new);+ }++ /**+ * Load the view with specified identifier.+ *+ * @param ident The identifier of the view to load, which should be "schema.view" format.+ * @return The {@link View} with specified identifier.+ * @throws NoSuchViewException if the view with specified identifier does not exist.+ */+ @Override+ public View loadView(NameIdentifier ident) throws NoSuchViewException {+ checkViewNameIdentifier(ident);++ Namespace fullNamespace = getEntityFullNamespace(ident.namespace());+ ViewResponse resp =+ restClient.get(+ formatViewRequestPath(fullNamespace) + "/" + RESTUtils.encodeString(ident.name()),+ ViewResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.viewErrorHandler());+ resp.validate();++ return resp.getView();+ }++ /**+ * Create a new view with specified identifier, columns, representations and other metadata.+ *+ * @param ident The identifier of the view, which should be "schema.view" format.+ * @param comment The comment of the view, may be {@code null}.+ * @param columns The output columns of the view.+ * @param representations The representations of the view. At least one representation is+ * expected.+ * @param defaultCatalog The default catalog used to resolve unqualified identifiers referenced by+ * the view definition, or {@code null} if not set.+ * @param defaultSchema The default schema used to resolve unqualified identifiers referenced by+ * the view definition, or {@code null} if not set.+ * @param properties The properties of the view.+ * @return The created {@link View}.+ * @throws NoSuchSchemaException if the schema with specified namespace does not exist.+ * @throws ViewAlreadyExistsException if the view with specified identifier already exists.+ */+ @Override+ public View createView(+ NameIdentifier ident,+ String comment,+ Column[] columns,+ Representation[] representations,+ String defaultCatalog,+ String defaultSchema,+ Map<String, String> properties)+ throws NoSuchSchemaException, ViewAlreadyExistsException {+ checkViewNameIdentifier(ident);++ ColumnDTO[] columnDTOs = toDTOs(columns);+ RepresentationDTO[] representationDTOs = toDTOs(representations);++ ViewCreateRequest req =+ new ViewCreateRequest(+ ident.name(),+ comment,+ columnDTOs,+ representationDTOs,+ defaultCatalog,+ defaultSchema,+ properties);+ req.validate();++ Namespace fullNamespace = getEntityFullNamespace(ident.namespace());+ ViewResponse resp =+ restClient.post(+ formatViewRequestPath(fullNamespace),+ req,+ ViewResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.viewErrorHandler());+ resp.validate();++ return resp.getView();+ }++ /**+ * Alter the view with specified identifier by applying the changes.+ *+ * @param ident The identifier of the view, which should be "schema.view" format.+ * @param changes View changes to apply to the view.+ * @return The altered {@link View}.+ * @throws NoSuchViewException if the view with specified identifier does not exist.+ * @throws IllegalArgumentException if the changes are invalid or rejected by the implementation.+ */+ @Override+ public View alterView(NameIdentifier ident, ViewChange... changes)+ throws NoSuchViewException, IllegalArgumentException {+ checkViewNameIdentifier(ident);++ List<ViewUpdateRequest> reqs =+ Arrays.stream(changes)+ .map(RelationalCatalog::toViewUpdateRequest)+ .collect(Collectors.toList());+ ViewUpdatesRequest updatesRequest = new ViewUpdatesRequest(reqs);+ updatesRequest.validate();++ Namespace fullNamespace = getEntityFullNamespace(ident.namespace());+ ViewResponse resp =+ restClient.put(+ formatViewRequestPath(fullNamespace) + "/" + RESTUtils.encodeString(ident.name()),+ updatesRequest,+ ViewResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.viewErrorHandler());+ resp.validate();++ return resp.getView();+ }++ /**+ * Drop the view with specified identifier.+ *+ * @param ident The identifier of the view, which should be "schema.view" format.+ * @return true if the view is dropped successfully, false if the view does not exist.+ */+ @Override+ public boolean dropView(NameIdentifier ident) {+ checkViewNameIdentifier(ident);++ Namespace fullNamespace = getEntityFullNamespace(ident.namespace());+ DropResponse resp =+ restClient.delete(+ formatViewRequestPath(fullNamespace) + "/" + RESTUtils.encodeString(ident.name()),+ DropResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.viewErrorHandler());+ resp.validate();+ return resp.dropped();+ }+@VisibleForTestingstatic String formatTableRequestPath(Namespace ns) {+ checkFullSchemaNamespace(ns, "Table");Namespace schemaNs = Namespace.of(ns.level(0), ns.level(1));return new StringBuilder().append(formatSchemaRequestPath(schemaNs))@@ -319,13 +497,91 @@ class RelationalCatalog extends BaseSchemaCatalog implements TableCatalog {}/**- * Get the full namespace of the table with the given table's short namespace (schema name).+ * Format the request path for view operations.+ *+ * @param ns The full namespace in "metalake.catalog.schema" format.+ * @return The request path for view operations.+ */+ @VisibleForTesting+ static String formatViewRequestPath(Namespace ns) {+ checkFullSchemaNamespace(ns, "View");+ Namespace schemaNs = Namespace.of(ns.level(0), ns.level(1));+ return new StringBuilder()+ .append(formatSchemaRequestPath(schemaNs))+ .append("/")+ .append(RESTUtils.encodeString(ns.level(2)))+ .append("/views")+ .toString();+ }++ /**+ * Check whether the namespace of a view is valid, which should be "schema".*- * @param tableNamespace The table's short namespace, which is the schema name.- * @return full namespace of the table, which is "metalake.catalog.schema" format.+ * @param namespace The namespace to check.*/- private Namespace getTableFullNamespace(Namespace tableNamespace) {- return Namespace.of(this.catalogNamespace().level(0), this.name(), tableNamespace.level(0));+ static void checkViewNamespace(Namespace namespace) {+ Namespace.check(+ namespace != null && namespace.length() == 1,+ "View namespace must be non-null and have 1 level, the input namespace is %s",+ namespace);+ }++ /**+ * Check whether the NameIdentifier of a view is valid.+ *+ * @param ident The NameIdentifier to check, which should be "schema.view" format.+ */+ static void checkViewNameIdentifier(NameIdentifier ident) {+ NameIdentifier.check(ident != null, "NameIdentifier must not be null");+ NameIdentifier.check(+ ident.name() != null && !ident.name().isEmpty(), "NameIdentifier name must not be empty");+ checkViewNamespace(ident.namespace());+ }++ private static ViewUpdateRequest toViewUpdateRequest(ViewChange change) {+ if (change instanceof ViewChange.RenameView) {+ return new ViewUpdateRequest.RenameViewRequest(((ViewChange.RenameView) change).getNewName());++ } else if (change instanceof ViewChange.SetProperty) {+ ViewChange.SetProperty setProperty = (ViewChange.SetProperty) change;+ return new ViewUpdateRequest.SetViewPropertyRequest(+ setProperty.getProperty(), setProperty.getValue());++ } else if (change instanceof ViewChange.RemoveProperty) {+ return new ViewUpdateRequest.RemoveViewPropertyRequest(+ ((ViewChange.RemoveProperty) change).getProperty());++ } else if (change instanceof ViewChange.ReplaceView) {+ ViewChange.ReplaceView replace = (ViewChange.ReplaceView) change;+ return new ViewUpdateRequest.ReplaceViewRequest(+ toDTOs(replace.getColumns()),+ toDTOs(replace.getRepresentations()),+ replace.getDefaultCatalog(),+ replace.getDefaultSchema(),+ replace.getComment());++ } else {+ throw new IllegalArgumentException(+ "Unknown change type: " + change.getClass().getSimpleName());+ }+ }++ /**+ * Get the full namespace of an entity with the given short namespace (schema name).+ *+ * @param entityNamespace The entity's short namespace, which is the schema name.+ * @return full namespace of the entity, which is "metalake.catalog.schema" format.+ */+ private Namespace getEntityFullNamespace(Namespace entityNamespace) {+ return Namespace.of(this.catalogNamespace().level(0), this.name(), entityNamespace.level(0));+ }++ private static void checkFullSchemaNamespace(Namespace namespace, String entityType) {+ Namespace.check(+ namespace != null && namespace.length() == 3,+ "%s full namespace must be non-null and have 3 levels in the format \"metalake.catalog.schema\", the input namespace is %s",+ entityType,+ namespace);}/**diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestRelationalCatalogView.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestRelationalCatalogView.javanew file mode 100644index 0000000000..1690f9b6f2--- /dev/null+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestRelationalCatalogView.java@@ -0,0 +1,341 @@+/*+ * 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.client;++import static org.apache.hc.core5.http.HttpStatus.SC_CONFLICT;+import static org.apache.hc.core5.http.HttpStatus.SC_INTERNAL_SERVER_ERROR;+import static org.apache.hc.core5.http.HttpStatus.SC_NOT_FOUND;+import static org.apache.hc.core5.http.HttpStatus.SC_OK;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.google.common.collect.ImmutableList;+import com.google.common.collect.ImmutableMap;+import java.time.Instant;+import java.util.Collections;+import java.util.Map;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.dto.AuditDTO;+import org.apache.gravitino.dto.rel.ColumnDTO;+import org.apache.gravitino.dto.rel.RepresentationDTO;+import org.apache.gravitino.dto.rel.SQLRepresentationDTO;+import org.apache.gravitino.dto.rel.ViewDTO;+import org.apache.gravitino.dto.requests.ViewCreateRequest;+import org.apache.gravitino.dto.requests.ViewUpdateRequest;+import org.apache.gravitino.dto.requests.ViewUpdatesRequest;+import org.apache.gravitino.dto.responses.DropResponse;+import org.apache.gravitino.dto.responses.EntityListResponse;+import org.apache.gravitino.dto.responses.ErrorResponse;+import org.apache.gravitino.dto.responses.ViewResponse;+import org.apache.gravitino.exceptions.NoSuchSchemaException;+import org.apache.gravitino.exceptions.NoSuchViewException;+import org.apache.gravitino.exceptions.ViewAlreadyExistsException;+import org.apache.gravitino.rel.Dialects;+import org.apache.gravitino.rel.Representation;+import org.apache.gravitino.rel.SQLRepresentation;+import org.apache.gravitino.rel.View;+import org.apache.gravitino.rel.ViewCatalog;+import org.apache.gravitino.rel.ViewChange;+import org.apache.gravitino.rel.types.Types;+import org.apache.hc.core5.http.Method;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Unit tests for view operations exposed by {@link RelationalCatalog}. */+public class TestRelationalCatalogView extends TestRelationalCatalog {++ private static final String SCHEMA_NAME = "schema1";++ @Test+ public void testListViews() throws JsonProcessingException {+ NameIdentifier view1 = NameIdentifier.of(metalakeName, catalogName, SCHEMA_NAME, "view1");+ NameIdentifier view2 = NameIdentifier.of(metalakeName, catalogName, SCHEMA_NAME, "view2");+ String viewPath = withSlash(RelationalCatalog.formatViewRequestPath(view1.namespace()));++ // empty result+ EntityListResponse emptyResp = new EntityListResponse(new NameIdentifier[] {});+ buildMockResource(Method.GET, viewPath, null, emptyResp, SC_OK);+ NameIdentifier[] empty = catalog.asViewCatalog().listViews(Namespace.of(SCHEMA_NAME));+ Assertions.assertEquals(0, empty.length);++ // some results+ EntityListResponse resp = new EntityListResponse(new NameIdentifier[] {view1, view2});+ buildMockResource(Method.GET, viewPath, null, resp, SC_OK);+ NameIdentifier[] views = catalog.asViewCatalog().listViews(Namespace.of(SCHEMA_NAME));+ Assertions.assertEquals(2, views.length);+ Assertions.assertEquals(NameIdentifier.of(SCHEMA_NAME, "view1"), views[0]);+ Assertions.assertEquals(NameIdentifier.of(SCHEMA_NAME, "view2"), views[1]);++ // NoSuchSchemaException+ ErrorResponse errorResp =+ ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "schema not found");+ buildMockResource(Method.GET, viewPath, null, errorResp, SC_NOT_FOUND);+ ViewCatalog viewCatalog = catalog.asViewCatalog();+ Namespace ns = Namespace.of(SCHEMA_NAME);+ Throwable ex =+ Assertions.assertThrows(NoSuchSchemaException.class, () -> viewCatalog.listViews(ns));+ Assertions.assertTrue(ex.getMessage().contains("schema not found"));++ // Internal error+ ErrorResponse errorResp1 = ErrorResponse.internalError("internal error");+ buildMockResource(Method.GET, viewPath, null, errorResp1, SC_INTERNAL_SERVER_ERROR);+ Throwable ex1 =+ Assertions.assertThrows(RuntimeException.class, () -> viewCatalog.listViews(ns));+ Assertions.assertTrue(ex1.getMessage().contains("internal error"));+ }++ @Test+ public void testLoadView() throws JsonProcessingException {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, "view1");+ Namespace fullNamespace = Namespace.of(metalakeName, catalogName, SCHEMA_NAME);+ String viewPath =+ withSlash(RelationalCatalog.formatViewRequestPath(fullNamespace) + "/" + ident.name());++ ViewDTO expected = newViewDTO("view1", "comment", defaultColumns(), defaultRepresentations());+ ViewResponse resp = new ViewResponse(expected);+ buildMockResource(Method.GET, viewPath, null, resp, SC_OK);++ View loaded = catalog.asViewCatalog().loadView(ident);+ Assertions.assertEquals(expected.name(), loaded.name());+ Assertions.assertEquals(expected.comment(), loaded.comment());+ Assertions.assertEquals(expected.defaultCatalog(), loaded.defaultCatalog());+ Assertions.assertEquals(expected.defaultSchema(), loaded.defaultSchema());+ Assertions.assertEquals(expected.representations().length, loaded.representations().length);++ // NoSuchViewException+ ErrorResponse errorResp =+ ErrorResponse.notFound(NoSuchViewException.class.getSimpleName(), "view not found");+ buildMockResource(Method.GET, viewPath, null, errorResp, SC_NOT_FOUND);+ ViewCatalog viewCatalog = catalog.asViewCatalog();+ Throwable ex =+ Assertions.assertThrows(NoSuchViewException.class, () -> viewCatalog.loadView(ident));+ Assertions.assertTrue(ex.getMessage().contains("view not found"));+ }++ @Test+ public void testCreateView() throws JsonProcessingException {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, "view1");+ Namespace fullNamespace = Namespace.of(metalakeName, catalogName, SCHEMA_NAME);+ String viewPath = withSlash(RelationalCatalog.formatViewRequestPath(fullNamespace));++ ColumnDTO[] columns = defaultColumns();+ RepresentationDTO[] representations = defaultRepresentations();+ Map<String, String> properties = ImmutableMap.of("k1", "v1");++ ViewCreateRequest req =+ new ViewCreateRequest(+ ident.name(), "comment", columns, representations, null, null, properties);+ ViewDTO expected = newViewDTO("view1", "comment", columns, representations);+ ViewResponse resp = new ViewResponse(expected);+ buildMockResource(Method.POST, viewPath, req, resp, SC_OK);++ Representation[] apiRepresentations =+ new Representation[] {+ SQLRepresentation.builder().withDialect(Dialects.TRINO).withSql("SELECT 1").build()+ };+ View created =+ catalog+ .asViewCatalog()+ .createView(ident, "comment", columns, apiRepresentations, null, null, properties);+ Assertions.assertEquals(expected.name(), created.name());+ Assertions.assertEquals(expected.comment(), created.comment());++ // NoSuchSchemaException+ ErrorResponse schemaErr =+ ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "schema not found");+ buildMockResource(Method.POST, viewPath, req, schemaErr, SC_NOT_FOUND);+ ViewCatalog viewCatalog = catalog.asViewCatalog();+ Throwable ex =+ Assertions.assertThrows(+ NoSuchSchemaException.class,+ () ->+ viewCatalog.createView(+ ident, "comment", columns, apiRepresentations, null, null, properties));+ Assertions.assertTrue(ex.getMessage().contains("schema not found"));++ // ViewAlreadyExistsException+ ErrorResponse existsErr =+ ErrorResponse.alreadyExists(+ ViewAlreadyExistsException.class.getSimpleName(), "view already exists");+ buildMockResource(Method.POST, viewPath, req, existsErr, SC_CONFLICT);+ Throwable ex1 =+ Assertions.assertThrows(+ ViewAlreadyExistsException.class,+ () ->+ viewCatalog.createView(+ ident, "comment", columns, apiRepresentations, null, null, properties));+ Assertions.assertTrue(ex1.getMessage().contains("view already exists"));+ }++ @Test+ public void testAlterViewRename() throws JsonProcessingException {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, "view1");+ ViewDTO updated = newViewDTO("view2", "comment", defaultColumns(), defaultRepresentations());+ ViewUpdateRequest req = new ViewUpdateRequest.RenameViewRequest("view2");+ runAlterView(ident, req, updated, ViewChange.rename("view2"));+ }++ @Test+ public void testAlterViewSetProperty() throws JsonProcessingException {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, "view1");+ ViewDTO updated =+ ViewDTO.builder()+ .withName("view1")+ .withComment("comment")+ .withColumns(defaultColumns())+ .withRepresentations(defaultRepresentations())+ .withProperties(ImmutableMap.of("k1", "v1"))+ .withAudit(mockAudit())+ .build();+ ViewUpdateRequest req = new ViewUpdateRequest.SetViewPropertyRequest("k1", "v1");+ runAlterView(ident, req, updated, ViewChange.setProperty("k1", "v1"));+ }++ @Test+ public void testAlterViewRemoveProperty() throws JsonProcessingException {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, "view1");+ ViewDTO updated = newViewDTO("view1", "comment", defaultColumns(), defaultRepresentations());+ ViewUpdateRequest req = new ViewUpdateRequest.RemoveViewPropertyRequest("k1");+ runAlterView(ident, req, updated, ViewChange.removeProperty("k1"));+ }++ @Test+ public void testAlterViewReplace() throws JsonProcessingException {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, "view1");+ SQLRepresentationDTO newRep =+ SQLRepresentationDTO.builder().withDialect(Dialects.TRINO).withSql("SELECT 3").build();+ ColumnDTO[] newColumns = defaultColumns();+ RepresentationDTO[] newReps = new RepresentationDTO[] {newRep};+ ViewDTO updated = newViewDTO("view1", "new comment", newColumns, newReps);++ ViewUpdateRequest req =+ new ViewUpdateRequest.ReplaceViewRequest(newColumns, newReps, null, null, "new comment");+ SQLRepresentation newRepApi =+ SQLRepresentation.builder().withDialect(Dialects.TRINO).withSql("SELECT 3").build();+ runAlterView(+ ident,+ req,+ updated,+ ViewChange.replaceView(+ newColumns, new Representation[] {newRepApi}, null, null, "new comment"));+ }++ @Test+ public void testDropView() throws JsonProcessingException {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, "view1");+ Namespace fullNamespace = Namespace.of(metalakeName, catalogName, SCHEMA_NAME);+ String viewPath =+ withSlash(RelationalCatalog.formatViewRequestPath(fullNamespace) + "/" + ident.name());++ DropResponse resp = new DropResponse(true);+ buildMockResource(Method.DELETE, viewPath, null, resp, SC_OK);+ Assertions.assertTrue(catalog.asViewCatalog().dropView(ident));++ // return false+ DropResponse resp2 = new DropResponse(false);+ buildMockResource(Method.DELETE, viewPath, null, resp2, SC_OK);+ Assertions.assertFalse(catalog.asViewCatalog().dropView(ident));++ // internal error+ ErrorResponse errorResp = ErrorResponse.internalError("internal error");+ buildMockResource(Method.DELETE, viewPath, null, errorResp, SC_INTERNAL_SERVER_ERROR);+ Throwable ex =+ Assertions.assertThrows(+ RuntimeException.class, () -> catalog.asViewCatalog().dropView(ident));+ Assertions.assertTrue(ex.getMessage().contains("internal error"));+ }++ @Test+ public void testCreateViewRejectsNullRepresentations() {+ NameIdentifier ident = NameIdentifier.of(SCHEMA_NAME, "view1");++ ViewCatalog viewCatalog = catalog.asViewCatalog();+ IllegalArgumentException exception =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ viewCatalog.createView(+ ident, "comment", null, null, null, null, Collections.emptyMap()));+ Assertions.assertTrue(+ exception+ .getMessage()+ .contains("\"representations\" field is required and cannot be empty"));+ }++ @Test+ public void testListViewsRejectsInvalidNamespace() {+ ViewCatalog viewCatalog = catalog.asViewCatalog();+ IllegalArgumentException exception =+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> viewCatalog.listViews(Namespace.of("s1", "s2")));+ Assertions.assertTrue(exception.getMessage().contains("have 1 level"));+ }++ @Test+ public void testFormatViewRequestPathRejectsInvalidNamespaceLength() {+ IllegalArgumentException exception =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> RelationalCatalog.formatViewRequestPath(Namespace.of("schema1")));+ Assertions.assertTrue(exception.getMessage().contains("have 3 levels"));+ }++ private void runAlterView(+ NameIdentifier ident, ViewUpdateRequest req, ViewDTO updated, ViewChange change)+ throws JsonProcessingException {+ Namespace fullNamespace = Namespace.of(metalakeName, catalogName, ident.namespace().level(0));+ String viewPath =+ withSlash(RelationalCatalog.formatViewRequestPath(fullNamespace) + "/" + ident.name());+ ViewUpdatesRequest updatesRequest = new ViewUpdatesRequest(ImmutableList.of(req));+ ViewResponse resp = new ViewResponse(updated);+ buildMockResource(Method.PUT, viewPath, updatesRequest, resp, SC_OK);++ View altered = catalog.asViewCatalog().alterView(ident, change);+ Assertions.assertEquals(updated.name(), altered.name());+ Assertions.assertEquals(updated.comment(), altered.comment());+ Assertions.assertEquals(updated.properties(), altered.properties());+ Assertions.assertEquals(updated.representations().length, altered.representations().length);+ }++ private static ColumnDTO[] defaultColumns() {+ return new ColumnDTO[] {createMockColumn("col1", Types.IntegerType.get(), "c1")};+ }++ private static RepresentationDTO[] defaultRepresentations() {+ return new RepresentationDTO[] {+ SQLRepresentationDTO.builder().withDialect(Dialects.TRINO).withSql("SELECT 1").build()+ };+ }++ private static ViewDTO newViewDTO(+ String name, String comment, ColumnDTO[] columns, RepresentationDTO[] representations) {+ return ViewDTO.builder()+ .withName(name)+ .withComment(comment)+ .withColumns(columns)+ .withRepresentations(representations)+ .withProperties(Collections.emptyMap())+ .withAudit(mockAudit())+ .build();+ }++ private static AuditDTO mockAudit() {+ return AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build();+ }+}diff --git a/common/src/main/java/org/apache/gravitino/dto/rel/ViewDTO.java b/common/src/main/java/org/apache/gravitino/dto/rel/ViewDTO.javaindex 519f79112f..c4e6b65dc9 100644--- a/common/src/main/java/org/apache/gravitino/dto/rel/ViewDTO.java+++ b/common/src/main/java/org/apache/gravitino/dto/rel/ViewDTO.java@@ -28,6 +28,7 @@ import javax.annotation.Nullable;import lombok.EqualsAndHashCode;import lombok.ToString;import org.apache.gravitino.dto.AuditDTO;+import org.apache.gravitino.dto.util.DTOConverters;import org.apache.gravitino.rel.Column;import org.apache.gravitino.rel.Representation;import org.apache.gravitino.rel.View;@@ -104,7 +105,7 @@ public class ViewDTO implements View {@Overridepublic Representation[] representations() {- return representations == null ? new RepresentationDTO[0] : representations;+ return DTOConverters.fromDTOs(representations);}@Overridediff --git a/common/src/test/java/org/apache/gravitino/dto/rel/TestViewDTO.java b/common/src/test/java/org/apache/gravitino/dto/rel/TestViewDTO.javaindex d0bd9a60ec..8bb39c0edf 100644--- a/common/src/test/java/org/apache/gravitino/dto/rel/TestViewDTO.java+++ b/common/src/test/java/org/apache/gravitino/dto/rel/TestViewDTO.java@@ -21,8 +21,10 @@ package org.apache.gravitino.dto.rel;import com.fasterxml.jackson.core.JsonProcessingException;import java.time.Instant;import java.util.Map;+import java.util.Optional;import org.apache.gravitino.dto.AuditDTO;import org.apache.gravitino.json.JsonUtils;+import org.apache.gravitino.rel.SQLRepresentation;import org.apache.gravitino.rel.types.Types;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;@@ -59,7 +61,7 @@ public class TestViewDTO {Assertions.assertEquals("sch", deserialized.defaultSchema());Assertions.assertEquals(Map.of("k", "v"), deserialized.properties());Assertions.assertEquals(1, deserialized.representations().length);- Assertions.assertInstanceOf(SQLRepresentationDTO.class, deserialized.representations()[0]);+ Assertions.assertInstanceOf(SQLRepresentation.class, deserialized.representations()[0]);}@Test@@ -126,7 +128,7 @@ public class TestViewDTO {Assertions.assertEquals("v_raw", dto.name());Assertions.assertEquals("raw comment", dto.comment());Assertions.assertEquals(1, dto.representations().length);- Assertions.assertInstanceOf(SQLRepresentationDTO.class, dto.representations()[0]);+ Assertions.assertInstanceOf(SQLRepresentation.class, dto.representations()[0]);Assertions.assertEquals("cat", dto.defaultCatalog());Assertions.assertEquals("sch", dto.defaultSchema());Assertions.assertEquals("v", dto.properties().get("k"));@@ -148,6 +150,37 @@ public class TestViewDTO {Assertions.assertEquals(0, dto.columns().length);}+ @Test+ public void testSqlForWithSQLRepresentationDTO() throws JsonProcessingException {+ ViewDTO dto =+ ViewDTO.builder()+ .withName("v1")+ .withRepresentations(+ new RepresentationDTO[] {+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 1").build(),+ SQLRepresentationDTO.builder().withDialect("spark").withSql("SELECT 2").build()+ })+ .withAudit(audit())+ .build();++ // Serialize and deserialize to simulate client-side REST response handling+ String json = JsonUtils.objectMapper().writeValueAsString(dto);+ ViewDTO deserialized = JsonUtils.objectMapper().readValue(json, ViewDTO.class);++ Optional<SQLRepresentation> trino = deserialized.sqlFor("trino");+ Assertions.assertTrue(trino.isPresent());+ Assertions.assertEquals("trino", trino.get().dialect());+ Assertions.assertEquals("SELECT 1", trino.get().sql());++ // Case-insensitive match+ Assertions.assertTrue(deserialized.sqlFor("TRINO").isPresent());+ Assertions.assertTrue(deserialized.sqlFor("Trino").isPresent());++ // Missing dialect returns empty+ Assertions.assertFalse(deserialized.sqlFor("hive").isPresent());+ Assertions.assertFalse(deserialized.sqlFor(null).isPresent());+ }+private AuditDTO audit() {return AuditDTO.builder().withCreator("u1").withCreateTime(Instant.now()).build();}diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestViewOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestViewOperations.javaindex 063d4c02e7..2bd2c0df7e 100644--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestViewOperations.java+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestViewOperations.java@@ -203,8 +203,8 @@ public class TestViewOperations extends BaseOperationsTest {Assertions.assertNull(viewDTO.defaultCatalog());Assertions.assertNull(viewDTO.defaultSchema());Assertions.assertEquals(1, viewDTO.representations().length);- Assertions.assertTrue(viewDTO.representations()[0] instanceof SQLRepresentationDTO);- SQLRepresentationDTO sqlRep = (SQLRepresentationDTO) viewDTO.representations()[0];+ Assertions.assertTrue(viewDTO.representations()[0] instanceof SQLRepresentation);+ SQLRepresentation sqlRep = (SQLRepresentation) viewDTO.representations()[0];Assertions.assertEquals("trino", sqlRep.dialect());Assertions.assertEquals("SELECT 1", sqlRep.sql());