Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#10981] feat(common,server): add REST endpoints and DTOs for logical views (#10982)

mchades0b76771230ea
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.java
index 69ef28d808..6db44da3c4 100644
--- a/common/src/main/java/org/apache/gravitino/dto/rel/RepresentationDTO.java
+++ b/common/src/main/java/org/apache/gravitino/dto/rel/RepresentationDTO.java
@@ -18,16 +18,22 @@
*/
package org.apache.gravitino.dto.rel;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
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. */
+/**
+ * A DTO mirroring {@link org.apache.gravitino.rel.Representation}. Representation DTOs are
+ * serialized with a {@code type} discriminator so Jackson can deserialize into the correct subtype.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
- include = JsonTypeInfo.As.PROPERTY,
+ include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = "type",
+ visible = true,
defaultImpl = SQLRepresentationDTO.class)
@JsonSubTypes({
@JsonSubTypes.Type(value = SQLRepresentationDTO.class, name = Representation.TYPE_SQL)
@@ -38,23 +44,29 @@ public abstract class RepresentationDTO implements Representation {
protected RepresentationDTO() {}
/**
- * Converts this DTO to a representation object.
+ * Validates the fields of this representation.
*
- * @return The representation object.
+ * @throws IllegalArgumentException If the representation is invalid.
*/
- public abstract Representation toRepresentation();
+ public abstract void validate() throws IllegalArgumentException;
/**
- * Creates a representation DTO from a representation object.
+ * Creates a {@link RepresentationDTO} from a {@link Representation} domain object.
*
- * @param representation The representation object.
+ * @param representation The representation domain object.
* @return The representation DTO.
*/
public static RepresentationDTO fromRepresentation(Representation representation) {
+ if (representation instanceof RepresentationDTO) {
+ return (RepresentationDTO) representation;
+ }
if (representation instanceof SQLRepresentation) {
- return SQLRepresentationDTO.fromSQLRepresentation((SQLRepresentation) representation);
+ SQLRepresentation sqlRepresentation = (SQLRepresentation) representation;
+ return SQLRepresentationDTO.builder()
+ .withDialect(sqlRepresentation.dialect())
+ .withSql(sqlRepresentation.sql())
+ .build();
}
-
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.java
index c53f9798d9..995f638b30 100644
--- a/common/src/main/java/org/apache/gravitino/dto/rel/SQLRepresentationDTO.java
+++ b/common/src/main/java/org/apache/gravitino/dto/rel/SQLRepresentationDTO.java
@@ -18,16 +18,22 @@
*/
package org.apache.gravitino.dto.rel;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
-import lombok.EqualsAndHashCode;
-import lombok.Getter;
+import com.google.common.base.Preconditions;
+import java.util.Objects;
+import org.apache.commons.lang3.StringUtils;
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 {
+/**
+ * A DTO mirroring {@link org.apache.gravitino.rel.SQLRepresentation}. Represents a SQL-based view
+ * definition for a particular dialect.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public final class SQLRepresentationDTO extends RepresentationDTO {
+
+ @JsonProperty("type")
+ private final String type = Representation.TYPE_SQL;
@JsonProperty("dialect")
private String dialect;
@@ -35,36 +41,112 @@ public class SQLRepresentationDTO extends RepresentationDTO {
@JsonProperty("sql")
private String sql;
- private SQLRepresentationDTO() {}
+ private SQLRepresentationDTO() {
+ super();
+ }
+
+ private SQLRepresentationDTO(String dialect, String sql) {
+ this.dialect = dialect;
+ this.sql = sql;
+ }
/**
- * Creates a SQL representation DTO.
+ * Creates a new {@link Builder}.
*
- * @param dialect SQL dialect.
- * @param sql SQL body.
+ * @return A new builder instance.
*/
- public SQLRepresentationDTO(String dialect, String sql) {
- this.dialect = dialect;
- this.sql = sql;
+ public static Builder builder() {
+ return new Builder();
}
@Override
public String type() {
- return Representation.TYPE_SQL;
+ return type;
}
- @Override
- public SQLRepresentation toRepresentation() {
- return SQLRepresentation.builder().withDialect(dialect).withSql(sql).build();
+ /**
+ * Returns the SQL dialect of this representation.
+ *
+ * @return The dialect identifier.
+ */
+ public String dialect() {
+ return dialect;
}
/**
- * Creates SQL representation DTO from SQL representation.
+ * Returns the SQL text of this representation.
*
- * @param representation SQL representation.
- * @return SQL representation DTO.
+ * @return The SQL text.
*/
- public static SQLRepresentationDTO fromSQLRepresentation(SQLRepresentation representation) {
- return new SQLRepresentationDTO(representation.dialect(), representation.sql());
+ public String sql() {
+ return sql;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(dialect), "\"dialect\" field is required and cannot be empty");
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(sql), "\"sql\" field is required and cannot be empty");
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof SQLRepresentationDTO)) return false;
+ SQLRepresentationDTO that = (SQLRepresentationDTO) o;
+ return Objects.equals(dialect, that.dialect) && Objects.equals(sql, that.sql);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(dialect, sql);
+ }
+
+ @Override
+ public String toString() {
+ return "SQLRepresentationDTO{" + "dialect='" + dialect + '\'' + ", sql='" + sql + '\'' + '}';
+ }
+
+ /** Builder for {@link SQLRepresentationDTO}. */
+ public static final class Builder {
+
+ private String dialect;
+ private String sql;
+
+ private Builder() {}
+
+ /**
+ * Sets the dialect.
+ *
+ * @param dialect The dialect identifier.
+ * @return This builder.
+ */
+ public Builder withDialect(String dialect) {
+ this.dialect = dialect;
+ return this;
+ }
+
+ /**
+ * Sets the SQL text.
+ *
+ * @param sql The SQL text.
+ * @return This builder.
+ */
+ public Builder withSql(String sql) {
+ this.sql = sql;
+ return this;
+ }
+
+ /**
+ * Builds a new {@link SQLRepresentationDTO}.
+ *
+ * @return The constructed instance.
+ */
+ public SQLRepresentationDTO build() {
+ SQLRepresentationDTO representation = new SQLRepresentationDTO(dialect, sql);
+ representation.validate();
+ return representation;
+ }
}
}
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.java
new file mode 100644
index 0000000000..519f79112f
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/rel/ViewDTO.java
@@ -0,0 +1,270 @@
+/*
+ * 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.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Map;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+import org.apache.gravitino.dto.AuditDTO;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Representation;
+import org.apache.gravitino.rel.View;
+
+/** Represents a View DTO (Data Transfer Object). */
+@JsonIgnoreProperties(ignoreUnknown = true)
+@EqualsAndHashCode
+@ToString
+public class ViewDTO implements View {
+
+ @JsonProperty("name")
+ private String name;
+
+ @JsonProperty("comment")
+ @Nullable
+ private String comment;
+
+ @JsonProperty("columns")
+ private ColumnDTO[] columns;
+
+ @JsonProperty("representations")
+ private RepresentationDTO[] representations;
+
+ @JsonProperty("defaultCatalog")
+ @Nullable
+ private String defaultCatalog;
+
+ @JsonProperty("defaultSchema")
+ @Nullable
+ private String defaultSchema;
+
+ @JsonProperty("properties")
+ @Nullable
+ private Map<String, String> properties;
+
+ @JsonProperty("audit")
+ private AuditDTO audit;
+
+ private ViewDTO() {}
+
+ private ViewDTO(
+ String name,
+ @Nullable String comment,
+ ColumnDTO[] columns,
+ RepresentationDTO[] representations,
+ @Nullable String defaultCatalog,
+ @Nullable String defaultSchema,
+ @Nullable Map<String, String> properties,
+ AuditDTO audit) {
+ this.name = name;
+ this.comment = comment;
+ this.columns = columns;
+ this.representations = representations;
+ this.defaultCatalog = defaultCatalog;
+ this.defaultSchema = defaultSchema;
+ this.properties = properties;
+ this.audit = audit;
+ }
+
+ @Override
+ public String name() {
+ return name;
+ }
+
+ @Override
+ public String comment() {
+ return comment;
+ }
+
+ @Override
+ public Column[] columns() {
+ return columns == null ? new ColumnDTO[0] : columns;
+ }
+
+ @Override
+ public Representation[] representations() {
+ return representations == null ? new RepresentationDTO[0] : representations;
+ }
+
+ @Override
+ public String defaultCatalog() {
+ return defaultCatalog;
+ }
+
+ @Override
+ public String defaultSchema() {
+ return defaultSchema;
+ }
+
+ @Override
+ public Map<String, String> properties() {
+ return properties == null ? Collections.emptyMap() : properties;
+ }
+
+ @Override
+ public AuditDTO auditInfo() {
+ return audit;
+ }
+
+ /**
+ * Creates a new {@link Builder} to build a {@link ViewDTO}.
+ *
+ * @return A new builder instance.
+ */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ /** Builder class for constructing {@link ViewDTO} instances. */
+ public static class Builder {
+
+ private String name;
+ @Nullable private String comment;
+ private ColumnDTO[] columns;
+ private RepresentationDTO[] representations;
+ @Nullable private String defaultCatalog;
+ @Nullable private String defaultSchema;
+ @Nullable private Map<String, String> properties;
+ private AuditDTO audit;
+
+ private Builder() {}
+
+ /**
+ * Sets the view name.
+ *
+ * @param name The view name.
+ * @return This builder.
+ */
+ public Builder withName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ /**
+ * Sets the view comment.
+ *
+ * @param comment The view comment.
+ * @return This builder.
+ */
+ public Builder withComment(@Nullable String comment) {
+ this.comment = comment;
+ return this;
+ }
+
+ /**
+ * Sets the view columns.
+ *
+ * @param columns The view output columns.
+ * @return This builder.
+ */
+ public Builder withColumns(ColumnDTO[] columns) {
+ this.columns = columns;
+ return this;
+ }
+
+ /**
+ * Sets the view representations.
+ *
+ * @param representations The view representations.
+ * @return This builder.
+ */
+ public Builder withRepresentations(RepresentationDTO[] representations) {
+ this.representations = representations;
+ return this;
+ }
+
+ /**
+ * Sets the default catalog used to resolve unqualified identifiers in view representations.
+ *
+ * @param defaultCatalog The default catalog, or {@code null} if not set.
+ * @return This builder.
+ */
+ public Builder withDefaultCatalog(@Nullable String defaultCatalog) {
+ this.defaultCatalog = defaultCatalog;
+ return this;
+ }
+
+ /**
+ * Sets the default schema used to resolve unqualified identifiers in view representations.
+ *
+ * @param defaultSchema The default schema, or {@code null} if not set.
+ * @return This builder.
+ */
+ public Builder withDefaultSchema(@Nullable String defaultSchema) {
+ this.defaultSchema = defaultSchema;
+ return this;
+ }
+
+ /**
+ * Sets the view properties.
+ *
+ * @param properties The view properties.
+ * @return This builder.
+ */
+ public Builder withProperties(@Nullable Map<String, String> properties) {
+ this.properties = properties;
+ return this;
+ }
+
+ /**
+ * Sets the audit information for the view.
+ *
+ * @param audit The audit information.
+ * @return This builder.
+ */
+ public Builder withAudit(AuditDTO audit) {
+ this.audit = audit;
+ return this;
+ }
+
+ /**
+ * Builds a new {@link ViewDTO}.
+ *
+ * @return The constructed instance.
+ * @throws IllegalArgumentException If required fields are missing.
+ */
+ public ViewDTO build() {
+ Preconditions.checkArgument(name != null && !name.isEmpty(), "name cannot be null or empty");
+ Preconditions.checkArgument(audit != null, "audit cannot be null");
+ Preconditions.checkArgument(
+ representations != null && representations.length > 0,
+ "representations cannot be null or empty");
+ Arrays.stream(representations)
+ .forEach(
+ rep -> {
+ Preconditions.checkArgument(rep != null, "representation must not be null");
+ rep.validate();
+ });
+ return new ViewDTO(
+ name,
+ comment,
+ columns == null ? new ColumnDTO[0] : columns,
+ representations,
+ defaultCatalog,
+ defaultSchema,
+ properties,
+ audit);
+ }
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/ViewCreateRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/ViewCreateRequest.java
new file mode 100644
index 0000000000..8c0d02305a
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/requests/ViewCreateRequest.java
@@ -0,0 +1,146 @@
+/*
+ * 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.requests;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nullable;
+import lombok.Builder;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import lombok.extern.jackson.Jacksonized;
+import org.apache.commons.lang3.StringUtils;
+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.rest.RESTRequest;
+
+/** Represents a request to create a view. */
+@Getter
+@EqualsAndHashCode
+@ToString
+@Builder
+@Jacksonized
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class ViewCreateRequest implements RESTRequest {
+
+ @JsonProperty("name")
+ private final String name;
+
+ @JsonProperty("comment")
+ @Nullable
+ private final String comment;
+
+ @JsonProperty("columns")
+ private final ColumnDTO[] columns;
+
+ @JsonProperty("representations")
+ private final RepresentationDTO[] representations;
+
+ @JsonProperty("defaultCatalog")
+ @Nullable
+ private final String defaultCatalog;
+
+ @JsonProperty("defaultSchema")
+ @Nullable
+ private final String defaultSchema;
+
+ @JsonProperty("properties")
+ @Nullable
+ private final Map<String, String> properties;
+
+ /** Default constructor for Jackson deserialization. */
+ public ViewCreateRequest() {
+ this(null, null, null, null, null, null, null);
+ }
+
+ /**
+ * Creates a new {@link ViewCreateRequest}.
+ *
+ * @param name The name of the view.
+ * @param comment The comment of the view.
+ * @param columns The output columns of the view.
+ * @param representations The representations of the view.
+ * @param defaultCatalog The default catalog used to resolve unqualified identifiers in view
+ * representations.
+ * @param defaultSchema The default schema used to resolve unqualified identifiers in view
+ * representations.
+ * @param properties The properties of the view.
+ */
+ public ViewCreateRequest(
+ String name,
+ @Nullable String comment,
+ ColumnDTO[] columns,
+ RepresentationDTO[] representations,
+ @Nullable String defaultCatalog,
+ @Nullable String defaultSchema,
+ @Nullable Map<String, String> properties) {
+ this.name = name;
+ this.comment = comment;
+ this.columns = columns;
+ this.representations = representations;
+ this.defaultCatalog = defaultCatalog;
+ this.defaultSchema = defaultSchema;
+ this.properties = properties;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(name), "\"name\" field is required and cannot be empty");
+ Preconditions.checkArgument(
+ representations != null && representations.length > 0,
+ "\"representations\" field is required and cannot be empty");
+ Arrays.stream(representations)
+ .forEach(
+ rep -> {
+ Preconditions.checkArgument(rep != null, "representation must not be null");
+ rep.validate();
+ });
+ if (columns != null) {
+ Arrays.stream(columns)
+ .forEach(
+ column -> {
+ Preconditions.checkArgument(column != null, "column must not be null");
+ column.validate();
+ });
+ }
+
+ validateNoDuplicateDialects(representations);
+ }
+
+ static void validateNoDuplicateDialects(RepresentationDTO[] representations) {
+ Set<String> seenDialects = new HashSet<>();
+ Arrays.stream(representations)
+ .filter(rep -> rep instanceof SQLRepresentationDTO)
+ .map(rep -> ((SQLRepresentationDTO) rep).dialect())
+ .forEach(
+ dialect ->
+ Preconditions.checkArgument(
+ seenDialects.add(dialect),
+ "Duplicate SQL representation dialect: %s",
+ dialect));
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/ViewUpdateRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/ViewUpdateRequest.java
new file mode 100644
index 0000000000..c203086bd9
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/requests/ViewUpdateRequest.java
@@ -0,0 +1,256 @@
+/*
+ * 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.requests;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import com.google.common.base.Preconditions;
+import java.util.Arrays;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.dto.rel.ColumnDTO;
+import org.apache.gravitino.dto.rel.RepresentationDTO;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.rel.ViewChange;
+import org.apache.gravitino.rest.RESTRequest;
+
+/** Represents a request to update a view. */
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
+@JsonSubTypes({
+ @JsonSubTypes.Type(value = ViewUpdateRequest.RenameViewRequest.class, name = "rename"),
+ @JsonSubTypes.Type(value = ViewUpdateRequest.SetViewPropertyRequest.class, name = "setProperty"),
+ @JsonSubTypes.Type(
+ value = ViewUpdateRequest.RemoveViewPropertyRequest.class,
+ name = "removeProperty"),
+ @JsonSubTypes.Type(value = ViewUpdateRequest.ReplaceViewRequest.class, name = "replaceView")
+})
+public interface ViewUpdateRequest extends RESTRequest {
+
+ /**
+ * The view change represented by this request.
+ *
+ * @return An instance of {@link ViewChange}.
+ */
+ ViewChange viewChange();
+
+ /** Represents a request to rename a view. */
+ @EqualsAndHashCode
+ @ToString
+ @Getter
+ class RenameViewRequest implements ViewUpdateRequest {
+
+ @JsonProperty("newName")
+ private final String newName;
+
+ /**
+ * Constructor for RenameViewRequest.
+ *
+ * @param newName The new name of the view.
+ */
+ public RenameViewRequest(String newName) {
+ this.newName = newName;
+ }
+
+ /** Default constructor for Jackson deserialization. */
+ public RenameViewRequest() {
+ this(null);
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(newName), "\"newName\" field is required and cannot be empty");
+ }
+
+ @Override
+ public ViewChange viewChange() {
+ return ViewChange.rename(newName);
+ }
+ }
+
+ /** Represents a request to set a property of a view. */
+ @EqualsAndHashCode
+ @ToString
+ @Getter
+ class SetViewPropertyRequest implements ViewUpdateRequest {
+
+ @JsonProperty("property")
+ private final String property;
+
+ @JsonProperty("value")
+ private final String value;
+
+ /**
+ * Constructor for SetViewPropertyRequest.
+ *
+ * @param property The property to set.
+ * @param value The value of the property.
+ */
+ public SetViewPropertyRequest(String property, String value) {
+ this.property = property;
+ this.value = value;
+ }
+
+ /** Default constructor for Jackson deserialization. */
+ public SetViewPropertyRequest() {
+ this(null, null);
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(property), "\"property\" field is required and cannot be empty");
+ Preconditions.checkArgument(value != null, "\"value\" field is required and cannot be null");
+ }
+
+ @Override
+ public ViewChange viewChange() {
+ return ViewChange.setProperty(property, value);
+ }
+ }
+
+ /** Represents a request to remove a property of a view. */
+ @EqualsAndHashCode
+ @ToString
+ @Getter
+ class RemoveViewPropertyRequest implements ViewUpdateRequest {
+
+ @JsonProperty("property")
+ private final String property;
+
+ /**
+ * Constructor for RemoveViewPropertyRequest.
+ *
+ * @param property The property to remove.
+ */
+ public RemoveViewPropertyRequest(String property) {
+ this.property = property;
+ }
+
+ /** Default constructor for Jackson deserialization. */
+ public RemoveViewPropertyRequest() {
+ this(null);
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(property), "\"property\" field is required and cannot be empty");
+ }
+
+ @Override
+ public ViewChange viewChange() {
+ return ViewChange.removeProperty(property);
+ }
+ }
+
+ /**
+ * Represents a request to atomically replace the body (columns, representations, default catalog,
+ * default schema and comment) of a view. View name and properties are not affected.
+ */
+ @EqualsAndHashCode
+ @ToString
+ @Getter
+ class ReplaceViewRequest implements ViewUpdateRequest {
+
+ @JsonProperty("columns")
+ private final ColumnDTO[] columns;
+
+ @JsonProperty("representations")
+ private final RepresentationDTO[] representations;
+
+ @JsonProperty("defaultCatalog")
+ @Nullable
+ private final String defaultCatalog;
+
+ @JsonProperty("defaultSchema")
+ @Nullable
+ private final String defaultSchema;
+
+ @JsonProperty("comment")
+ @Nullable
+ private final String comment;
+
+ /**
+ * Constructor for ReplaceViewRequest.
+ *
+ * @param columns The new output columns of the view.
+ * @param representations The new representations of the view.
+ * @param defaultCatalog The new default catalog, or {@code null} to unset it.
+ * @param defaultSchema The new default schema, or {@code null} to unset it.
+ * @param comment The new comment, or {@code null} to unset it.
+ */
+ public ReplaceViewRequest(
+ ColumnDTO[] columns,
+ RepresentationDTO[] representations,
+ @Nullable String defaultCatalog,
+ @Nullable String defaultSchema,
+ @Nullable String comment) {
+ this.columns = columns;
+ this.representations = representations;
+ this.defaultCatalog = defaultCatalog;
+ this.defaultSchema = defaultSchema;
+ this.comment = comment;
+ }
+
+ /** Default constructor for Jackson deserialization. */
+ public ReplaceViewRequest() {
+ this(null, null, null, null, null);
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ representations != null && representations.length > 0,
+ "\"representations\" field is required and cannot be empty");
+ Arrays.stream(representations)
+ .forEach(
+ rep -> {
+ Preconditions.checkArgument(rep != null, "representation must not be null");
+ rep.validate();
+ });
+ if (columns != null) {
+ Arrays.stream(columns)
+ .forEach(
+ column -> {
+ Preconditions.checkArgument(column != null, "column must not be null");
+ column.validate();
+ });
+ }
+
+ ViewCreateRequest.validateNoDuplicateDialects(representations);
+ }
+
+ @Override
+ public ViewChange viewChange() {
+ return ViewChange.replaceView(
+ columns == null ? new ColumnDTO[0] : columns,
+ DTOConverters.fromDTOs(representations),
+ defaultCatalog,
+ defaultSchema,
+ comment);
+ }
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/requests/ViewUpdatesRequest.java b/common/src/main/java/org/apache/gravitino/dto/requests/ViewUpdatesRequest.java
new file mode 100644
index 0000000000..8cf29b7788
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/requests/ViewUpdatesRequest.java
@@ -0,0 +1,58 @@
+/*
+ * 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.requests;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import java.util.List;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.gravitino.rest.RESTRequest;
+
+/** Represents a request to update a view. */
+@Getter
+@EqualsAndHashCode
+@ToString
+public class ViewUpdatesRequest implements RESTRequest {
+
+ @JsonProperty("updates")
+ private final List<ViewUpdateRequest> updates;
+
+ /**
+ * Creates a new ViewUpdatesRequest.
+ *
+ * @param updates The updates to apply to the view.
+ */
+ public ViewUpdatesRequest(List<ViewUpdateRequest> updates) {
+ this.updates = updates;
+ }
+
+ /** Default constructor used by Jackson deserializer. */
+ public ViewUpdatesRequest() {
+ this(null);
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(updates != null, "updates must not be null");
+ Preconditions.checkArgument(!updates.isEmpty(), "updates must not be empty");
+ updates.forEach(RESTRequest::validate);
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/responses/ViewResponse.java b/common/src/main/java/org/apache/gravitino/dto/responses/ViewResponse.java
new file mode 100644
index 0000000000..08aabf8fd7
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/responses/ViewResponse.java
@@ -0,0 +1,66 @@
+/*
+ * 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.responses;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.dto.rel.ViewDTO;
+
+/** Represents a response for a view. */
+@Getter
+@ToString
+@EqualsAndHashCode(callSuper = true)
+public class ViewResponse extends BaseResponse {
+
+ @JsonProperty("view")
+ private final ViewDTO view;
+
+ /**
+ * Creates a new ViewResponse.
+ *
+ * @param view The view DTO object.
+ */
+ public ViewResponse(ViewDTO view) {
+ super(0);
+ this.view = view;
+ }
+
+ /** Default constructor used by Jackson deserializer. */
+ public ViewResponse() {
+ super();
+ this.view = null;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ super.validate();
+
+ Preconditions.checkArgument(view != null, "view must not be null");
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(view.name()), "view 'name' must not be null or empty");
+ Preconditions.checkArgument(view.auditInfo() != null, "view 'audit' must not be null");
+ Preconditions.checkArgument(
+ view.representations() != null && view.representations().length > 0,
+ "view 'representations' must not be null or empty");
+ }
+}
diff --git a/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java b/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java
index 77e04605fe..e9ee2226dd 100644
--- a/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java
+++ b/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java
@@ -62,8 +62,11 @@ import org.apache.gravitino.dto.model.ModelVersionDTO;
import org.apache.gravitino.dto.policy.PolicyContentDTO;
import org.apache.gravitino.dto.rel.ColumnDTO;
import org.apache.gravitino.dto.rel.DistributionDTO;
+import org.apache.gravitino.dto.rel.RepresentationDTO;
+import org.apache.gravitino.dto.rel.SQLRepresentationDTO;
import org.apache.gravitino.dto.rel.SortOrderDTO;
import org.apache.gravitino.dto.rel.TableDTO;
+import org.apache.gravitino.dto.rel.ViewDTO;
import org.apache.gravitino.dto.rel.expressions.FieldReferenceDTO;
import org.apache.gravitino.dto.rel.expressions.FuncExpressionDTO;
import org.apache.gravitino.dto.rel.expressions.FunctionArg;
@@ -101,7 +104,10 @@ import org.apache.gravitino.policy.IcebergDataCompactionContent;
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.Table;
+import org.apache.gravitino.rel.View;
import org.apache.gravitino.rel.expressions.Expression;
import org.apache.gravitino.rel.expressions.FunctionExpression;
import org.apache.gravitino.rel.expressions.NamedReference;
@@ -289,6 +295,69 @@ public class DTOConverters {
.build();
}
+ /**
+ * Converts a {@link View} implementation to a {@link ViewDTO}.
+ *
+ * @param view The view implementation.
+ * @return The view DTO.
+ */
+ public static ViewDTO toDTO(View view) {
+ return ViewDTO.builder()
+ .withName(view.name())
+ .withComment(view.comment())
+ .withColumns(
+ Arrays.stream(view.columns()).map(DTOConverters::toDTO).toArray(ColumnDTO[]::new))
+ .withRepresentations(toDTOs(view.representations()))
+ .withDefaultCatalog(view.defaultCatalog())
+ .withDefaultSchema(view.defaultSchema())
+ .withProperties(view.properties())
+ .withAudit(toDTO(view.auditInfo()))
+ .build();
+ }
+
+ /**
+ * Converts a {@link Representation} implementation to a {@link RepresentationDTO}.
+ *
+ * @param representation The representation implementation.
+ * @return The representation DTO.
+ */
+ public static RepresentationDTO toDTO(Representation representation) {
+ if (representation instanceof RepresentationDTO) {
+ return (RepresentationDTO) representation;
+ }
+ if (representation instanceof SQLRepresentation) {
+ return toDTO((SQLRepresentation) representation);
+ }
+ throw new IllegalArgumentException(
+ "Unsupported representation type: " + representation.getClass().getName());
+ }
+
+ /**
+ * Converts a {@link SQLRepresentation} implementation to a {@link SQLRepresentationDTO}.
+ *
+ * @param sqlRepresentation The SQL representation implementation.
+ * @return The SQL representation DTO.
+ */
+ public static SQLRepresentationDTO toDTO(SQLRepresentation sqlRepresentation) {
+ return (SQLRepresentationDTO) RepresentationDTO.fromRepresentation(sqlRepresentation);
+ }
+
+ /**
+ * Converts an array of {@link Representation} implementations to an array of {@link
+ * RepresentationDTO}.
+ *
+ * @param representations The representation implementations.
+ * @return The representation DTOs.
+ */
+ public static RepresentationDTO[] toDTOs(Representation[] representations) {
+ if (representations == null) {
+ return new RepresentationDTO[0];
+ }
+ return Arrays.stream(representations)
+ .map(DTOConverters::toDTO)
+ .toArray(RepresentationDTO[]::new);
+ }
+
/**
* Converts a Distribution implementation to a DistributionDTO.
*
@@ -1132,6 +1201,36 @@ public class DTOConverters {
fromFunctionArg((FunctionArg) column.defaultValue()));
}
+ /**
+ * Converts a {@link RepresentationDTO} to a {@link Representation}.
+ *
+ * @param representationDTO The representation DTO to be converted.
+ * @return The representation implementation.
+ */
+ public static Representation fromDTO(RepresentationDTO representationDTO) {
+ if (representationDTO instanceof SQLRepresentationDTO) {
+ SQLRepresentationDTO dto = (SQLRepresentationDTO) representationDTO;
+ return SQLRepresentation.builder().withDialect(dto.dialect()).withSql(dto.sql()).build();
+ }
+ throw new IllegalArgumentException(
+ "Unsupported representation DTO type: " + representationDTO.getClass().getName());
+ }
+
+ /**
+ * Converts an array of {@link RepresentationDTO} to an array of {@link Representation}.
+ *
+ * @param representationDTOs The representation DTOs to be converted.
+ * @return The representation implementations.
+ */
+ public static Representation[] fromDTOs(RepresentationDTO[] representationDTOs) {
+ if (representationDTOs == null) {
+ return new Representation[0];
+ }
+ return Arrays.stream(representationDTOs)
+ .map(DTOConverters::fromDTO)
+ .toArray(Representation[]::new);
+ }
+
/**
* Converts a TableDTO to a Table.
*
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.java
index 5e00ead7b5..2e8c53717d 100644
--- a/common/src/test/java/org/apache/gravitino/dto/rel/TestRepresentationDTO.java
+++ b/common/src/test/java/org/apache/gravitino/dto/rel/TestRepresentationDTO.java
@@ -19,6 +19,7 @@
package org.apache.gravitino.dto.rel;
import com.fasterxml.jackson.core.JsonProcessingException;
+import org.apache.gravitino.dto.util.DTOConverters;
import org.apache.gravitino.json.JsonUtils;
import org.apache.gravitino.rel.Representation;
import org.apache.gravitino.rel.SQLRepresentation;
@@ -30,8 +31,9 @@ public class TestRepresentationDTO {
@Test
public void testRepresentationDTOSerDe() throws JsonProcessingException {
SQLRepresentationDTO sqlRepresentationDTO =
- SQLRepresentationDTO.fromSQLRepresentation(
- SQLRepresentation.builder().withDialect("spark").withSql("SELECT 1").build());
+ (SQLRepresentationDTO)
+ RepresentationDTO.fromRepresentation(
+ SQLRepresentation.builder().withDialect("spark").withSql("SELECT 1").build());
String json = JsonUtils.objectMapper().writeValueAsString(sqlRepresentationDTO);
RepresentationDTO deserialized =
@@ -39,8 +41,8 @@ public class TestRepresentationDTO {
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());
+ Assertions.assertEquals("spark", ((SQLRepresentationDTO) deserialized).dialect());
+ Assertions.assertEquals("SELECT 1", ((SQLRepresentationDTO) deserialized).sql());
}
@Test
@@ -49,8 +51,28 @@ public class TestRepresentationDTO {
SQLRepresentation.builder().withDialect("trino").withSql("SELECT c1 FROM t").build();
RepresentationDTO dto = RepresentationDTO.fromRepresentation(representation);
- Representation converted = dto.toRepresentation();
+ Representation converted = DTOConverters.fromDTO(dto);
Assertions.assertEquals(representation, converted);
}
+
+ @Test
+ public void testSQLRepresentationDTOBuilderRejectsMissingDialect() {
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> SQLRepresentationDTO.builder().withSql("SELECT 1").build());
+ Assertions.assertEquals(
+ "\"dialect\" field is required and cannot be empty", exception.getMessage());
+ }
+
+ @Test
+ public void testSQLRepresentationDTOBuilderRejectsBlankSql() {
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> SQLRepresentationDTO.builder().withDialect("spark").withSql(" ").build());
+ Assertions.assertEquals(
+ "\"sql\" field is required and cannot be empty", exception.getMessage());
+ }
}
diff --git a/common/src/test/java/org/apache/gravitino/dto/rel/TestViewDTO.java b/common/src/test/java/org/apache/gravitino/dto/rel/TestViewDTO.java
new file mode 100644
index 0000000000..d0bd9a60ec
--- /dev/null
+++ b/common/src/test/java/org/apache/gravitino/dto/rel/TestViewDTO.java
@@ -0,0 +1,154 @@
+/*
+ * 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 java.time.Instant;
+import java.util.Map;
+import org.apache.gravitino.dto.AuditDTO;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.rel.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestViewDTO {
+
+ @Test
+ public void testViewDTOSerDe() throws JsonProcessingException {
+ ViewDTO dto =
+ ViewDTO.builder()
+ .withName("v1")
+ .withComment("comment")
+ .withColumns(
+ new ColumnDTO[] {
+ ColumnDTO.builder().withName("c1").withDataType(Types.LongType.get()).build()
+ })
+ .withRepresentations(
+ new RepresentationDTO[] {
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 1").build()
+ })
+ .withDefaultCatalog("cat")
+ .withDefaultSchema("sch")
+ .withProperties(Map.of("k", "v"))
+ .withAudit(audit())
+ .build();
+
+ String json = JsonUtils.objectMapper().writeValueAsString(dto);
+ ViewDTO deserialized = JsonUtils.objectMapper().readValue(json, ViewDTO.class);
+
+ Assertions.assertEquals("v1", deserialized.name());
+ Assertions.assertEquals("comment", deserialized.comment());
+ Assertions.assertEquals(1, deserialized.columns().length);
+ Assertions.assertEquals("cat", deserialized.defaultCatalog());
+ 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]);
+ }
+
+ @Test
+ public void testViewDTOBuildDefaultColumnsAndProperties() {
+ ViewDTO dto =
+ ViewDTO.builder()
+ .withName("v1")
+ .withRepresentations(
+ new RepresentationDTO[] {
+ SQLRepresentationDTO.builder().withDialect("spark").withSql("SELECT 2").build()
+ })
+ .withAudit(audit())
+ .build();
+
+ Assertions.assertEquals(0, dto.columns().length);
+ Assertions.assertTrue(dto.properties().isEmpty());
+ }
+
+ @Test
+ public void testViewDTOBuildValidation() {
+ IllegalArgumentException exception1 =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ ViewDTO.builder()
+ .withAudit(audit())
+ .withRepresentations(new RepresentationDTO[0])
+ .build());
+ Assertions.assertEquals("name cannot be null or empty", exception1.getMessage());
+
+ IllegalArgumentException exception2 =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ ViewDTO.builder()
+ .withName("v1")
+ .withRepresentations(new RepresentationDTO[0])
+ .build());
+ Assertions.assertEquals("audit cannot be null", exception2.getMessage());
+
+ IllegalArgumentException exception3 =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> ViewDTO.builder().withName("v1").withAudit(audit()).build());
+ Assertions.assertEquals("representations cannot be null or empty", exception3.getMessage());
+ }
+
+ @Test
+ public void testViewDTODeserializeFromRawJson() throws JsonProcessingException {
+ String rawJson =
+ "{"
+ + "\"name\":\"v_raw\","
+ + "\"comment\":\"raw comment\","
+ + "\"columns\":[],"
+ + "\"representations\":[{\"type\":\"sql\",\"dialect\":\"spark\",\"sql\":\"SELECT 2\"}],"
+ + "\"defaultCatalog\":\"cat\","
+ + "\"defaultSchema\":\"sch\","
+ + "\"properties\":{\"k\":\"v\"},"
+ + "\"audit\":{}"
+ + "}";
+
+ ViewDTO dto = JsonUtils.objectMapper().readValue(rawJson, ViewDTO.class);
+
+ 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.assertEquals("cat", dto.defaultCatalog());
+ Assertions.assertEquals("sch", dto.defaultSchema());
+ Assertions.assertEquals("v", dto.properties().get("k"));
+ }
+
+ @Test
+ public void testViewDTOColumnsFallbackToEmptyArrayWhenMissingInJson()
+ throws JsonProcessingException {
+ String rawJson =
+ "{"
+ + "\"name\":\"v_raw\","
+ + "\"representations\":[{\"type\":\"sql\",\"dialect\":\"spark\",\"sql\":\"SELECT 2\"}],"
+ + "\"audit\":{}"
+ + "}";
+
+ ViewDTO dto = JsonUtils.objectMapper().readValue(rawJson, ViewDTO.class);
+
+ Assertions.assertNotNull(dto.columns());
+ Assertions.assertEquals(0, dto.columns().length);
+ }
+
+ private AuditDTO audit() {
+ return AuditDTO.builder().withCreator("u1").withCreateTime(Instant.now()).build();
+ }
+}
diff --git a/common/src/test/java/org/apache/gravitino/dto/requests/TestViewCreateRequest.java b/common/src/test/java/org/apache/gravitino/dto/requests/TestViewCreateRequest.java
new file mode 100644
index 0000000000..529fb21ba2
--- /dev/null
+++ b/common/src/test/java/org/apache/gravitino/dto/requests/TestViewCreateRequest.java
@@ -0,0 +1,155 @@
+/*
+ * 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.requests;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.Map;
+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.json.JsonUtils;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestViewCreateRequest {
+
+ @Test
+ public void testViewCreateRequestSerDeAndValidate() throws JsonProcessingException {
+ ViewCreateRequest request =
+ ViewCreateRequest.builder()
+ .name("v1")
+ .comment("comment")
+ .columns(new ColumnDTO[0])
+ .representations(
+ new RepresentationDTO[] {
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 1").build()
+ })
+ .defaultCatalog("cat")
+ .defaultSchema("sch")
+ .properties(Map.of("k", "v"))
+ .build();
+
+ String json = JsonUtils.objectMapper().writeValueAsString(request);
+ ViewCreateRequest deserialized =
+ JsonUtils.objectMapper().readValue(json, ViewCreateRequest.class);
+
+ Assertions.assertEquals("v1", deserialized.getName());
+ Assertions.assertEquals("comment", deserialized.getComment());
+ Assertions.assertEquals("cat", deserialized.getDefaultCatalog());
+ Assertions.assertEquals("sch", deserialized.getDefaultSchema());
+ Assertions.assertEquals(Map.of("k", "v"), deserialized.getProperties());
+ Assertions.assertDoesNotThrow(deserialized::validate);
+ }
+
+ @Test
+ public void testViewCreateRequestValidateRequiredFields() {
+ ViewCreateRequest missingName =
+ ViewCreateRequest.builder()
+ .representations(
+ new RepresentationDTO[] {
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 1").build()
+ })
+ .build();
+ IllegalArgumentException exception1 =
+ Assertions.assertThrows(IllegalArgumentException.class, missingName::validate);
+ Assertions.assertEquals(
+ "\"name\" field is required and cannot be empty", exception1.getMessage());
+
+ ViewCreateRequest missingRepresentations = ViewCreateRequest.builder().name("v1").build();
+ IllegalArgumentException exception2 =
+ Assertions.assertThrows(IllegalArgumentException.class, missingRepresentations::validate);
+ Assertions.assertEquals(
+ "\"representations\" field is required and cannot be empty", exception2.getMessage());
+ }
+
+ @Test
+ public void testViewCreateRequestValidateDuplicateDialect() {
+ ViewCreateRequest duplicateDialect =
+ ViewCreateRequest.builder()
+ .name("v1")
+ .representations(
+ new RepresentationDTO[] {
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 1").build(),
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 2").build()
+ })
+ .build();
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(IllegalArgumentException.class, duplicateDialect::validate);
+ Assertions.assertEquals("Duplicate SQL representation dialect: trino", exception.getMessage());
+ }
+
+ @Test
+ public void testViewCreateRequestValidateNullColumn() {
+ ViewCreateRequest request =
+ ViewCreateRequest.builder()
+ .name("v1")
+ .columns(new ColumnDTO[] {null})
+ .representations(
+ new RepresentationDTO[] {
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 1").build()
+ })
+ .build();
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(IllegalArgumentException.class, request::validate);
+ Assertions.assertEquals("column must not be null", exception.getMessage());
+ }
+
+ @Test
+ public void testViewCreateRequestValidateInvalidColumn() throws JsonProcessingException {
+ String rawJson =
+ "{"
+ + "\"name\":\"v1\","
+ + "\"columns\":[{}],"
+ + "\"representations\":[{\"type\":\"sql\",\"dialect\":\"trino\",\"sql\":\"SELECT 1\"}]"
+ + "}";
+
+ ViewCreateRequest request =
+ JsonUtils.objectMapper().readValue(rawJson, ViewCreateRequest.class);
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(IllegalArgumentException.class, request::validate);
+ Assertions.assertEquals("Column name cannot be null or empty.", exception.getMessage());
+ }
+
+ @Test
+ public void testViewCreateRequestDeserializeFromRawJson() throws JsonProcessingException {
+ String rawJson =
+ "{"
+ + "\"name\":\"v_raw\","
+ + "\"comment\":\"raw comment\","
+ + "\"columns\":[],"
+ + "\"representations\":[{\"type\":\"sql\",\"dialect\":\"trino\",\"sql\":\"SELECT 1\"}],"
+ + "\"defaultCatalog\":\"cat\","
+ + "\"defaultSchema\":\"sch\","
+ + "\"properties\":{\"k\":\"v\"}"
+ + "}";
+
+ ViewCreateRequest request =
+ JsonUtils.objectMapper().readValue(rawJson, ViewCreateRequest.class);
+
+ Assertions.assertEquals("v_raw", request.getName());
+ Assertions.assertEquals("raw comment", request.getComment());
+ Assertions.assertEquals("cat", request.getDefaultCatalog());
+ Assertions.assertEquals("sch", request.getDefaultSchema());
+ Assertions.assertEquals("v", request.getProperties().get("k"));
+ Assertions.assertDoesNotThrow(request::validate);
+ }
+}
diff --git a/common/src/test/java/org/apache/gravitino/dto/requests/TestViewUpdateRequest.java b/common/src/test/java/org/apache/gravitino/dto/requests/TestViewUpdateRequest.java
new file mode 100644
index 0000000000..dfcdcc9c04
--- /dev/null
+++ b/common/src/test/java/org/apache/gravitino/dto/requests/TestViewUpdateRequest.java
@@ -0,0 +1,211 @@
+/*
+ * 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.requests;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.collect.ImmutableList;
+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.json.JsonUtils;
+import org.apache.gravitino.rel.ViewChange;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestViewUpdateRequest {
+
+ @Test
+ public void testRenameViewRequestSerDeAndChange() throws JsonProcessingException {
+ ViewUpdateRequest request = new ViewUpdateRequest.RenameViewRequest("v2");
+
+ String json = JsonUtils.objectMapper().writeValueAsString(request);
+ ViewUpdateRequest deserialized =
+ JsonUtils.objectMapper().readValue(json, ViewUpdateRequest.class);
+
+ Assertions.assertInstanceOf(ViewUpdateRequest.RenameViewRequest.class, deserialized);
+ Assertions.assertDoesNotThrow(deserialized::validate);
+ ViewChange change = deserialized.viewChange();
+ Assertions.assertInstanceOf(ViewChange.RenameView.class, change);
+ Assertions.assertEquals("v2", ((ViewChange.RenameView) change).getNewName());
+ }
+
+ @Test
+ public void testSetAndRemovePropertyRequestValidation() {
+ ViewUpdateRequest setProperty = new ViewUpdateRequest.SetViewPropertyRequest("k", "v");
+ ViewUpdateRequest removeProperty = new ViewUpdateRequest.RemoveViewPropertyRequest("k");
+
+ Assertions.assertDoesNotThrow(setProperty::validate);
+ Assertions.assertDoesNotThrow(removeProperty::validate);
+
+ ViewChange setPropertyChange = setProperty.viewChange();
+ Assertions.assertInstanceOf(ViewChange.SetProperty.class, setPropertyChange);
+ Assertions.assertEquals("k", ((ViewChange.SetProperty) setPropertyChange).getProperty());
+ Assertions.assertEquals("v", ((ViewChange.SetProperty) setPropertyChange).getValue());
+
+ ViewChange removePropertyChange = removeProperty.viewChange();
+ Assertions.assertInstanceOf(ViewChange.RemoveProperty.class, removePropertyChange);
+ Assertions.assertEquals("k", ((ViewChange.RemoveProperty) removePropertyChange).getProperty());
+ }
+
+ @Test
+ public void testReplaceViewRequestValidateAndChange() {
+ ViewUpdateRequest.ReplaceViewRequest request =
+ new ViewUpdateRequest.ReplaceViewRequest(
+ new ColumnDTO[0],
+ new RepresentationDTO[] {
+ SQLRepresentationDTO.builder().withDialect("spark").withSql("SELECT 2").build()
+ },
+ "cat1",
+ "sch1",
+ "new comment");
+
+ Assertions.assertDoesNotThrow(request::validate);
+ ViewChange change = request.viewChange();
+ Assertions.assertInstanceOf(ViewChange.ReplaceView.class, change);
+ ViewChange.ReplaceView replaceView = (ViewChange.ReplaceView) change;
+ Assertions.assertEquals(1, replaceView.getRepresentations().length);
+ Assertions.assertEquals("cat1", replaceView.getDefaultCatalog());
+ Assertions.assertEquals("sch1", replaceView.getDefaultSchema());
+ Assertions.assertEquals("new comment", replaceView.getComment());
+ }
+
+ @Test
+ public void testReplaceViewRequestValidateDuplicateDialect() {
+ ViewUpdateRequest.ReplaceViewRequest request =
+ new ViewUpdateRequest.ReplaceViewRequest(
+ new ColumnDTO[0],
+ new RepresentationDTO[] {
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 1").build(),
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 2").build()
+ },
+ null,
+ null,
+ null);
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(IllegalArgumentException.class, request::validate);
+ Assertions.assertEquals("Duplicate SQL representation dialect: trino", exception.getMessage());
+ }
+
+ @Test
+ public void testReplaceViewRequestValidateNullColumn() {
+ ViewUpdateRequest.ReplaceViewRequest request =
+ new ViewUpdateRequest.ReplaceViewRequest(
+ new ColumnDTO[] {null},
+ new RepresentationDTO[] {
+ SQLRepresentationDTO.builder().withDialect("spark").withSql("SELECT 2").build()
+ },
+ null,
+ null,
+ null);
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(IllegalArgumentException.class, request::validate);
+ Assertions.assertEquals("column must not be null", exception.getMessage());
+ }
+
+ @Test
+ public void testReplaceViewRequestValidateInvalidColumn() throws JsonProcessingException {
+ String rawJson =
+ "{"
+ + "\"@type\":\"replaceView\","
+ + "\"columns\":[{}],"
+ + "\"representations\":[{\"type\":\"sql\",\"dialect\":\"spark\",\"sql\":\"SELECT 2\"}]"
+ + "}";
+
+ ViewUpdateRequest.ReplaceViewRequest request =
+ (ViewUpdateRequest.ReplaceViewRequest)
+ JsonUtils.objectMapper().readValue(rawJson, ViewUpdateRequest.class);
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(IllegalArgumentException.class, request::validate);
+ Assertions.assertEquals("Column name cannot be null or empty.", exception.getMessage());
+ }
+
+ @Test
+ public void testViewUpdatesRequestSerDeAndValidate() throws JsonProcessingException {
+ ViewUpdatesRequest request =
+ new ViewUpdatesRequest(
+ ImmutableList.of(
+ new ViewUpdateRequest.RenameViewRequest("v2"),
+ new ViewUpdateRequest.SetViewPropertyRequest("k", "v"),
+ new ViewUpdateRequest.ReplaceViewRequest(
+ new ColumnDTO[0],
+ new RepresentationDTO[] {
+ SQLRepresentationDTO.builder()
+ .withDialect("spark")
+ .withSql("SELECT 2")
+ .build()
+ },
+ null,
+ null,
+ null)));
+
+ String json = JsonUtils.objectMapper().writeValueAsString(request);
+ ViewUpdatesRequest deserialized =
+ JsonUtils.objectMapper().readValue(json, ViewUpdatesRequest.class);
+
+ Assertions.assertEquals(3, deserialized.getUpdates().size());
+ Assertions.assertDoesNotThrow(deserialized::validate);
+ Assertions.assertInstanceOf(
+ ViewUpdateRequest.RenameViewRequest.class, deserialized.getUpdates().get(0));
+ Assertions.assertInstanceOf(
+ ViewUpdateRequest.SetViewPropertyRequest.class, deserialized.getUpdates().get(1));
+ Assertions.assertInstanceOf(
+ ViewUpdateRequest.ReplaceViewRequest.class, deserialized.getUpdates().get(2));
+ }
+
+ @Test
+ public void testViewUpdatesRequestValidateEmptyUpdates() {
+ ViewUpdatesRequest empty = new ViewUpdatesRequest(ImmutableList.of());
+ IllegalArgumentException exception =
+ Assertions.assertThrows(IllegalArgumentException.class, empty::validate);
+ Assertions.assertEquals("updates must not be empty", exception.getMessage());
+ }
+
+ @Test
+ public void testViewUpdatesRequestDeserializeFromRawJson() throws JsonProcessingException {
+ String rawJson =
+ "{"
+ + "\"updates\":["
+ + "{\"@type\":\"rename\",\"newName\":\"v2\"},"
+ + "{\"@type\":\"setProperty\",\"property\":\"k\",\"value\":\"v\"},"
+ + "{\"@type\":\"replaceView\","
+ + "\"columns\":[],"
+ + "\"representations\":[{\"type\":\"sql\",\"dialect\":\"trino\",\"sql\":\"SELECT 1\"}],"
+ + "\"defaultCatalog\":\"cat\","
+ + "\"defaultSchema\":\"sch\","
+ + "\"comment\":\"new comment\""
+ + "}"
+ + "]"
+ + "}";
+
+ ViewUpdatesRequest request =
+ JsonUtils.objectMapper().readValue(rawJson, ViewUpdatesRequest.class);
+
+ Assertions.assertEquals(3, request.getUpdates().size());
+ Assertions.assertInstanceOf(
+ ViewUpdateRequest.RenameViewRequest.class, request.getUpdates().get(0));
+ Assertions.assertInstanceOf(
+ ViewUpdateRequest.SetViewPropertyRequest.class, request.getUpdates().get(1));
+ Assertions.assertInstanceOf(
+ ViewUpdateRequest.ReplaceViewRequest.class, request.getUpdates().get(2));
+ Assertions.assertDoesNotThrow(request::validate);
+ }
+}
diff --git a/common/src/test/java/org/apache/gravitino/dto/responses/TestViewResponse.java b/common/src/test/java/org/apache/gravitino/dto/responses/TestViewResponse.java
new file mode 100644
index 0000000000..9cef550fcd
--- /dev/null
+++ b/common/src/test/java/org/apache/gravitino/dto/responses/TestViewResponse.java
@@ -0,0 +1,132 @@
+/*
+ * 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.responses;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.time.Instant;
+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.json.JsonUtils;
+import org.apache.gravitino.rel.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestViewResponse {
+
+ @Test
+ public void testViewResponseSerDeAndValidate() throws JsonProcessingException {
+ ViewResponse response = new ViewResponse(viewDTO("v1"));
+
+ String json = JsonUtils.objectMapper().writeValueAsString(response);
+ ViewResponse deserialized = JsonUtils.objectMapper().readValue(json, ViewResponse.class);
+
+ Assertions.assertEquals("v1", deserialized.getView().name());
+ Assertions.assertDoesNotThrow(deserialized::validate);
+ }
+
+ @Test
+ public void testViewResponseValidateWithNullView() {
+ ViewResponse response = new ViewResponse();
+ IllegalArgumentException exception =
+ Assertions.assertThrows(IllegalArgumentException.class, response::validate);
+ Assertions.assertEquals("view must not be null", exception.getMessage());
+ }
+
+ @Test
+ public void testViewResponseValidateWithMissingRepresentations() throws JsonProcessingException {
+ String rawJson =
+ "{"
+ + "\"code\":0,"
+ + "\"view\":{"
+ + "\"name\":\"v1\","
+ + "\"columns\":[],"
+ + "\"representations\":[],"
+ + "\"audit\":{}"
+ + "}"
+ + "}";
+ ViewResponse response = JsonUtils.objectMapper().readValue(rawJson, ViewResponse.class);
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(IllegalArgumentException.class, response::validate);
+ Assertions.assertEquals(
+ "view 'representations' must not be null or empty", exception.getMessage());
+ }
+
+ @Test
+ public void testViewResponseValidateWithMissingNameMessage() throws JsonProcessingException {
+ String rawJson =
+ "{"
+ + "\"code\":0,"
+ + "\"view\":{"
+ + "\"name\":\"\","
+ + "\"columns\":[],"
+ + "\"representations\":[{\"type\":\"sql\",\"dialect\":\"trino\",\"sql\":\"SELECT 1\"}],"
+ + "\"audit\":{}"
+ + "}"
+ + "}";
+
+ ViewResponse malformed = JsonUtils.objectMapper().readValue(rawJson, ViewResponse.class);
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(IllegalArgumentException.class, malformed::validate);
+ Assertions.assertEquals("view 'name' must not be null or empty", exception.getMessage());
+ }
+
+ @Test
+ public void testViewResponseDeserializeFromRawJson() throws JsonProcessingException {
+ String rawJson =
+ "{"
+ + "\"code\":0,"
+ + "\"view\":{"
+ + "\"name\":\"v1\","
+ + "\"columns\":[],"
+ + "\"representations\":[{\"type\":\"sql\",\"dialect\":\"trino\",\"sql\":\"SELECT 1\"}],"
+ + "\"audit\":{}"
+ + "}"
+ + "}";
+
+ ViewResponse response = JsonUtils.objectMapper().readValue(rawJson, ViewResponse.class);
+
+ Assertions.assertEquals("v1", response.getView().name());
+ Assertions.assertEquals(1, response.getView().representations().length);
+ Assertions.assertDoesNotThrow(response::validate);
+ }
+
+ private ViewDTO viewDTO(String name) {
+ return ViewDTO.builder()
+ .withName(name)
+ .withColumns(
+ new ColumnDTO[] {
+ ColumnDTO.builder().withName("c1").withDataType(Types.IntegerType.get()).build()
+ })
+ .withRepresentations(
+ new RepresentationDTO[] {
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 1").build()
+ })
+ .withAudit(audit())
+ .build();
+ }
+
+ private AuditDTO audit() {
+ return AuditDTO.builder().withCreator("u1").withCreateTime(Instant.now()).build();
+ }
+}
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.java
index aff8d39769..de9e5d0f56 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
@@ -36,6 +36,7 @@ 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.dto.util.DTOConverters;
import org.apache.gravitino.json.JsonUtils;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.meta.NamespacedEntityId;
@@ -222,7 +223,7 @@ public class ViewPO {
.getTypeFactory()
.constructCollectionType(List.class, RepresentationDTO.class);
List<RepresentationDTO> list = JsonUtils.anyFieldMapper().readValue(json, type);
- return list.stream().map(RepresentationDTO::toRepresentation).toArray(Representation[]::new);
+ return list.stream().map(DTOConverters::fromDTO).toArray(Representation[]::new);
}
private static ColumnDTO toColumnDTO(Column column) {
diff --git a/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java b/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java
index 0d45a57721..91630cfe5d 100644
--- a/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java
+++ b/server/src/main/java/org/apache/gravitino/server/GravitinoServer.java
@@ -35,6 +35,7 @@ import org.apache.gravitino.catalog.PartitionDispatcher;
import org.apache.gravitino.catalog.SchemaDispatcher;
import org.apache.gravitino.catalog.TableDispatcher;
import org.apache.gravitino.catalog.TopicDispatcher;
+import org.apache.gravitino.catalog.ViewDispatcher;
import org.apache.gravitino.credential.CredentialOperationDispatcher;
import org.apache.gravitino.job.JobOperationDispatcher;
import org.apache.gravitino.lineage.LineageConfig;
@@ -142,6 +143,7 @@ public class GravitinoServer extends ResourceConfig {
bind(gravitinoEnv.catalogDispatcher()).to(CatalogDispatcher.class).ranked(1);
bind(gravitinoEnv.schemaDispatcher()).to(SchemaDispatcher.class).ranked(1);
bind(gravitinoEnv.tableDispatcher()).to(TableDispatcher.class).ranked(1);
+ bind(gravitinoEnv.viewDispatcher()).to(ViewDispatcher.class).ranked(1);
bind(gravitinoEnv.partitionDispatcher()).to(PartitionDispatcher.class).ranked(1);
bind(gravitinoEnv.filesetDispatcher()).to(FilesetDispatcher.class).ranked(1);
bind(gravitinoEnv.topicDispatcher()).to(TopicDispatcher.class).ranked(1);
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
index df6f67387b..2476c3f7e5 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
@@ -53,6 +53,7 @@ import org.apache.gravitino.exceptions.TagAlreadyAssociatedException;
import org.apache.gravitino.exceptions.TagAlreadyExistsException;
import org.apache.gravitino.exceptions.TopicAlreadyExistsException;
import org.apache.gravitino.exceptions.UserAlreadyExistsException;
+import org.apache.gravitino.exceptions.ViewAlreadyExistsException;
import org.apache.gravitino.server.web.Utils;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
@@ -74,6 +75,11 @@ public class ExceptionHandlers {
return TableExceptionHandler.INSTANCE.handle(op, table, schema, e);
}
+ public static Response handleViewException(
+ OperationType op, String view, String schema, Exception e) {
+ return ViewExceptionHandler.INSTANCE.handle(op, view, schema, e);
+ }
+
public static Response handleSchemaException(
OperationType op, String schema, String catalog, Exception e) {
return SchemaExceptionHandler.INSTANCE.handle(op, schema, catalog, e);
@@ -284,6 +290,47 @@ public class ExceptionHandlers {
}
}
+ private static class ViewExceptionHandler extends BaseExceptionHandler {
+
+ private static final ExceptionHandler INSTANCE = new ViewExceptionHandler();
+
+ private static String getViewErrorMsg(
+ String view, String operation, String schema, String reason) {
+ return String.format(
+ "Failed to operate view(s)%s operation [%s] under schema [%s], reason [%s]",
+ view, operation, schema, reason);
+ }
+
+ @Override
+ public Response handle(OperationType op, String view, String schema, Exception e) {
+ String formatted = StringUtil.isBlank(view) ? "" : " [" + view + "]";
+ String errorMsg = getViewErrorMsg(formatted, op.name(), schema, getErrorMsg(e));
+ LOG.warn(errorMsg, e);
+
+ if (e instanceof IllegalArgumentException) {
+ return Utils.illegalArguments(errorMsg, e);
+
+ } else if (e instanceof NotFoundException) {
+ return Utils.notFound(errorMsg, e);
+
+ } else if (e instanceof ViewAlreadyExistsException) {
+ return Utils.alreadyExists(errorMsg, e);
+
+ } else if (e instanceof UnsupportedOperationException) {
+ return Utils.unsupportedOperation(errorMsg, e);
+
+ } else if (e instanceof ForbiddenException) {
+ return Utils.forbidden(errorMsg, e);
+
+ } else if (e instanceof NotInUseException) {
+ return Utils.notInUse(errorMsg, e);
+
+ } else {
+ return super.handle(op, view, schema, e);
+ }
+ }
+ }
+
private static class SchemaExceptionHandler extends BaseExceptionHandler {
private static final ExceptionHandler INSTANCE = new SchemaExceptionHandler();
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/ViewOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/ViewOperations.java
new file mode 100644
index 0000000000..7d2cfd11dd
--- /dev/null
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/ViewOperations.java
@@ -0,0 +1,220 @@
+/*
+ * 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.server.web.rest;
+
+import com.codahale.metrics.annotation.ResponseMetered;
+import com.codahale.metrics.annotation.Timed;
+import javax.inject.Inject;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.catalog.ViewDispatcher;
+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.ViewResponse;
+import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.rel.View;
+import org.apache.gravitino.rel.ViewChange;
+import org.apache.gravitino.server.web.Utils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.NamespaceUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Path("metalakes/{metalake}/catalogs/{catalog}/schemas/{schema}/views")
+public class ViewOperations {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ViewOperations.class);
+
+ private final ViewDispatcher dispatcher;
+
+ @Context private HttpServletRequest httpRequest;
+
+ @Inject
+ public ViewOperations(ViewDispatcher dispatcher) {
+ this.dispatcher = dispatcher;
+ }
+
+ @GET
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "list-view." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "list-view", absolute = true)
+ public Response listViews(
+ @PathParam("metalake") String metalake,
+ @PathParam("catalog") String catalog,
+ @PathParam("schema") String schema) {
+ LOG.info("Received list views request for schema: {}.{}.{}", metalake, catalog, schema);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ Namespace viewNS = NamespaceUtil.ofView(metalake, catalog, schema);
+ NameIdentifier[] idents = dispatcher.listViews(viewNS);
+ Response response = Utils.ok(new EntityListResponse(idents));
+ LOG.info(
+ "List {} views under schema: {}.{}.{}", idents.length, metalake, catalog, schema);
+ return response;
+ });
+
+ } catch (Exception e) {
+ return ExceptionHandlers.handleViewException(OperationType.LIST, "", schema, e);
+ }
+ }
+
+ @POST
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "create-view." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "create-view", absolute = true)
+ public Response createView(
+ @PathParam("metalake") String metalake,
+ @PathParam("catalog") String catalog,
+ @PathParam("schema") String schema,
+ ViewCreateRequest request) {
+ LOG.info(
+ "Received create view request: {}.{}.{}.{}", metalake, catalog, schema, request.getName());
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ request.validate();
+ NameIdentifier ident =
+ NameIdentifierUtil.ofView(metalake, catalog, schema, request.getName());
+
+ View view =
+ dispatcher.createView(
+ ident,
+ request.getComment(),
+ DTOConverters.fromDTOs(request.getColumns()),
+ DTOConverters.fromDTOs(request.getRepresentations()),
+ request.getDefaultCatalog(),
+ request.getDefaultSchema(),
+ request.getProperties());
+ Response response = Utils.ok(new ViewResponse(DTOConverters.toDTO(view)));
+ LOG.info("View created: {}.{}.{}.{}", metalake, catalog, schema, request.getName());
+ return response;
+ });
+
+ } catch (Exception e) {
+ return ExceptionHandlers.handleViewException(
+ OperationType.CREATE, request.getName(), schema, e);
+ }
+ }
+
+ @GET
+ @Path("{view}")
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "load-view." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "load-view", absolute = true)
+ public Response loadView(
+ @PathParam("metalake") String metalake,
+ @PathParam("catalog") String catalog,
+ @PathParam("schema") String schema,
+ @PathParam("view") String view) {
+ LOG.info("Received load view request for view: {}.{}.{}.{}", metalake, catalog, schema, view);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ NameIdentifier ident = NameIdentifierUtil.ofView(metalake, catalog, schema, view);
+ View v = dispatcher.loadView(ident);
+ Response response = Utils.ok(new ViewResponse(DTOConverters.toDTO(v)));
+ LOG.info("View loaded: {}.{}.{}.{}", metalake, catalog, schema, view);
+ return response;
+ });
+ } catch (Exception e) {
+ return ExceptionHandlers.handleViewException(OperationType.LOAD, view, schema, e);
+ }
+ }
+
+ @PUT
+ @Path("{view}")
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "alter-view." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "alter-view", absolute = true)
+ public Response alterView(
+ @PathParam("metalake") String metalake,
+ @PathParam("catalog") String catalog,
+ @PathParam("schema") String schema,
+ @PathParam("view") String view,
+ ViewUpdatesRequest request) {
+ LOG.info("Received alter view request: {}.{}.{}.{}", metalake, catalog, schema, view);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ request.validate();
+ NameIdentifier ident = NameIdentifierUtil.ofView(metalake, catalog, schema, view);
+ ViewChange[] changes =
+ request.getUpdates().stream()
+ .map(ViewUpdateRequest::viewChange)
+ .toArray(ViewChange[]::new);
+ View v = dispatcher.alterView(ident, changes);
+ Response response = Utils.ok(new ViewResponse(DTOConverters.toDTO(v)));
+ LOG.info("View altered: {}.{}.{}.{}", metalake, catalog, schema, v.name());
+ return response;
+ });
+
+ } catch (Exception e) {
+ return ExceptionHandlers.handleViewException(OperationType.ALTER, view, schema, e);
+ }
+ }
+
+ @DELETE
+ @Path("{view}")
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "drop-view." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "drop-view", absolute = true)
+ public Response dropView(
+ @PathParam("metalake") String metalake,
+ @PathParam("catalog") String catalog,
+ @PathParam("schema") String schema,
+ @PathParam("view") String view) {
+ LOG.info("Received drop view request: {}.{}.{}.{}", metalake, catalog, schema, view);
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ NameIdentifier ident = NameIdentifierUtil.ofView(metalake, catalog, schema, view);
+ boolean dropped = dispatcher.dropView(ident);
+ if (dropped) {
+ LOG.info("View dropped: {}.{}.{}.{}", metalake, catalog, schema, view);
+ } else {
+ LOG.warn("Cannot find to be dropped view {} under schema {}", view, schema);
+ }
+ return Utils.ok(new DropResponse(dropped));
+ });
+
+ } catch (Exception e) {
+ return ExceptionHandlers.handleViewException(OperationType.DROP, view, schema, e);
+ }
+ }
+}
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.java
new file mode 100644
index 0000000000..063d4c02e7
--- /dev/null
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestViewOperations.java
@@ -0,0 +1,422 @@
+/*
+ * 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.server.web.rest;
+
+import static org.apache.gravitino.Configs.CACHE_ENABLED;
+import static org.apache.gravitino.Configs.ENABLE_AUTHORIZATION;
+import static org.apache.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;
+import static org.apache.gravitino.Configs.TREE_LOCK_MAX_NODE_IN_MEMORY;
+import static org.apache.gravitino.Configs.TREE_LOCK_MIN_NODE_IN_MEMORY;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Map;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.gravitino.Audit;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.catalog.ViewDispatcher;
+import org.apache.gravitino.dto.rel.ColumnDTO;
+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.ErrorConstants;
+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.lock.LockManager;
+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.apache.gravitino.rel.ViewChange;
+import org.apache.gravitino.rest.RESTUtils;
+import org.glassfish.jersey.internal.inject.AbstractBinder;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.test.TestProperties;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+public class TestViewOperations extends BaseOperationsTest {
+
+ private static final String VND_V1_JSON = "application/vnd.gravitino.v1+json";
+
+ private static class MockServletRequestFactory extends ServletRequestFactoryBase {
+ @Override
+ public HttpServletRequest get() {
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ when(request.getRemoteUser()).thenReturn(null);
+ return request;
+ }
+ }
+
+ private final ViewDispatcher dispatcher = mock(ViewDispatcher.class);
+ private final String metalake = "metalake";
+ private final String catalog = "catalog1";
+ private final String schema = "default";
+
+ @BeforeAll
+ public static void setup() throws IllegalAccessException {
+ Config config = mock(Config.class);
+ Mockito.doReturn(100000L).when(config).get(TREE_LOCK_MAX_NODE_IN_MEMORY);
+ Mockito.doReturn(1000L).when(config).get(TREE_LOCK_MIN_NODE_IN_MEMORY);
+ Mockito.doReturn(36000L).when(config).get(TREE_LOCK_CLEAN_INTERVAL);
+ Mockito.doReturn(false).when(config).get(CACHE_ENABLED);
+ Mockito.doReturn(false).when(config).get(ENABLE_AUTHORIZATION);
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "config", config, true);
+ FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", new LockManager(config), true);
+ }
+
+ @Override
+ protected Application configure() {
+ try {
+ forceSet(
+ TestProperties.CONTAINER_PORT, String.valueOf(RESTUtils.findAvailablePort(2000, 3000)));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ ResourceConfig resourceConfig = new ResourceConfig();
+ resourceConfig.register(ViewOperations.class);
+ resourceConfig.register(
+ new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bind(dispatcher).to(ViewDispatcher.class).ranked(2);
+ bindFactory(TestViewOperations.MockServletRequestFactory.class)
+ .to(HttpServletRequest.class);
+ }
+ });
+
+ return resourceConfig;
+ }
+
+ @Test
+ public void testListViews() {
+ NameIdentifier view1 = NameIdentifier.of(metalake, catalog, schema, "view1");
+ NameIdentifier view2 = NameIdentifier.of(metalake, catalog, schema, "view2");
+
+ when(dispatcher.listViews(any())).thenReturn(new NameIdentifier[] {view1, view2});
+
+ Response resp =
+ target(viewPath(metalake, catalog, schema))
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
+
+ EntityListResponse listResp = resp.readEntity(EntityListResponse.class);
+ Assertions.assertEquals(0, listResp.getCode());
+
+ NameIdentifier[] views = listResp.identifiers();
+ Assertions.assertEquals(2, views.length);
+ Assertions.assertEquals(view1, views[0]);
+ Assertions.assertEquals(view2, views[1]);
+
+ // Test throw NoSuchSchemaException
+ doThrow(new NoSuchSchemaException("mock error")).when(dispatcher).listViews(any());
+ Response resp1 =
+ target(viewPath(metalake, catalog, schema))
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+
+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());
+
+ ErrorResponse errorResp = resp1.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResp.getCode());
+ Assertions.assertEquals(NoSuchSchemaException.class.getSimpleName(), errorResp.getType());
+
+ // Test throw RuntimeException
+ doThrow(new RuntimeException("mock error")).when(dispatcher).listViews(any());
+ Response resp2 =
+ target(viewPath(metalake, catalog, schema))
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+
+ Assertions.assertEquals(
+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp2.getStatus());
+
+ ErrorResponse errorResp2 = resp2.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResp2.getCode());
+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp2.getType());
+ }
+
+ @Test
+ public void testLoadView() {
+ View view = mockView("view1", "comment", ImmutableMap.of("k", "v"), "trino", "SELECT 1");
+ when(dispatcher.loadView(any())).thenReturn(view);
+
+ Response resp =
+ target(viewPath(metalake, catalog, schema) + "/view1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+
+ ViewResponse viewResp = resp.readEntity(ViewResponse.class);
+ Assertions.assertEquals(0, viewResp.getCode());
+
+ ViewDTO viewDTO = viewResp.getView();
+ Assertions.assertEquals("view1", viewDTO.name());
+ Assertions.assertEquals("comment", viewDTO.comment());
+ Assertions.assertEquals(ImmutableMap.of("k", "v"), viewDTO.properties());
+ 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.assertEquals("trino", sqlRep.dialect());
+ Assertions.assertEquals("SELECT 1", sqlRep.sql());
+
+ // Test throw NoSuchViewException
+ doThrow(new NoSuchViewException("mock error")).when(dispatcher).loadView(any());
+ Response resp1 =
+ target(viewPath(metalake, catalog, schema) + "/view1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());
+
+ ErrorResponse errorResp = resp1.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResp.getCode());
+ Assertions.assertEquals(NoSuchViewException.class.getSimpleName(), errorResp.getType());
+ }
+
+ @Test
+ public void testCreateView() {
+ View view = mockView("view1", "comment", ImmutableMap.of("k", "v"), "trino", "SELECT 1");
+ when(dispatcher.createView(any(), any(), any(), any(), any(), any(), any())).thenReturn(view);
+
+ SQLRepresentationDTO repDTO =
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 1").build();
+ ViewCreateRequest req =
+ ViewCreateRequest.builder()
+ .name("view1")
+ .comment("comment")
+ .columns(new ColumnDTO[0])
+ .representations(new SQLRepresentationDTO[] {repDTO})
+ .properties(ImmutableMap.of("k", "v"))
+ .build();
+
+ Response resp =
+ target(viewPath(metalake, catalog, schema))
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept(VND_V1_JSON)
+ .post(Entity.entity(req, VND_V1_JSON));
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+
+ ViewResponse viewResp = resp.readEntity(ViewResponse.class);
+ Assertions.assertEquals(0, viewResp.getCode());
+ Assertions.assertEquals("view1", viewResp.getView().name());
+
+ // Test throw ViewAlreadyExistsException
+ doThrow(new ViewAlreadyExistsException("mock error"))
+ .when(dispatcher)
+ .createView(any(), any(), any(), any(), any(), any(), any());
+ Response resp1 =
+ target(viewPath(metalake, catalog, schema))
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept(VND_V1_JSON)
+ .post(Entity.entity(req, VND_V1_JSON));
+ Assertions.assertEquals(Response.Status.CONFLICT.getStatusCode(), resp1.getStatus());
+
+ ErrorResponse errorResp1 = resp1.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.ALREADY_EXISTS_CODE, errorResp1.getCode());
+ Assertions.assertEquals(ViewAlreadyExistsException.class.getSimpleName(), errorResp1.getType());
+
+ // Test throw NoSuchSchemaException
+ doThrow(new NoSuchSchemaException("mock error"))
+ .when(dispatcher)
+ .createView(any(), any(), any(), any(), any(), any(), any());
+ Response resp2 =
+ target(viewPath(metalake, catalog, schema))
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept(VND_V1_JSON)
+ .post(Entity.entity(req, VND_V1_JSON));
+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp2.getStatus());
+
+ // Test duplicate SQL representation dialects → 400 BAD_REQUEST
+ SQLRepresentationDTO dupRep1 =
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 1").build();
+ SQLRepresentationDTO dupRep2 =
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 2").build();
+ ViewCreateRequest dupReq =
+ ViewCreateRequest.builder()
+ .name("view1")
+ .columns(new ColumnDTO[0])
+ .representations(new SQLRepresentationDTO[] {dupRep1, dupRep2})
+ .build();
+ Response resp3 =
+ target(viewPath(metalake, catalog, schema))
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept(VND_V1_JSON)
+ .post(Entity.entity(dupReq, VND_V1_JSON));
+ Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), resp3.getStatus());
+ ErrorResponse errorResp3 = resp3.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.ILLEGAL_ARGUMENTS_CODE, errorResp3.getCode());
+ }
+
+ @Test
+ public void testRenameView() {
+ ViewUpdateRequest req = new ViewUpdateRequest.RenameViewRequest("view2");
+ View view = mockView("view2", "comment", ImmutableMap.of(), "trino", "SELECT 1");
+ assertUpdateView(new ViewUpdatesRequest(ImmutableList.of(req)), view);
+ }
+
+ @Test
+ public void testSetAndRemoveViewProperty() {
+ ViewUpdateRequest req1 = new ViewUpdateRequest.SetViewPropertyRequest("k", "v");
+ ViewUpdateRequest req2 = new ViewUpdateRequest.RemoveViewPropertyRequest("k");
+ View view = mockView("view1", "comment", ImmutableMap.of(), "trino", "SELECT 1");
+ assertUpdateView(new ViewUpdatesRequest(ImmutableList.of(req1, req2)), view);
+ }
+
+ @Test
+ public void testReplaceView() {
+ SQLRepresentationDTO repDTO =
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 2").build();
+ ViewUpdateRequest replace =
+ new ViewUpdateRequest.ReplaceViewRequest(
+ new ColumnDTO[0], new SQLRepresentationDTO[] {repDTO}, "cat1", "sch1", "new comment");
+ View view = mockView("view1", "new comment", ImmutableMap.of(), "trino", "SELECT 2");
+ assertUpdateView(new ViewUpdatesRequest(ImmutableList.of(replace)), view);
+
+ // Test duplicate SQL representation dialects → 400 BAD_REQUEST
+ SQLRepresentationDTO dupRep1 =
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 1").build();
+ SQLRepresentationDTO dupRep2 =
+ SQLRepresentationDTO.builder().withDialect("trino").withSql("SELECT 2").build();
+ ViewUpdateRequest dupReplace =
+ new ViewUpdateRequest.ReplaceViewRequest(
+ new ColumnDTO[0], new SQLRepresentationDTO[] {dupRep1, dupRep2}, null, null, null);
+ Response resp =
+ target(viewPath(metalake, catalog, schema) + "/view1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept(VND_V1_JSON)
+ .put(Entity.entity(new ViewUpdatesRequest(ImmutableList.of(dupReplace)), VND_V1_JSON));
+ Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), resp.getStatus());
+ ErrorResponse errorResp = resp.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.ILLEGAL_ARGUMENTS_CODE, errorResp.getCode());
+ }
+
+ @Test
+ public void testDropView() {
+ when(dispatcher.dropView(any())).thenReturn(true);
+ Response resp =
+ target(viewPath(metalake, catalog, schema) + "/view1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .delete();
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+
+ DropResponse dropResp = resp.readEntity(DropResponse.class);
+ Assertions.assertEquals(0, dropResp.getCode());
+ Assertions.assertTrue(dropResp.dropped());
+
+ when(dispatcher.dropView(any())).thenReturn(false);
+ Response resp1 =
+ target(viewPath(metalake, catalog, schema) + "/view1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .delete();
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp1.getStatus());
+
+ DropResponse dropResp1 = resp1.readEntity(DropResponse.class);
+ Assertions.assertFalse(dropResp1.dropped());
+
+ doThrow(new RuntimeException("mock error")).when(dispatcher).dropView(any());
+ Response resp2 =
+ target(viewPath(metalake, catalog, schema) + "/view1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .delete();
+
+ Assertions.assertEquals(
+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp2.getStatus());
+
+ ErrorResponse errorResp2 = resp2.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResp2.getCode());
+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResp2.getType());
+ }
+
+ private void assertUpdateView(ViewUpdatesRequest req, View updatedView) {
+ when(dispatcher.alterView(any(), any(ViewChange[].class))).thenReturn(updatedView);
+
+ Response resp =
+ target(viewPath(metalake, catalog, schema) + "/view1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept(VND_V1_JSON)
+ .put(Entity.entity(req, VND_V1_JSON));
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+
+ ViewResponse viewResp = resp.readEntity(ViewResponse.class);
+ Assertions.assertEquals(0, viewResp.getCode());
+
+ ViewDTO dto = viewResp.getView();
+ Assertions.assertEquals(updatedView.name(), dto.name());
+ Assertions.assertEquals(updatedView.comment(), dto.comment());
+ Assertions.assertEquals(updatedView.properties(), dto.properties());
+ }
+
+ private View mockView(
+ String name, String comment, Map<String, String> properties, String dialect, String sql) {
+ View mockedView = mock(View.class);
+ when(mockedView.name()).thenReturn(name);
+ when(mockedView.comment()).thenReturn(comment);
+ when(mockedView.properties()).thenReturn(properties);
+ when(mockedView.columns()).thenReturn(new Column[0]);
+ SQLRepresentation rep = SQLRepresentation.builder().withDialect(dialect).withSql(sql).build();
+ when(mockedView.representations()).thenReturn(new Representation[] {rep});
+
+ Audit mockAudit = mock(Audit.class);
+ when(mockAudit.creator()).thenReturn("gravitino");
+ when(mockAudit.createTime()).thenReturn(Instant.now());
+ when(mockedView.auditInfo()).thenReturn(mockAudit);
+
+ return mockedView;
+ }
+
+ private String viewPath(String metalake, String catalog, String schema) {
+ return "/metalakes/" + metalake + "/catalogs/" + catalog + "/schemas/" + schema + "/views";
+ }
+}