Skip to content

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

[#10991] feat(catalog-iceberg): implement view CRUD with complete delegation (#10992)

mchades52392dd12321
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java
index 99f143e8ad..a0e985ea49 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergCatalogOperations.java
@@ -50,6 +50,7 @@ import org.apache.gravitino.exceptions.NoSuchViewException;
import org.apache.gravitino.exceptions.NonEmptySchemaException;
import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
import org.apache.gravitino.exceptions.TableAlreadyExistsException;
+import org.apache.gravitino.exceptions.ViewAlreadyExistsException;
import org.apache.gravitino.iceberg.common.IcebergConfig;
import org.apache.gravitino.iceberg.common.authentication.AuthenticationConfig;
import org.apache.gravitino.iceberg.common.authentication.SupportsKerberos;
@@ -58,11 +59,13 @@ import org.apache.gravitino.iceberg.common.ops.IcebergCatalogWrapper.IcebergTabl
import org.apache.gravitino.iceberg.common.ops.KerberosAwareIcebergCatalogProxy;
import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Representation;
import org.apache.gravitino.rel.Table;
import org.apache.gravitino.rel.TableCatalog;
import org.apache.gravitino.rel.TableChange;
import org.apache.gravitino.rel.View;
import org.apache.gravitino.rel.ViewCatalog;
+import org.apache.gravitino.rel.ViewChange;
import org.apache.gravitino.rel.expressions.distributions.Distribution;
import org.apache.gravitino.rel.expressions.distributions.Distributions;
import org.apache.gravitino.rel.expressions.sorts.SortOrder;
@@ -80,7 +83,6 @@ import org.apache.iceberg.rest.requests.UpdateNamespacePropertiesRequest;
import org.apache.iceberg.rest.responses.GetNamespaceResponse;
import org.apache.iceberg.rest.responses.ListTablesResponse;
import org.apache.iceberg.rest.responses.LoadTableResponse;
-import org.apache.iceberg.rest.responses.LoadViewResponse;
import org.apache.iceberg.rest.responses.UpdateNamespacePropertiesResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -96,6 +98,7 @@ public class IcebergCatalogOperations
@VisibleForTesting IcebergCatalogWrapper icebergCatalogWrapper;
private IcebergCatalogWrapperHelper icebergCatalogWrapperHelper;
+ private IcebergViewCatalogOperations icebergViewCatalogOperations;
/**
* Initializes the Iceberg catalog operations with the provided configuration.
@@ -130,6 +133,7 @@ public class IcebergCatalogOperations
: rawWrapper;
this.icebergCatalogWrapperHelper =
new IcebergCatalogWrapperHelper(icebergCatalogWrapper.getCatalog());
+ this.icebergViewCatalogOperations = new IcebergViewCatalogOperations(icebergCatalogWrapper);
}
/** Closes the Iceberg catalog and releases the associated client pool. */
@@ -636,16 +640,89 @@ public class IcebergCatalogOperations
*/
@Override
public View loadView(NameIdentifier ident) throws NoSuchViewException {
- try {
- LoadViewResponse response =
- icebergCatalogWrapper.loadView(
- IcebergCatalogWrapperHelper.buildIcebergTableIdentifier(ident));
+ return viewCatalogOperations().loadView(ident);
+ }
- return IcebergView.fromLoadViewResponse(response, ident.name());
- } catch (Exception e) {
- throw new NoSuchViewException(
- e, "Failed to load view %s from Iceberg catalog: %s", ident, e.getMessage());
- }
+ /**
+ * Checks whether a view exists in the Iceberg catalog.
+ *
+ * @param ident A view identifier.
+ * @return {@code true} if the view exists, {@code false} otherwise.
+ */
+ @Override
+ public boolean viewExists(NameIdentifier ident) {
+ return viewCatalogOperations().viewExists(ident);
+ }
+
+ /**
+ * Lists all views in the given namespace from the Iceberg catalog.
+ *
+ * @param namespace A namespace.
+ * @return An array of view identifiers in the namespace.
+ * @throws NoSuchSchemaException If the schema does not exist.
+ */
+ @Override
+ public NameIdentifier[] listViews(Namespace namespace) throws NoSuchSchemaException {
+ return viewCatalogOperations().listViews(namespace);
+ }
+
+ /**
+ * Creates a view in the Iceberg catalog with the specified columns, representations, and
+ * properties.
+ *
+ * @param ident A view identifier.
+ * @param comment A view comment.
+ * @param columns The view output columns.
+ * @param representations The SQL representations of the view.
+ * @param defaultCatalog The default catalog used to resolve unqualified identifiers in SQL
+ * representations. This value is stored in Iceberg's view version metadata.
+ * @param defaultSchema The default schema used to resolve unqualified identifiers in SQL
+ * representations. When provided, it is used as the default namespace for the view version.
+ * @param properties The view properties.
+ * @return The created view metadata.
+ * @throws NoSuchSchemaException If the schema does not exist.
+ * @throws ViewAlreadyExistsException If the view already exists.
+ */
+ @Override
+ public View createView(
+ NameIdentifier ident,
+ String comment,
+ Column[] columns,
+ Representation[] representations,
+ String defaultCatalog,
+ String defaultSchema,
+ Map<String, String> properties)
+ throws NoSuchSchemaException, ViewAlreadyExistsException {
+ return viewCatalogOperations()
+ .createView(
+ ident, comment, columns, representations, defaultCatalog, defaultSchema, properties);
+ }
+
+ /**
+ * Applies {@link ViewChange changes} to an existing view in the Iceberg catalog. Rename cannot be
+ * combined with other changes.
+ *
+ * @param ident A view identifier.
+ * @param changes View changes to apply.
+ * @return The updated view metadata.
+ * @throws NoSuchViewException If the view does not exist.
+ * @throws IllegalArgumentException If the change is rejected by the implementation.
+ */
+ @Override
+ public View alterView(NameIdentifier ident, ViewChange... changes)
+ throws NoSuchViewException, IllegalArgumentException {
+ return viewCatalogOperations().alterView(ident, changes);
+ }
+
+ /**
+ * Drops a view from the Iceberg catalog.
+ *
+ * @param ident A view identifier.
+ * @return {@code true} if the view was dropped, {@code false} if the view does not exist.
+ */
+ @Override
+ public boolean dropView(NameIdentifier ident) {
+ return viewCatalogOperations().dropView(ident);
}
private static Distribution getIcebergDefaultDistribution(
@@ -661,4 +738,8 @@ public class IcebergCatalogOperations
private static String currentUser() {
return PrincipalUtils.getCurrentUserName();
}
+
+ private IcebergViewCatalogOperations viewCatalogOperations() {
+ return icebergViewCatalogOperations;
+ }
}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergView.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergView.java
index 955b0ed98c..3ef1028fd8 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergView.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergView.java
@@ -23,38 +23,75 @@ import java.util.Collections;
import java.util.Map;
import lombok.Getter;
import lombok.ToString;
+import org.apache.gravitino.catalog.lakehouse.iceberg.converter.ConvertUtil;
import org.apache.gravitino.meta.AuditInfo;
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.iceberg.Schema;
import org.apache.iceberg.rest.responses.LoadViewResponse;
+import org.apache.iceberg.view.SQLViewRepresentation;
+import org.apache.iceberg.view.ViewMetadata;
+import org.apache.iceberg.view.ViewVersion;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/** Represents an Apache Iceberg View entity in the Iceberg catalog. */
@ToString
@Getter
public class IcebergView implements View {
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergView.class);
+
private String name;
+ private String comment;
+ private String defaultCatalog;
+ private String defaultSchema;
+ private Column[] columns;
+ private Representation[] representations;
private Map<String, String> properties;
private AuditInfo auditInfo;
private IcebergView() {}
/**
- * Converts an Iceberg LoadViewResponse to a Gravitino IcebergView.
+ * Converts an Iceberg LoadViewResponse to a Gravitino IcebergView, extracting columns,
+ * representations, and comment from the view metadata.
*
* @param response The Iceberg LoadViewResponse.
* @param viewName The name of the view.
* @return A new IcebergView instance.
*/
public static IcebergView fromLoadViewResponse(LoadViewResponse response, String viewName) {
+ ViewMetadata metadata = response.metadata();
+ if (metadata == null) {
+ return IcebergView.builder()
+ .withName(viewName)
+ .withProperties(Maps.newHashMap())
+ .withColumns(new Column[0])
+ .withRepresentations(new Representation[0])
+ .withAuditInfo(AuditInfo.EMPTY)
+ .build();
+ }
+
Map<String, String> properties =
- response.metadata() != null && response.metadata().properties() != null
- ? Maps.newHashMap(response.metadata().properties())
- : Maps.newHashMap();
+ metadata.properties() != null ? Maps.newHashMap(metadata.properties()) : Maps.newHashMap();
+ String comment = properties.get("comment");
+ ViewVersion currentVersion = metadata.currentVersion();
+ String defaultCatalog = currentVersion.defaultCatalog();
+ String defaultSchema = extractDefaultSchema(currentVersion);
+
+ Column[] columns = extractColumns(metadata);
+ Representation[] representations = extractRepresentations(metadata);
return IcebergView.builder()
.withName(viewName)
+ .withComment(comment)
+ .withDefaultCatalog(defaultCatalog)
+ .withDefaultSchema(defaultSchema)
+ .withColumns(columns)
+ .withRepresentations(representations)
.withProperties(properties)
.withAuditInfo(AuditInfo.EMPTY)
.build();
@@ -66,18 +103,33 @@ public class IcebergView implements View {
}
@Override
- public Map<String, String> properties() {
- return properties != null ? properties : Collections.emptyMap();
+ public String comment() {
+ return comment;
+ }
+
+ @Override
+ public String defaultCatalog() {
+ return defaultCatalog;
+ }
+
+ @Override
+ public String defaultSchema() {
+ return defaultSchema;
}
@Override
public Column[] columns() {
- return new Column[0];
+ return columns != null ? columns : new Column[0];
}
@Override
public Representation[] representations() {
- return new Representation[0];
+ return representations != null ? representations : new Representation[0];
+ }
+
+ @Override
+ public Map<String, String> properties() {
+ return properties != null ? properties : Collections.emptyMap();
}
@Override
@@ -90,6 +142,46 @@ public class IcebergView implements View {
return new Builder();
}
+ private static Column[] extractColumns(ViewMetadata metadata) {
+ try {
+ Schema schema = metadata.schema();
+ if (schema != null && schema.columns() != null) {
+ return schema.columns().stream().map(ConvertUtil::fromNestedField).toArray(Column[]::new);
+ }
+ } catch (Exception e) {
+ LOG.warn("Failed to extract columns from Iceberg view metadata", e);
+ }
+ return new Column[0];
+ }
+
+ private static Representation[] extractRepresentations(ViewMetadata metadata) {
+ try {
+ ViewVersion currentVersion = metadata.currentVersion();
+ return currentVersion.representations().stream()
+ .filter(r -> r instanceof SQLViewRepresentation)
+ .map(
+ r -> {
+ SQLViewRepresentation sqlRep = (SQLViewRepresentation) r;
+ return (Representation)
+ SQLRepresentation.builder()
+ .withDialect(sqlRep.dialect())
+ .withSql(sqlRep.sql())
+ .build();
+ })
+ .toArray(Representation[]::new);
+ } catch (Exception e) {
+ LOG.warn("Failed to extract representations from Iceberg view metadata", e);
+ }
+ return new Representation[0];
+ }
+
+ private static String extractDefaultSchema(ViewVersion currentVersion) {
+ if (currentVersion.defaultNamespace() == null) {
+ return null;
+ }
+ return currentVersion.defaultNamespace().toString();
+ }
+
/** Builder for IcebergView. */
public static class Builder {
private final IcebergView view;
@@ -103,6 +195,31 @@ public class IcebergView implements View {
return this;
}
+ public Builder withComment(String comment) {
+ view.comment = comment;
+ return this;
+ }
+
+ public Builder withDefaultCatalog(String defaultCatalog) {
+ view.defaultCatalog = defaultCatalog;
+ return this;
+ }
+
+ public Builder withDefaultSchema(String defaultSchema) {
+ view.defaultSchema = defaultSchema;
+ return this;
+ }
+
+ public Builder withColumns(Column[] columns) {
+ view.columns = columns;
+ return this;
+ }
+
+ public Builder withRepresentations(Representation[] representations) {
+ view.representations = representations;
+ return this;
+ }
+
public Builder withProperties(Map<String, String> properties) {
view.properties = properties != null ? Maps.newHashMap(properties) : Maps.newHashMap();
return this;
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergViewCatalogOperations.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergViewCatalogOperations.java
new file mode 100644
index 0000000000..776f9e1810
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/IcebergViewCatalogOperations.java
@@ -0,0 +1,446 @@
+/*
+ * 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.catalog.lakehouse.iceberg;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.catalog.lakehouse.iceberg.converter.ConvertUtil;
+import org.apache.gravitino.catalog.lakehouse.iceberg.ops.IcebergCatalogWrapperHelper;
+import org.apache.gravitino.exceptions.NoSuchSchemaException;
+import org.apache.gravitino.exceptions.NoSuchViewException;
+import org.apache.gravitino.exceptions.ViewAlreadyExistsException;
+import org.apache.gravitino.iceberg.common.ops.IcebergCatalogWrapper;
+import org.apache.gravitino.meta.AuditInfo;
+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.utils.PrincipalUtils;
+import org.apache.iceberg.MetadataUpdate;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.UpdateRequirements;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.exceptions.AlreadyExistsException;
+import org.apache.iceberg.exceptions.NoSuchNamespaceException;
+import org.apache.iceberg.rest.requests.ImmutableCreateViewRequest;
+import org.apache.iceberg.rest.requests.RenameTableRequest;
+import org.apache.iceberg.rest.requests.UpdateTableRequest;
+import org.apache.iceberg.rest.responses.ListTablesResponse;
+import org.apache.iceberg.rest.responses.LoadViewResponse;
+import org.apache.iceberg.view.ImmutableSQLViewRepresentation;
+import org.apache.iceberg.view.ImmutableViewVersion;
+import org.apache.iceberg.view.SQLViewRepresentation;
+import org.apache.iceberg.view.ViewMetadata;
+import org.apache.iceberg.view.ViewRepresentation;
+import org.apache.iceberg.view.ViewVersion;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** View catalog operations for Iceberg. */
+class IcebergViewCatalogOperations {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IcebergViewCatalogOperations.class);
+
+ private static final int INITIAL_VIEW_VERSION_ID = 1;
+
+ /** Iceberg sentinel value for {@code SetCurrentViewVersion}: "use the last added version". */
+ private static final int ICEBERG_LAST_ADDED_VIEW_VERSION = -1;
+
+ private final IcebergCatalogWrapper icebergCatalogWrapper;
+
+ IcebergViewCatalogOperations(IcebergCatalogWrapper icebergCatalogWrapper) {
+ Preconditions.checkArgument(
+ icebergCatalogWrapper != null, "icebergCatalogWrapper must not be null");
+ this.icebergCatalogWrapper = icebergCatalogWrapper;
+ }
+
+ public View loadView(NameIdentifier ident) throws NoSuchViewException {
+ try {
+ LoadViewResponse response =
+ icebergCatalogWrapper.loadView(
+ IcebergCatalogWrapperHelper.buildIcebergTableIdentifier(ident));
+ return IcebergView.fromLoadViewResponse(response, ident.name());
+ } catch (org.apache.iceberg.exceptions.NoSuchViewException e) {
+ throw new NoSuchViewException(e, "Iceberg view %s does not exist", ident);
+ }
+ }
+
+ public boolean viewExists(NameIdentifier ident) {
+ return icebergCatalogWrapper.viewExists(
+ IcebergCatalogWrapperHelper.buildIcebergTableIdentifier(ident));
+ }
+
+ public NameIdentifier[] listViews(Namespace namespace) throws NoSuchSchemaException {
+ org.apache.iceberg.catalog.Namespace icebergNamespace =
+ IcebergCatalogWrapperHelper.getIcebergNamespace(namespace);
+ if (!icebergCatalogWrapper.namespaceExists(icebergNamespace)) {
+ throw new NoSuchSchemaException("Schema %s does not exist", namespace);
+ }
+ try {
+ ListTablesResponse response = icebergCatalogWrapper.listView(icebergNamespace);
+ return response.identifiers().stream()
+ .map(id -> NameIdentifier.of(ArrayUtils.add(namespace.levels(), id.name())))
+ .toArray(NameIdentifier[]::new);
+ } catch (NoSuchNamespaceException e) {
+ throw new NoSuchSchemaException("Schema does not exist %s in Iceberg", namespace);
+ }
+ }
+
+ public View createView(
+ NameIdentifier ident,
+ String comment,
+ Column[] columns,
+ Representation[] representations,
+ String defaultCatalog,
+ String defaultSchema,
+ Map<String, String> properties)
+ throws NoSuchSchemaException, ViewAlreadyExistsException {
+ org.apache.iceberg.catalog.Namespace icebergNamespace =
+ IcebergCatalogWrapperHelper.getIcebergNamespace(ident.namespace());
+
+ Schema schema = ConvertUtil.toIcebergSchema(columns);
+ List<ViewRepresentation> viewRepresentations = new ArrayList<>();
+ for (Representation representation : representations) {
+ viewRepresentations.add(toSqlViewRepresentation(representation));
+ }
+ Representation[] sqlRepresentations =
+ viewRepresentations.stream()
+ .map(IcebergViewCatalogOperations::toSqlRepresentation)
+ .toArray(SQLRepresentation[]::new);
+
+ org.apache.iceberg.catalog.Namespace defaultNamespace =
+ defaultSchema != null
+ ? IcebergCatalogWrapperHelper.getIcebergNamespace(defaultSchema)
+ : icebergNamespace;
+
+ ViewVersion viewVersion =
+ ImmutableViewVersion.builder()
+ .versionId(INITIAL_VIEW_VERSION_ID)
+ .timestampMillis(System.currentTimeMillis())
+ .schemaId(schema.schemaId())
+ .defaultNamespace(defaultNamespace)
+ .representations(viewRepresentations)
+ .putSummary("operation", "create")
+ .defaultCatalog(defaultCatalog)
+ .build();
+
+ Map<String, String> allProperties =
+ properties != null ? Maps.newHashMap(properties) : Maps.newHashMap();
+ if (comment != null) {
+ allProperties.put("comment", comment);
+ }
+
+ ImmutableCreateViewRequest request =
+ ImmutableCreateViewRequest.builder()
+ .name(ident.name())
+ .schema(schema)
+ .viewVersion(viewVersion)
+ .properties(allProperties)
+ .build();
+
+ try {
+ icebergCatalogWrapper.createView(icebergNamespace, request);
+ LOG.info("Created Iceberg view {}", ident);
+ return IcebergView.builder()
+ .withName(ident.name())
+ .withComment(comment)
+ .withDefaultCatalog(defaultCatalog)
+ .withDefaultSchema(defaultNamespace.toString())
+ .withColumns(columns)
+ .withRepresentations(sqlRepresentations)
+ .withProperties(allProperties)
+ .withAuditInfo(
+ AuditInfo.builder().withCreator(currentUser()).withCreateTime(Instant.now()).build())
+ .build();
+ } catch (AlreadyExistsException e) {
+ throw new ViewAlreadyExistsException(e, "View %s already exists in Iceberg catalog", ident);
+ } catch (NoSuchNamespaceException e) {
+ throw new NoSuchSchemaException(
+ e, "Schema does not exist for view %s in Iceberg catalog", ident);
+ }
+ }
+
+ public View alterView(NameIdentifier ident, ViewChange... changes)
+ throws NoSuchViewException, IllegalArgumentException {
+ Optional<ViewChange> renameOptional =
+ Arrays.stream(changes).filter(c -> c instanceof ViewChange.RenameView).reduce((a, b) -> b);
+ if (renameOptional.isPresent()) {
+ long nonRenameChangeCount =
+ Arrays.stream(changes).filter(c -> !(c instanceof ViewChange.RenameView)).count();
+ if (nonRenameChangeCount > 0) {
+ throw new IllegalArgumentException("Rename cannot be combined with other view changes.");
+ }
+ return renameView(ident, (ViewChange.RenameView) renameOptional.get());
+ }
+ return internalUpdateView(ident, changes);
+ }
+
+ public boolean dropView(NameIdentifier ident) {
+ try {
+ icebergCatalogWrapper.dropView(
+ IcebergCatalogWrapperHelper.buildIcebergTableIdentifier(ident));
+ LOG.info("Dropped Iceberg view {}", ident);
+ return true;
+ } catch (org.apache.iceberg.exceptions.NoSuchViewException e) {
+ LOG.warn("Iceberg view {} does not exist, skip dropping", ident);
+ return false;
+ }
+ }
+
+ private View renameView(NameIdentifier ident, ViewChange.RenameView rename)
+ throws NoSuchViewException {
+ try {
+ RenameTableRequest request =
+ RenameTableRequest.builder()
+ .withSource(IcebergCatalogWrapperHelper.buildIcebergTableIdentifier(ident))
+ .withDestination(
+ IcebergCatalogWrapperHelper.buildIcebergTableIdentifier(
+ ident.namespace(), rename.getNewName()))
+ .build();
+ icebergCatalogWrapper.renameView(request);
+ return loadView(
+ NameIdentifier.of(ArrayUtils.add(ident.namespace().levels(), rename.getNewName())));
+ } catch (org.apache.iceberg.exceptions.NoSuchViewException e) {
+ throw new NoSuchViewException(e, "Iceberg view %s does not exist", ident);
+ }
+ }
+
+ private View internalUpdateView(NameIdentifier ident, ViewChange... changes)
+ throws NoSuchViewException, IllegalArgumentException {
+ TableIdentifier viewId = IcebergCatalogWrapperHelper.buildIcebergTableIdentifier(ident);
+ try {
+ LoadViewResponse current = icebergCatalogWrapper.loadView(viewId);
+ ViewMetadata metadata = current.metadata();
+
+ GroupedViewChanges groupedChanges = groupViewChanges(changes);
+
+ List<MetadataUpdate> updates =
+ new ArrayList<>(
+ buildPropertyMetadataUpdates(
+ groupedChanges.setProperties(), groupedChanges.removedProperties()));
+ groupedChanges
+ .replaceView()
+ .ifPresent(
+ replaceView ->
+ updates.addAll(buildNewViewVersionUpdates(ident, replaceView, metadata)));
+
+ if (updates.isEmpty()) {
+ return loadView(ident);
+ }
+
+ UpdateTableRequest request =
+ UpdateTableRequest.create(
+ viewId, UpdateRequirements.forReplaceView(metadata, updates), updates);
+ LoadViewResponse response = icebergCatalogWrapper.updateView(viewId, request);
+ LOG.info("Altered Iceberg view {}", ident);
+ return IcebergView.fromLoadViewResponse(response, ident.name());
+ } catch (org.apache.iceberg.exceptions.NoSuchViewException e) {
+ throw new NoSuchViewException(e, "Iceberg view %s does not exist", ident);
+ }
+ }
+
+ /** Grouped result of processing view changes. */
+ private static final class GroupedViewChanges {
+
+ private final Map<String, String> setProperties;
+ private final Set<String> removedProperties;
+ private final ViewChange.ReplaceView replaceView;
+
+ private GroupedViewChanges(
+ Map<String, String> setProperties,
+ Set<String> removedProperties,
+ ViewChange.ReplaceView replaceView) {
+ this.setProperties = setProperties;
+ this.removedProperties = removedProperties;
+ this.replaceView = replaceView;
+ }
+
+ private Map<String, String> setProperties() {
+ return setProperties;
+ }
+
+ private Set<String> removedProperties() {
+ return removedProperties;
+ }
+
+ private Optional<ViewChange.ReplaceView> replaceView() {
+ return Optional.ofNullable(replaceView);
+ }
+ }
+
+ /**
+ * Groups view changes by processing them in order so the last change for a key wins. The method
+ * also captures the last {@link ViewChange.ReplaceView} if present.
+ */
+ private static GroupedViewChanges groupViewChanges(ViewChange[] changes) {
+ Map<String, String> setProps = new HashMap<>();
+ Set<String> removeProps = new HashSet<>();
+ ViewChange.ReplaceView replace = null;
+ for (ViewChange change : changes) {
+ if (change instanceof ViewChange.SetProperty) {
+ ViewChange.SetProperty setProperty = (ViewChange.SetProperty) change;
+ String property = setProperty.getProperty();
+ setProps.put(property, setProperty.getValue());
+ removeProps.remove(property);
+ } else if (change instanceof ViewChange.RemoveProperty) {
+ String property = ((ViewChange.RemoveProperty) change).getProperty();
+ removeProps.add(property);
+ setProps.remove(property);
+ } else if (change instanceof ViewChange.ReplaceView) {
+ replace = (ViewChange.ReplaceView) change;
+ applyReplaceViewProperties(replace, setProps, removeProps);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported view change type: " + change.getClass().getSimpleName());
+ }
+ }
+ return new GroupedViewChanges(setProps, removeProps, replace);
+ }
+
+ /**
+ * Applies the implicit property side-effects of a {@link ViewChange.ReplaceView}: sets or removes
+ * {@code comment}. This should be invoked in the order changes are processed so subsequent
+ * explicit property changes can override these values.
+ */
+ private static void applyReplaceViewProperties(
+ ViewChange.ReplaceView replace, Map<String, String> setProps, Set<String> removeProps) {
+ if (replace.getComment() == null) {
+ removeProps.add("comment");
+ setProps.remove("comment");
+ } else {
+ setProps.put("comment", replace.getComment());
+ removeProps.remove("comment");
+ }
+ }
+
+ /** Converts {@code setProps} and {@code removeProps} into the corresponding MetadataUpdates. */
+ private static List<MetadataUpdate> buildPropertyMetadataUpdates(
+ Map<String, String> setProps, Set<String> removeProps) {
+ List<MetadataUpdate> updates = new ArrayList<>();
+ if (!setProps.isEmpty()) {
+ updates.add(new MetadataUpdate.SetProperties(setProps));
+ }
+ if (!removeProps.isEmpty()) {
+ updates.add(new MetadataUpdate.RemoveProperties(removeProps));
+ }
+ return updates;
+ }
+
+ /**
+ * Builds the schema-and-version MetadataUpdates required to replace a view's SQL definition.
+ * Reuses an existing schema when the column layout matches; otherwise adds a new one.
+ */
+ private static List<MetadataUpdate> buildNewViewVersionUpdates(
+ NameIdentifier ident, ViewChange.ReplaceView replace, ViewMetadata metadata) {
+ List<MetadataUpdate> updates = new ArrayList<>();
+ ViewVersion currentVersion = metadata.currentVersion();
+
+ int newVersionId =
+ currentVersion != null ? currentVersion.versionId() + 1 : INITIAL_VIEW_VERSION_ID;
+
+ Schema replacementSchema = ConvertUtil.toIcebergSchema(replace.getColumns());
+ Optional<Schema> existingSchema =
+ metadata.schemas().stream()
+ .filter(schema -> schema.sameSchema(replacementSchema))
+ .findFirst();
+ int schemaId;
+ if (existingSchema.isPresent()) {
+ schemaId = existingSchema.get().schemaId();
+ } else {
+ int newSchemaId = metadata.schemas().stream().mapToInt(Schema::schemaId).max().orElse(-1) + 1;
+ Schema newSchema =
+ new Schema(
+ newSchemaId, replacementSchema.columns(), replacementSchema.identifierFieldIds());
+ updates.add(new MetadataUpdate.AddSchema(newSchema));
+ schemaId = newSchemaId;
+ }
+
+ org.apache.iceberg.catalog.Namespace defaultNamespace =
+ replace.getDefaultSchema() != null
+ ? IcebergCatalogWrapperHelper.getIcebergNamespace(replace.getDefaultSchema())
+ : (currentVersion != null
+ ? currentVersion.defaultNamespace()
+ : IcebergCatalogWrapperHelper.getIcebergNamespace(ident.namespace()));
+
+ List<ViewRepresentation> newRepresentations = new ArrayList<>();
+ for (Representation representation : replace.getRepresentations()) {
+ newRepresentations.add(toSqlViewRepresentation(representation));
+ }
+
+ ViewVersion newVersion =
+ ImmutableViewVersion.builder()
+ .versionId(newVersionId)
+ .timestampMillis(System.currentTimeMillis())
+ .schemaId(schemaId)
+ .defaultNamespace(defaultNamespace)
+ .representations(newRepresentations)
+ .putSummary("operation", "alter")
+ .defaultCatalog(replace.getDefaultCatalog())
+ .build();
+
+ updates.add(new MetadataUpdate.AddViewVersion(newVersion));
+ updates.add(new MetadataUpdate.SetCurrentViewVersion(ICEBERG_LAST_ADDED_VIEW_VERSION));
+ return updates;
+ }
+
+ private static ViewRepresentation toSqlViewRepresentation(Representation representation) {
+ SQLRepresentation sqlRepresentation = normalizeSqlRepresentation(representation);
+ return ImmutableSQLViewRepresentation.builder()
+ .sql(sqlRepresentation.sql())
+ .dialect(sqlRepresentation.dialect())
+ .build();
+ }
+
+ private static SQLRepresentation toSqlRepresentation(ViewRepresentation viewRepresentation) {
+ Preconditions.checkArgument(
+ viewRepresentation instanceof SQLViewRepresentation,
+ "Iceberg catalog only supports SQL view representation, but got: %s",
+ viewRepresentation == null ? "null" : viewRepresentation.getClass().getSimpleName());
+ SQLViewRepresentation sqlViewRepresentation = (SQLViewRepresentation) viewRepresentation;
+ return SQLRepresentation.builder()
+ .withDialect(sqlViewRepresentation.dialect())
+ .withSql(sqlViewRepresentation.sql())
+ .build();
+ }
+
+ private static SQLRepresentation normalizeSqlRepresentation(Representation representation) {
+ Preconditions.checkArgument(
+ representation instanceof SQLRepresentation,
+ "Iceberg catalog only supports SQLRepresentation, but got: %s",
+ representation == null ? "null" : representation.getClass().getSimpleName());
+ return (SQLRepresentation) representation;
+ }
+
+ private static String currentUser() {
+ return PrincipalUtils.getCurrentUserName();
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.java b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.java
index d49b2ab7b3..3443c5782e 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/main/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/ConvertUtil.java
@@ -18,9 +18,11 @@
*/
package org.apache.gravitino.catalog.lakehouse.iceberg.converter;
+import com.google.common.base.Preconditions;
import java.util.Arrays;
import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergColumn;
import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergTable;
+import org.apache.gravitino.rel.Column;
import org.apache.iceberg.Schema;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.Types;
@@ -41,6 +43,27 @@ public class ConvertUtil {
return new Schema(converted.asNestedType().asStructType().fields());
}
+ /**
+ * Convert an array of Gravitino columns to an Iceberg Schema.
+ *
+ * @param columns Gravitino columns.
+ * @return Iceberg schema.
+ */
+ public static Schema toIcebergSchema(Column[] columns) {
+ Preconditions.checkArgument(columns != null, "columns must not be null");
+ org.apache.gravitino.rel.types.Types.StructType.Field[] fields =
+ Arrays.stream(columns)
+ .map(
+ col ->
+ org.apache.gravitino.rel.types.Types.StructType.Field.of(
+ col.name(), col.dataType(), col.nullable(), col.comment()))
+ .toArray(org.apache.gravitino.rel.types.Types.StructType.Field[]::new);
+ org.apache.gravitino.rel.types.Types.StructType structType =
+ org.apache.gravitino.rel.types.Types.StructType.of(fields);
+ Type converted = ToIcebergTypeVisitor.visit(structType, new ToIcebergType(structType));
+ return new Schema(converted.asNestedType().asStructType().fields());
+ }
+
/**
* Convert the nested field of Iceberg to the Iceberg column.
*
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergView.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergView.java
index cfc9563663..f6dfae0146 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergView.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergView.java
@@ -22,10 +22,21 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableMap;
+import java.util.Arrays;
+import java.util.Collections;
import java.util.Map;
import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Representation;
+import org.apache.gravitino.rel.SQLRepresentation;
+import org.apache.gravitino.rel.types.Types;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.rest.responses.LoadViewResponse;
+import org.apache.iceberg.types.Types.NestedField;
+import org.apache.iceberg.view.SQLViewRepresentation;
import org.apache.iceberg.view.ViewMetadata;
+import org.apache.iceberg.view.ViewVersion;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -35,8 +46,11 @@ public class TestIcebergView {
public void testFromLoadViewResponse() {
// Test with properties
Map<String, String> properties = ImmutableMap.of("key1", "value1", "key2", "value2");
+ ViewVersion mockVersion = mock(ViewVersion.class);
+ when(mockVersion.representations()).thenReturn(Collections.emptyList());
ViewMetadata mockMetadata = mock(ViewMetadata.class);
when(mockMetadata.properties()).thenReturn(properties);
+ when(mockMetadata.currentVersion()).thenReturn(mockVersion);
LoadViewResponse mockResponse = mock(LoadViewResponse.class);
when(mockResponse.metadata()).thenReturn(mockMetadata);
@@ -65,8 +79,11 @@ public class TestIcebergView {
@Test
public void testFromLoadViewResponseWithNullMetadataProperties() {
// Test with null properties in metadata
+ ViewVersion mockVersion = mock(ViewVersion.class);
+ when(mockVersion.representations()).thenReturn(Collections.emptyList());
ViewMetadata mockMetadata = mock(ViewMetadata.class);
when(mockMetadata.properties()).thenReturn(null);
+ when(mockMetadata.currentVersion()).thenReturn(mockVersion);
LoadViewResponse mockResponse = mock(LoadViewResponse.class);
when(mockResponse.metadata()).thenReturn(mockMetadata);
@@ -107,4 +124,137 @@ public class TestIcebergView {
Assertions.assertNotNull(view.properties());
Assertions.assertTrue(view.properties().isEmpty());
}
+
+ @Test
+ public void testFromLoadViewResponseExtractsComment() {
+ Map<String, String> properties = ImmutableMap.of("comment", "my view comment", "key", "val");
+ ViewVersion mockVersion = mock(ViewVersion.class);
+ when(mockVersion.representations()).thenReturn(Collections.emptyList());
+ ViewMetadata mockMetadata = mock(ViewMetadata.class);
+ when(mockMetadata.properties()).thenReturn(properties);
+ when(mockMetadata.currentVersion()).thenReturn(mockVersion);
+
+ LoadViewResponse mockResponse = mock(LoadViewResponse.class);
+ when(mockResponse.metadata()).thenReturn(mockMetadata);
+
+ IcebergView view = IcebergView.fromLoadViewResponse(mockResponse, "comment_view");
+
+ Assertions.assertEquals("my view comment", view.comment());
+ Assertions.assertEquals(properties, view.properties());
+ }
+
+ @Test
+ public void testFromLoadViewResponseExtractsRepresentations() {
+ Map<String, String> properties = ImmutableMap.of("key", "val");
+
+ SQLViewRepresentation sqlRep = mock(SQLViewRepresentation.class);
+ when(sqlRep.dialect()).thenReturn("spark");
+ when(sqlRep.sql()).thenReturn("SELECT id FROM t1");
+
+ ViewVersion mockVersion = mock(ViewVersion.class);
+ when(mockVersion.representations()).thenReturn(Collections.singletonList(sqlRep));
+
+ ViewMetadata mockMetadata = mock(ViewMetadata.class);
+ when(mockMetadata.properties()).thenReturn(properties);
+ when(mockMetadata.currentVersion()).thenReturn(mockVersion);
+
+ LoadViewResponse mockResponse = mock(LoadViewResponse.class);
+ when(mockResponse.metadata()).thenReturn(mockMetadata);
+
+ IcebergView view = IcebergView.fromLoadViewResponse(mockResponse, "rep_view");
+
+ Assertions.assertEquals(1, view.representations().length);
+ Representation rep = view.representations()[0];
+ Assertions.assertInstanceOf(SQLRepresentation.class, rep);
+ SQLRepresentation sqlRepResult = (SQLRepresentation) rep;
+ Assertions.assertEquals("spark", sqlRepResult.dialect());
+ Assertions.assertEquals("SELECT id FROM t1", sqlRepResult.sql());
+ }
+
+ @Test
+ public void testFromLoadViewResponseExtractsDefaultCatalogAndSchema() {
+ Map<String, String> properties = ImmutableMap.of("k", "v");
+
+ ViewVersion mockVersion = mock(ViewVersion.class);
+ when(mockVersion.representations()).thenReturn(Collections.emptyList());
+ when(mockVersion.defaultCatalog()).thenReturn("current_cat");
+ when(mockVersion.defaultNamespace()).thenReturn(Namespace.of("schema1"));
+
+ ViewMetadata mockMetadata = mock(ViewMetadata.class);
+ when(mockMetadata.properties()).thenReturn(properties);
+ when(mockMetadata.currentVersion()).thenReturn(mockVersion);
+
+ LoadViewResponse mockResponse = mock(LoadViewResponse.class);
+ when(mockResponse.metadata()).thenReturn(mockMetadata);
+
+ IcebergView view = IcebergView.fromLoadViewResponse(mockResponse, "default_view");
+
+ Assertions.assertEquals("current_cat", view.defaultCatalog());
+ Assertions.assertEquals("schema1", view.defaultSchema());
+ Assertions.assertEquals("v", view.properties().get("k"));
+ }
+
+ @Test
+ public void testFromLoadViewResponseExtractsColumns() {
+ Map<String, String> properties = ImmutableMap.of("key", "val");
+
+ ViewVersion mockVersion = mock(ViewVersion.class);
+ when(mockVersion.representations()).thenReturn(Collections.emptyList());
+
+ NestedField field1 =
+ NestedField.optional(1, "id", org.apache.iceberg.types.Types.LongType.get(), "id column");
+ NestedField field2 =
+ NestedField.required(2, "name", org.apache.iceberg.types.Types.StringType.get());
+
+ Schema schema = new Schema(Arrays.asList(field1, field2));
+
+ ViewMetadata mockMetadata = mock(ViewMetadata.class);
+ when(mockMetadata.properties()).thenReturn(properties);
+ when(mockMetadata.currentVersion()).thenReturn(mockVersion);
+ when(mockMetadata.schema()).thenReturn(schema);
+
+ LoadViewResponse mockResponse = mock(LoadViewResponse.class);
+ when(mockResponse.metadata()).thenReturn(mockMetadata);
+
+ IcebergView view = IcebergView.fromLoadViewResponse(mockResponse, "col_view");
+
+ Assertions.assertEquals(2, view.columns().length);
+ Assertions.assertEquals("id", view.columns()[0].name());
+ Assertions.assertTrue(view.columns()[0].nullable());
+ Assertions.assertEquals("id column", view.columns()[0].comment());
+ Assertions.assertEquals("name", view.columns()[1].name());
+ Assertions.assertFalse(view.columns()[1].nullable());
+ Assertions.assertEquals(Types.LongType.get(), view.columns()[0].dataType());
+ }
+
+ @Test
+ public void testBuilderWithAllFields() {
+ Column mockCol = mock(Column.class);
+ when(mockCol.name()).thenReturn("c1");
+
+ SQLRepresentation rep =
+ SQLRepresentation.builder().withDialect("trino").withSql("SELECT 1").build();
+ AuditInfo auditInfo = AuditInfo.builder().withCreator("user").withCreateTime(null).build();
+
+ IcebergView view =
+ IcebergView.builder()
+ .withName("full_view")
+ .withComment("full view")
+ .withDefaultCatalog("cat1")
+ .withDefaultSchema("schema1")
+ .withColumns(new Column[] {mockCol})
+ .withRepresentations(new Representation[] {rep})
+ .withProperties(ImmutableMap.of("k", "v"))
+ .withAuditInfo(auditInfo)
+ .build();
+
+ Assertions.assertEquals("full_view", view.name());
+ Assertions.assertEquals("full view", view.comment());
+ Assertions.assertEquals("cat1", view.defaultCatalog());
+ Assertions.assertEquals("schema1", view.defaultSchema());
+ Assertions.assertEquals(1, view.columns().length);
+ Assertions.assertEquals("c1", view.columns()[0].name());
+ Assertions.assertEquals(1, view.representations().length);
+ Assertions.assertEquals("trino", ((SQLRepresentation) view.representations()[0]).dialect());
+ }
}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergViewCatalogOperations.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergViewCatalogOperations.java
new file mode 100644
index 0000000000..65ba63a7fa
--- /dev/null
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/TestIcebergViewCatalogOperations.java
@@ -0,0 +1,377 @@
+/*
+ * 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.catalog.lakehouse.iceberg;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.exceptions.NoSuchViewException;
+import org.apache.gravitino.iceberg.common.ops.IcebergCatalogWrapper;
+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.rel.types.Types;
+import org.apache.iceberg.MetadataUpdate;
+import org.apache.iceberg.UpdateRequirement;
+import org.apache.iceberg.UpdateRequirements;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.exceptions.ServiceFailureException;
+import org.apache.iceberg.rest.requests.ImmutableCreateViewRequest;
+import org.apache.iceberg.rest.requests.UpdateTableRequest;
+import org.apache.iceberg.rest.responses.LoadViewResponse;
+import org.apache.iceberg.view.ViewMetadata;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+public class TestIcebergViewCatalogOperations {
+
+ @Test
+ public void testLoadViewTranslatesOnlyNoSuchViewException() {
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+ when(wrapper.loadView(any(TableIdentifier.class)))
+ .thenThrow(new org.apache.iceberg.exceptions.NoSuchViewException("view missing"));
+
+ Assertions.assertThrows(NoSuchViewException.class, () -> operations.loadView(ident));
+ }
+
+ @Test
+ public void testLoadViewPropagatesNonNoSuchViewException() {
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+ when(wrapper.loadView(any(TableIdentifier.class)))
+ .thenThrow(new ServiceFailureException("backend unavailable"));
+
+ Assertions.assertThrows(ServiceFailureException.class, () -> operations.loadView(ident));
+ }
+
+ @Test
+ public void testViewExistsDelegatesToWrapper() {
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+ when(wrapper.viewExists(any(TableIdentifier.class))).thenReturn(true);
+
+ Assertions.assertTrue(operations.viewExists(ident));
+ verify(wrapper).viewExists(any(TableIdentifier.class));
+ }
+
+ @Test
+ public void testAlterViewRejectsRenameWithOtherChanges() {
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ operations.alterView(
+ ident, ViewChange.rename("view2"), ViewChange.setProperty("k", "v")));
+
+ Assertions.assertEquals(
+ "Rename cannot be combined with other view changes.", exception.getMessage());
+
+ verify(wrapper, never()).renameView(any());
+ }
+
+ @Test
+ public void testCreateViewRejectsSqlLikeRepresentationWithoutSqlRepresentationClass()
+ throws Exception {
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ Representation sqlLikeRepresentation =
+ new Representation() {
+ @Override
+ public String type() {
+ return Representation.TYPE_SQL;
+ }
+
+ public String dialect() {
+ return "spark";
+ }
+
+ public String sql() {
+ return "SELECT id FROM t";
+ }
+ };
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ operations.createView(
+ ident,
+ null,
+ columns,
+ new Representation[] {sqlLikeRepresentation},
+ null,
+ null,
+ Collections.emptyMap()));
+ Assertions.assertTrue(exception.getMessage().contains(SQLRepresentation.class.getSimpleName()));
+ }
+
+ @Test
+ public void testCreateViewStoresDefaultCatalogInViewVersion() throws Exception {
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ SQLRepresentation representation =
+ SQLRepresentation.builder().withDialect("spark").withSql("SELECT id FROM t").build();
+
+ doAnswer(
+ invocation -> {
+ ImmutableCreateViewRequest request = invocation.getArgument(1);
+ Assertions.assertEquals("catalog1", request.viewVersion().defaultCatalog());
+ Assertions.assertFalse(request.properties().containsKey("default-catalog"));
+ return mockLoadViewResponse();
+ })
+ .when(wrapper)
+ .createView(
+ any(org.apache.iceberg.catalog.Namespace.class), any(ImmutableCreateViewRequest.class));
+
+ View view =
+ operations.createView(
+ ident,
+ "test comment",
+ columns,
+ new Representation[] {representation},
+ "catalog1",
+ "schema1",
+ Collections.singletonMap("k", "v"));
+
+ Assertions.assertEquals("catalog1", view.defaultCatalog());
+ Assertions.assertEquals("schema1", view.defaultSchema());
+ Assertions.assertFalse(view.properties().containsKey("default-catalog"));
+ }
+
+ @Test
+ public void testCreateViewAllowsNullDefaultCatalogInViewVersion() throws Exception {
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ SQLRepresentation representation =
+ SQLRepresentation.builder().withDialect("spark").withSql("SELECT id FROM t").build();
+
+ doAnswer(
+ invocation -> {
+ ImmutableCreateViewRequest request = invocation.getArgument(1);
+ Assertions.assertNull(request.viewVersion().defaultCatalog());
+ return mockLoadViewResponse();
+ })
+ .when(wrapper)
+ .createView(
+ any(org.apache.iceberg.catalog.Namespace.class), any(ImmutableCreateViewRequest.class));
+
+ View view =
+ operations.createView(
+ ident,
+ "test comment",
+ columns,
+ new Representation[] {representation},
+ null,
+ "schema1",
+ Collections.singletonMap("k", "v"));
+
+ Assertions.assertNull(view.defaultCatalog());
+ }
+
+ @Test
+ public void testAlterViewSetAfterRemoveKeepsProperty() throws Exception {
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+ LoadViewResponse loaded = mockLoadViewResponseWithUuid("view-uuid");
+ when(wrapper.loadView(any(TableIdentifier.class))).thenReturn(loaded);
+
+ doAnswer(
+ invocation -> {
+ UpdateTableRequest request = invocation.getArgument(1);
+ Map<String, String> setProps = extractSetProperties(request.updates());
+ Set<String> removedProps = extractRemovedProperties(request.updates());
+ Assertions.assertEquals("v1", setProps.get("k1"));
+ Assertions.assertFalse(removedProps.contains("k1"));
+ return mockLoadViewResponse();
+ })
+ .when(wrapper)
+ .updateView(any(TableIdentifier.class), any(UpdateTableRequest.class));
+
+ operations.alterView(
+ ident, ViewChange.removeProperty("k1"), ViewChange.setProperty("k1", "v1"));
+
+ verify(wrapper).updateView(any(TableIdentifier.class), any(UpdateTableRequest.class));
+ }
+
+ @Test
+ public void testAlterViewRemoveAfterSetRemovesProperty() throws Exception {
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+ LoadViewResponse loaded = mockLoadViewResponseWithUuid("view-uuid");
+ when(wrapper.loadView(any(TableIdentifier.class))).thenReturn(loaded);
+
+ doAnswer(
+ invocation -> {
+ UpdateTableRequest request = invocation.getArgument(1);
+ Map<String, String> setProps = extractSetProperties(request.updates());
+ Set<String> removedProps = extractRemovedProperties(request.updates());
+ Assertions.assertFalse(setProps.containsKey("k1"));
+ Assertions.assertTrue(removedProps.contains("k1"));
+ return mockLoadViewResponse();
+ })
+ .when(wrapper)
+ .updateView(any(TableIdentifier.class), any(UpdateTableRequest.class));
+
+ operations.alterView(
+ ident, ViewChange.setProperty("k1", "v1"), ViewChange.removeProperty("k1"));
+
+ verify(wrapper).updateView(any(TableIdentifier.class), any(UpdateTableRequest.class));
+ }
+
+ @Test
+ public void testAlterViewReplaceDoesNotApplyLegacyDefaultCatalogPropertyCleanup()
+ throws Exception {
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+
+ ViewMetadata metadata = Mockito.mock(ViewMetadata.class);
+ when(metadata.uuid()).thenReturn("view-uuid");
+ when(metadata.schemas()).thenReturn(Collections.emptyList());
+
+ LoadViewResponse loaded = Mockito.mock(LoadViewResponse.class);
+ when(loaded.metadata()).thenReturn(metadata);
+ when(wrapper.loadView(any(TableIdentifier.class))).thenReturn(loaded);
+
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ SQLRepresentation representation =
+ SQLRepresentation.builder().withDialect("spark").withSql("SELECT id FROM t").build();
+
+ doAnswer(
+ invocation -> {
+ UpdateTableRequest request = invocation.getArgument(1);
+ Map<String, String> setProps = extractSetProperties(request.updates());
+ Set<String> removedProps = extractRemovedProperties(request.updates());
+ Assertions.assertFalse(setProps.containsKey("default-catalog"));
+ Assertions.assertFalse(removedProps.contains("default-catalog"));
+ return mockLoadViewResponse();
+ })
+ .when(wrapper)
+ .updateView(any(TableIdentifier.class), any(UpdateTableRequest.class));
+
+ operations.alterView(
+ ident,
+ ViewChange.replaceView(
+ columns, new Representation[] {representation}, null, "schema1", null));
+
+ verify(wrapper).updateView(any(TableIdentifier.class), any(UpdateTableRequest.class));
+ }
+
+ @Test
+ public void testAlterViewBuildsOptimisticConcurrencyRequirements() throws Exception {
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+
+ ViewMetadata metadata = Mockito.mock(ViewMetadata.class);
+ when(metadata.uuid()).thenReturn("view-uuid");
+
+ LoadViewResponse loaded = Mockito.mock(LoadViewResponse.class);
+ when(loaded.metadata()).thenReturn(metadata);
+ when(wrapper.loadView(any(TableIdentifier.class))).thenReturn(loaded);
+
+ doAnswer(
+ invocation -> {
+ UpdateTableRequest request = invocation.getArgument(1);
+ List<UpdateRequirement> expectedRequirements =
+ UpdateRequirements.forReplaceView(metadata, request.updates());
+ Assertions.assertEquals(expectedRequirements.size(), request.requirements().size());
+ for (int i = 0; i < expectedRequirements.size(); i++) {
+ Assertions.assertEquals(
+ expectedRequirements.get(i).getClass(),
+ request.requirements().get(i).getClass());
+ }
+ Assertions.assertFalse(request.requirements().isEmpty());
+ return mockLoadViewResponse();
+ })
+ .when(wrapper)
+ .updateView(any(TableIdentifier.class), any(UpdateTableRequest.class));
+
+ operations.alterView(ident, ViewChange.setProperty("k", "v"));
+
+ verify(wrapper).updateView(any(TableIdentifier.class), any(UpdateTableRequest.class));
+ }
+
+ private static LoadViewResponse mockLoadViewResponse() {
+ return Mockito.mock(LoadViewResponse.class);
+ }
+
+ private static LoadViewResponse mockLoadViewResponseWithUuid(String uuid) {
+ ViewMetadata metadata = Mockito.mock(ViewMetadata.class);
+ when(metadata.uuid()).thenReturn(uuid);
+
+ LoadViewResponse response = Mockito.mock(LoadViewResponse.class);
+ when(response.metadata()).thenReturn(metadata);
+ return response;
+ }
+
+ private static Map<String, String> extractSetProperties(List<MetadataUpdate> updates) {
+ return updates.stream()
+ .filter(update -> update instanceof MetadataUpdate.SetProperties)
+ .map(update -> ((MetadataUpdate.SetProperties) update).updated())
+ .findFirst()
+ .orElse(java.util.Collections.emptyMap());
+ }
+
+ private static Set<String> extractRemovedProperties(List<MetadataUpdate> updates) {
+ return updates.stream()
+ .filter(update -> update instanceof MetadataUpdate.RemoveProperties)
+ .map(update -> ((MetadataUpdate.RemoveProperties) update).removed())
+ .findFirst()
+ .orElse(java.util.Collections.emptySet());
+ }
+}
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestConvertUtil.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestConvertUtil.java
index 8f6270e143..28952ae218 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestConvertUtil.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/converter/TestConvertUtil.java
@@ -100,6 +100,14 @@ public class TestConvertUtil extends TestBaseConvert {
Assertions.assertTrue(mapType.valueType().asMapType().valueType().isPrimitiveType());
}
+ @Test
+ public void testToIcebergSchemaWithNullColumns() {
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> ConvertUtil.toIcebergSchema((Column[]) null));
+ Assertions.assertEquals("columns must not be null", exception.getMessage());
+ }
+
@Test
public void testToPrimitiveType() {
ByteType byteType = ByteType.get();
diff --git a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/CatalogIcebergBaseIT.java b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/CatalogIcebergBaseIT.java
index 82aedaff7d..a91a6aa0bd 100644
--- a/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/CatalogIcebergBaseIT.java
+++ b/catalogs/catalog-lakehouse-iceberg/src/test/java/org/apache/gravitino/catalog/lakehouse/iceberg/integration/test/CatalogIcebergBaseIT.java
@@ -54,17 +54,24 @@ import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergTable;
import org.apache.gravitino.catalog.lakehouse.iceberg.ops.IcebergCatalogWrapperHelper;
import org.apache.gravitino.client.GravitinoMetalake;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
+import org.apache.gravitino.exceptions.NoSuchViewException;
import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
import org.apache.gravitino.exceptions.TableAlreadyExistsException;
+import org.apache.gravitino.exceptions.ViewAlreadyExistsException;
import org.apache.gravitino.iceberg.common.IcebergConfig;
import org.apache.gravitino.iceberg.common.utils.IcebergCatalogUtil;
import org.apache.gravitino.integration.test.container.ContainerSuite;
import org.apache.gravitino.integration.test.util.BaseIT;
import org.apache.gravitino.integration.test.util.GravitinoITUtils;
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.TableCatalog;
import org.apache.gravitino.rel.TableChange;
+import org.apache.gravitino.rel.View;
+import org.apache.gravitino.rel.ViewCatalog;
+import org.apache.gravitino.rel.ViewChange;
import org.apache.gravitino.rel.expressions.FunctionExpression;
import org.apache.gravitino.rel.expressions.NamedReference;
import org.apache.gravitino.rel.expressions.distributions.Distribution;
@@ -108,6 +115,9 @@ public abstract class CatalogIcebergBaseIT extends BaseIT {
private static final String ICEBERG_COL_NAME2 = "iceberg_col_name2";
private static final String ICEBERG_COL_NAME3 = "iceberg_col_name3";
private static final String ICEBERG_COL_NAME4 = "iceberg_col_name4";
+ private static final String VIEW_COMMENT = "view comment";
+ private static final String SPARK_DIALECT = "spark";
+ private static final String TRINO_DIALECT = "trino";
private static final String provider = "lakehouse-iceberg";
private static final String SELECT_ALL_TEMPLATE = "SELECT * FROM iceberg.%s";
private static String INSERT_BATCH_WITHOUT_PARTITION_TEMPLATE =
@@ -185,6 +195,11 @@ public abstract class CatalogIcebergBaseIT extends BaseIT {
private void clearTableAndSchema() {
if (catalog.asSchemas().schemaExists(schemaName)) {
+ NameIdentifier[] viewIdentifiers =
+ catalog.asViewCatalog().listViews(Namespace.of(schemaName));
+ for (NameIdentifier nameIdentifier : viewIdentifiers) {
+ catalog.asViewCatalog().dropView(nameIdentifier);
+ }
NameIdentifier[] nameIdentifiers =
catalog.asTableCatalog().listTables(Namespace.of(schemaName));
for (NameIdentifier nameIdentifier : nameIdentifiers) {
@@ -1541,6 +1556,534 @@ public abstract class CatalogIcebergBaseIT extends BaseIT {
}
}
+ @Test
+ void testCreateAndLoadView() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ Column[] columns = {
+ Column.of("id", Types.LongType.get(), "id column"),
+ Column.of("name", Types.StringType.get(), "name column")
+ };
+ SQLRepresentation sparkRep =
+ SQLRepresentation.builder()
+ .withDialect(SPARK_DIALECT)
+ .withSql("SELECT id, name FROM some_table")
+ .build();
+
+ String viewName = GravitinoITUtils.genRandomName("test_view");
+ View created =
+ viewCatalog.createView(
+ NameIdentifier.of(schemaName, viewName),
+ VIEW_COMMENT,
+ columns,
+ new SQLRepresentation[] {sparkRep},
+ null,
+ null,
+ Collections.singletonMap("created_by", "test"));
+
+ Assertions.assertEquals(viewName, created.name());
+ Assertions.assertEquals(VIEW_COMMENT, created.comment());
+ Assertions.assertEquals(1, created.representations().length);
+ Assertions.assertEquals(Representation.TYPE_SQL, created.representations()[0].type());
+ Assertions.assertEquals("test", created.properties().get("created_by"));
+
+ View loaded = viewCatalog.loadView(NameIdentifier.of(schemaName, viewName));
+ Assertions.assertEquals(viewName, loaded.name());
+ Assertions.assertEquals(VIEW_COMMENT, loaded.comment());
+ Assertions.assertEquals(1, loaded.representations().length);
+ Assertions.assertEquals(Representation.TYPE_SQL, loaded.representations()[0].type());
+ Assertions.assertEquals("test", loaded.properties().get("created_by"));
+ }
+
+ @Test
+ void testCreateViewWithMultipleRepresentations() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ Column[] columns = {Column.of("id", Types.IntegerType.get(), null)};
+ SQLRepresentation sparkRep =
+ SQLRepresentation.builder().withDialect(SPARK_DIALECT).withSql("SELECT id FROM t").build();
+ SQLRepresentation trinoRep =
+ SQLRepresentation.builder().withDialect(TRINO_DIALECT).withSql("SELECT id FROM t").build();
+
+ String viewName = GravitinoITUtils.genRandomName("multi_rep_view");
+ View view =
+ viewCatalog.createView(
+ NameIdentifier.of(schemaName, viewName),
+ null,
+ columns,
+ new SQLRepresentation[] {sparkRep, trinoRep},
+ null,
+ null,
+ Collections.emptyMap());
+
+ Assertions.assertEquals(2, view.representations().length);
+ Assertions.assertEquals(Representation.TYPE_SQL, view.representations()[0].type());
+ Assertions.assertEquals(Representation.TYPE_SQL, view.representations()[1].type());
+ Assertions.assertNull(view.comment());
+ }
+
+ @Test
+ void testCreateViewAndQueryWithSpark() {
+ TableCatalog tableCatalog = catalog.asTableCatalog();
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+
+ String sourceTableName = GravitinoITUtils.genRandomName("view_source_tbl");
+ NameIdentifier sourceTableIdent = NameIdentifier.of(schemaName, sourceTableName);
+ Column[] columns = {
+ Column.of("id", Types.IntegerType.get(), null),
+ Column.of("name", Types.StringType.get(), null)
+ };
+ tableCatalog.createTable(
+ sourceTableIdent,
+ columns,
+ table_comment,
+ createProperties(),
+ Transforms.EMPTY_TRANSFORM,
+ Distributions.NONE,
+ new SortOrder[0]);
+
+ TableIdentifier sourceTableIdentifier = TableIdentifier.of(schemaName, sourceTableName);
+ spark.sql(
+ String.format(
+ "INSERT INTO iceberg.%s VALUES (1, 'alice'), (2, 'bob')", sourceTableIdentifier));
+
+ String viewName = GravitinoITUtils.genRandomName("spark_query_view");
+ TableIdentifier viewIdentifier = TableIdentifier.of(schemaName, viewName);
+ String viewSql = String.format("SELECT id, name FROM iceberg.%s", sourceTableIdentifier);
+ viewCatalog.createView(
+ NameIdentifier.of(schemaName, viewName),
+ VIEW_COMMENT,
+ columns,
+ new SQLRepresentation[] {
+ SQLRepresentation.builder().withDialect(SPARK_DIALECT).withSql(viewSql).build()
+ },
+ null,
+ null,
+ Collections.emptyMap());
+
+ List<Row> result =
+ spark
+ .sql(String.format("SELECT * FROM iceberg.%s ORDER BY id", viewIdentifier))
+ .collectAsList();
+ Assertions.assertEquals(2, result.size());
+ Assertions.assertEquals(1, result.get(0).getInt(0));
+ Assertions.assertEquals("alice", result.get(0).getString(1));
+ Assertions.assertEquals(2, result.get(1).getInt(0));
+ Assertions.assertEquals("bob", result.get(1).getString(1));
+ }
+
+ @Test
+ void testSparkCreateViewLoadWithGravitino() {
+ TableCatalog tableCatalog = catalog.asTableCatalog();
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+
+ String sourceTableName = GravitinoITUtils.genRandomName("spark_create_view_src");
+ NameIdentifier sourceTableIdent = NameIdentifier.of(schemaName, sourceTableName);
+ Column[] columns = {
+ Column.of("id", Types.IntegerType.get(), null),
+ Column.of("name", Types.StringType.get(), null)
+ };
+ tableCatalog.createTable(
+ sourceTableIdent,
+ columns,
+ table_comment,
+ createProperties(),
+ Transforms.EMPTY_TRANSFORM,
+ Distributions.NONE,
+ new SortOrder[0]);
+
+ TableIdentifier sourceTableIdentifier = TableIdentifier.of(schemaName, sourceTableName);
+ spark.sql(
+ String.format(
+ "INSERT INTO iceberg.%s VALUES (10, 'spark_created'), (20, 'spark_loaded')",
+ sourceTableIdentifier));
+
+ String viewName = GravitinoITUtils.genRandomName("spark_created_view");
+ TableIdentifier viewIdentifier = TableIdentifier.of(schemaName, viewName);
+ spark.sql(
+ String.format(
+ "CREATE OR REPLACE VIEW iceberg.%s AS SELECT id, name FROM iceberg.%s",
+ viewIdentifier, sourceTableIdentifier));
+
+ View loaded = viewCatalog.loadView(NameIdentifier.of(schemaName, viewName));
+ Assertions.assertEquals(viewName, loaded.name());
+ Assertions.assertEquals(2, loaded.columns().length);
+ Assertions.assertEquals("id", loaded.columns()[0].name());
+ Assertions.assertEquals("name", loaded.columns()[1].name());
+ Assertions.assertTrue(loaded.representations().length > 0);
+ Assertions.assertEquals(Representation.TYPE_SQL, loaded.representations()[0].type());
+ }
+
+ @Test
+ void testCreateViewWithUnsupportedRepresentation() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ Representation unsupportedRepresentation = () -> "unsupported";
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ viewCatalog.createView(
+ NameIdentifier.of(schemaName, GravitinoITUtils.genRandomName("bad_rep_view")),
+ null,
+ columns,
+ new Representation[] {unsupportedRepresentation},
+ null,
+ null,
+ Collections.emptyMap()));
+ Assertions.assertNotNull(exception.getMessage());
+ }
+
+ @Test
+ void testAlterViewReplaceWithUnsupportedRepresentation() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ String viewName = GravitinoITUtils.genRandomName("replace_bad_rep_view");
+ NameIdentifier viewIdent = NameIdentifier.of(schemaName, viewName);
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ SQLRepresentation sparkRep =
+ SQLRepresentation.builder().withDialect(SPARK_DIALECT).withSql("SELECT id FROM t").build();
+ viewCatalog.createView(
+ viewIdent,
+ null,
+ columns,
+ new SQLRepresentation[] {sparkRep},
+ null,
+ null,
+ Collections.emptyMap());
+
+ Representation unsupportedRepresentation = () -> "unsupported";
+ IllegalArgumentException exception =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ viewCatalog.alterView(
+ viewIdent,
+ ViewChange.replaceView(
+ columns,
+ new Representation[] {unsupportedRepresentation},
+ null,
+ schemaName,
+ null)));
+ Assertions.assertNotNull(exception.getMessage());
+ }
+
+ @Test
+ void testListViews() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ String view1 = GravitinoITUtils.genRandomName("list_view1");
+ String view2 = GravitinoITUtils.genRandomName("list_view2");
+ Column[] columns = {Column.of("c1", Types.StringType.get(), null)};
+ SQLRepresentation rep =
+ SQLRepresentation.builder().withDialect(SPARK_DIALECT).withSql("SELECT c1 FROM t").build();
+
+ viewCatalog.createView(
+ NameIdentifier.of(schemaName, view1),
+ null,
+ columns,
+ new SQLRepresentation[] {rep},
+ null,
+ null,
+ Collections.emptyMap());
+ viewCatalog.createView(
+ NameIdentifier.of(schemaName, view2),
+ null,
+ columns,
+ new SQLRepresentation[] {rep},
+ null,
+ null,
+ Collections.emptyMap());
+
+ NameIdentifier[] views = viewCatalog.listViews(Namespace.of(schemaName));
+ Assertions.assertTrue(views.length >= 2);
+ boolean foundView1 = false;
+ boolean foundView2 = false;
+ for (NameIdentifier v : views) {
+ if (v.name().equals(view1)) {
+ foundView1 = true;
+ }
+ if (v.name().equals(view2)) {
+ foundView2 = true;
+ }
+ }
+ Assertions.assertTrue(foundView1, "view1 not found in list");
+ Assertions.assertTrue(foundView2, "view2 not found in list");
+ }
+
+ @Test
+ void testViewExists() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ String viewName = GravitinoITUtils.genRandomName("exists_view");
+ NameIdentifier ident = NameIdentifier.of(schemaName, viewName);
+
+ Assertions.assertFalse(viewCatalog.viewExists(ident));
+
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ SQLRepresentation rep =
+ SQLRepresentation.builder().withDialect(SPARK_DIALECT).withSql("SELECT id FROM t").build();
+ viewCatalog.createView(
+ ident, null, columns, new SQLRepresentation[] {rep}, null, null, Collections.emptyMap());
+
+ Assertions.assertTrue(viewCatalog.viewExists(ident));
+ }
+
+ @Test
+ void testDropView() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ String viewName = GravitinoITUtils.genRandomName("drop_view");
+ NameIdentifier ident = NameIdentifier.of(schemaName, viewName);
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ SQLRepresentation rep =
+ SQLRepresentation.builder().withDialect(SPARK_DIALECT).withSql("SELECT id FROM t").build();
+
+ viewCatalog.createView(
+ ident, null, columns, new SQLRepresentation[] {rep}, null, null, Collections.emptyMap());
+ Assertions.assertTrue(viewCatalog.viewExists(ident));
+
+ Assertions.assertTrue(viewCatalog.dropView(ident));
+ Assertions.assertFalse(viewCatalog.viewExists(ident));
+ Assertions.assertFalse(viewCatalog.dropView(ident));
+ }
+
+ @Test
+ void testAlterViewRename() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ String viewName = GravitinoITUtils.genRandomName("rename_view");
+ String newName = GravitinoITUtils.genRandomName("renamed_view");
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ SQLRepresentation rep =
+ SQLRepresentation.builder().withDialect(SPARK_DIALECT).withSql("SELECT id FROM t").build();
+
+ viewCatalog.createView(
+ NameIdentifier.of(schemaName, viewName),
+ null,
+ columns,
+ new SQLRepresentation[] {rep},
+ null,
+ null,
+ Collections.emptyMap());
+
+ View renamed =
+ viewCatalog.alterView(NameIdentifier.of(schemaName, viewName), ViewChange.rename(newName));
+
+ Assertions.assertEquals(newName, renamed.name());
+ Assertions.assertFalse(viewCatalog.viewExists(NameIdentifier.of(schemaName, viewName)));
+ Assertions.assertTrue(viewCatalog.viewExists(NameIdentifier.of(schemaName, newName)));
+ }
+
+ @Test
+ void testAlterViewSetAndRemoveProperty() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ String viewName = GravitinoITUtils.genRandomName("prop_view");
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ SQLRepresentation rep =
+ SQLRepresentation.builder().withDialect(SPARK_DIALECT).withSql("SELECT id FROM t").build();
+
+ viewCatalog.createView(
+ NameIdentifier.of(schemaName, viewName),
+ null,
+ columns,
+ new SQLRepresentation[] {rep},
+ null,
+ null,
+ Collections.singletonMap("initial_key", "initial_val"));
+
+ View withProp =
+ viewCatalog.alterView(
+ NameIdentifier.of(schemaName, viewName), ViewChange.setProperty("new_key", "new_val"));
+ Assertions.assertEquals("new_val", withProp.properties().get("new_key"));
+ Assertions.assertEquals("initial_val", withProp.properties().get("initial_key"));
+
+ View withoutProp =
+ viewCatalog.alterView(
+ NameIdentifier.of(schemaName, viewName), ViewChange.removeProperty("new_key"));
+ Assertions.assertNull(withoutProp.properties().get("new_key"));
+ }
+
+ @Test
+ void testCreateViewAlreadyExists() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ String viewName = GravitinoITUtils.genRandomName("dup_view");
+ NameIdentifier ident = NameIdentifier.of(schemaName, viewName);
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ SQLRepresentation rep =
+ SQLRepresentation.builder().withDialect(SPARK_DIALECT).withSql("SELECT id FROM t").build();
+
+ viewCatalog.createView(
+ ident, null, columns, new SQLRepresentation[] {rep}, null, null, Collections.emptyMap());
+
+ Assertions.assertThrows(
+ ViewAlreadyExistsException.class,
+ () ->
+ viewCatalog.createView(
+ ident,
+ null,
+ columns,
+ new SQLRepresentation[] {rep},
+ null,
+ null,
+ Collections.emptyMap()));
+ }
+
+ @Test
+ void testLoadNonExistentView() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ NameIdentifier ident = NameIdentifier.of(schemaName, "non_existent_view_xyz");
+ Assertions.assertThrows(NoSuchViewException.class, () -> viewCatalog.loadView(ident));
+ }
+
+ @Test
+ void testAlterViewReplace() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ String viewName = GravitinoITUtils.genRandomName("replace_view");
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ SQLRepresentation sparkRep =
+ SQLRepresentation.builder().withDialect(SPARK_DIALECT).withSql("SELECT id FROM t").build();
+
+ viewCatalog.createView(
+ NameIdentifier.of(schemaName, viewName),
+ "original comment",
+ columns,
+ new SQLRepresentation[] {sparkRep},
+ null,
+ null,
+ Collections.singletonMap("replace.drop-dialect.allowed", "true"));
+
+ SQLRepresentation trinoRep =
+ SQLRepresentation.builder()
+ .withDialect(TRINO_DIALECT)
+ .withSql("SELECT id, name FROM updated_table")
+ .build();
+ Column[] replacedColumns = {
+ Column.of("id", Types.LongType.get(), null), Column.of("name", Types.StringType.get(), null)
+ };
+
+ View altered =
+ viewCatalog.alterView(
+ NameIdentifier.of(schemaName, viewName),
+ ViewChange.replaceView(
+ replacedColumns,
+ new SQLRepresentation[] {trinoRep},
+ null,
+ schemaName,
+ "replaced comment"));
+
+ Assertions.assertEquals("replaced comment", altered.comment());
+ Assertions.assertEquals(1, altered.representations().length);
+ Assertions.assertTrue(altered.sqlFor(TRINO_DIALECT).isPresent());
+ Assertions.assertFalse(altered.sqlFor(SPARK_DIALECT).isPresent());
+ Assertions.assertEquals(2, altered.columns().length);
+ Assertions.assertEquals("name", altered.columns()[1].name());
+ }
+
+ @Test
+ void testAlterViewReplaceThenSetCustomProperty() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ String viewName = GravitinoITUtils.genRandomName("replace_then_set_view");
+ NameIdentifier ident = NameIdentifier.of(schemaName, viewName);
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ SQLRepresentation sparkRep =
+ SQLRepresentation.builder().withDialect(SPARK_DIALECT).withSql("SELECT id FROM t").build();
+
+ Map<String, String> createProps = Maps.newHashMap();
+ createProps.put("keep_key", "keep_val");
+ createProps.put("replace.drop-dialect.allowed", "true");
+
+ viewCatalog.createView(
+ ident,
+ "original comment",
+ columns,
+ new SQLRepresentation[] {sparkRep},
+ null,
+ null,
+ createProps);
+
+ SQLRepresentation trinoRep =
+ SQLRepresentation.builder()
+ .withDialect(TRINO_DIALECT)
+ .withSql("SELECT id, name FROM updated_table")
+ .build();
+ Column[] replacedColumns = {
+ Column.of("id", Types.LongType.get(), null), Column.of("name", Types.StringType.get(), null)
+ };
+
+ View altered =
+ viewCatalog.alterView(
+ ident,
+ ViewChange.replaceView(
+ replacedColumns,
+ new SQLRepresentation[] {trinoRep},
+ "replace_catalog",
+ schemaName,
+ "replace comment"),
+ ViewChange.setProperty("custom_key", "custom_val"));
+
+ Assertions.assertEquals("replace comment", altered.comment());
+ Assertions.assertEquals("replace_catalog", altered.defaultCatalog());
+ Assertions.assertEquals("custom_val", altered.properties().get("custom_key"));
+ Assertions.assertEquals("keep_val", altered.properties().get("keep_key"));
+ Assertions.assertEquals(2, altered.columns().length);
+ Assertions.assertEquals("name", altered.columns()[1].name());
+ Assertions.assertTrue(altered.sqlFor(TRINO_DIALECT).isPresent());
+ }
+
+ @Test
+ void testAlterViewSetCustomPropertyThenReplaceKeepsProperty() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ String viewName = GravitinoITUtils.genRandomName("set_then_replace_view");
+ NameIdentifier ident = NameIdentifier.of(schemaName, viewName);
+ Column[] columns = {Column.of("id", Types.LongType.get(), null)};
+ SQLRepresentation sparkRep =
+ SQLRepresentation.builder().withDialect(SPARK_DIALECT).withSql("SELECT id FROM t").build();
+
+ Map<String, String> createProps = Maps.newHashMap();
+ createProps.put("keep_key", "keep_val");
+ createProps.put("replace.drop-dialect.allowed", "true");
+
+ viewCatalog.createView(
+ ident,
+ "original comment",
+ columns,
+ new SQLRepresentation[] {sparkRep},
+ null,
+ null,
+ createProps);
+
+ SQLRepresentation trinoRep =
+ SQLRepresentation.builder()
+ .withDialect(TRINO_DIALECT)
+ .withSql("SELECT id, name FROM updated_table")
+ .build();
+ Column[] replacedColumns = {
+ Column.of("id", Types.LongType.get(), null), Column.of("name", Types.StringType.get(), null)
+ };
+
+ View altered =
+ viewCatalog.alterView(
+ ident,
+ ViewChange.setProperty("custom_key", "custom_val"),
+ ViewChange.replaceView(
+ replacedColumns,
+ new SQLRepresentation[] {trinoRep},
+ "replace_catalog",
+ schemaName,
+ "replace comment"));
+
+ Assertions.assertEquals("replace comment", altered.comment());
+ Assertions.assertEquals("replace_catalog", altered.defaultCatalog());
+ Assertions.assertEquals("custom_val", altered.properties().get("custom_key"));
+ Assertions.assertEquals("keep_val", altered.properties().get("keep_key"));
+ Assertions.assertEquals(2, altered.columns().length);
+ Assertions.assertEquals("name", altered.columns()[1].name());
+ Assertions.assertTrue(altered.sqlFor(TRINO_DIALECT).isPresent());
+ }
+
+ @Test
+ void testListViewsInNonExistentSchema() {
+ ViewCatalog viewCatalog = catalog.asViewCatalog();
+ Assertions.assertThrows(
+ NoSuchSchemaException.class,
+ () -> viewCatalog.listViews(Namespace.of("non_existent_schema_xyz")));
+ }
+
protected static void assertionsTableInfo(
String tableName,
String tableComment,