Skip to content

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

[#11925] feat(trino-connector): Support views in Trino connector (#11926)

Yuhui830a19d86a28
diff --git a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveViewCatalogOperations.java b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveViewCatalogOperations.java
index aed09d2865..a636fe142a 100644
--- a/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveViewCatalogOperations.java
+++ b/catalogs/catalog-hive/src/main/java/org/apache/gravitino/catalog/hive/HiveViewCatalogOperations.java
@@ -64,6 +64,14 @@ class HiveViewCatalogOperations implements ViewCatalog {
private static final String SUPPORTED_VIEW_DIALECTS =
String.join(", ", Dialects.HIVE, Dialects.TRINO, Dialects.FLINK, Dialects.SPARK);
+ /**
+ * Reserved view property, namespaced by the Trino connector, used to round-trip a Trino native
+ * view's {@code SECURITY DEFINER} owner into the encoded {@code viewOriginalText} payload; its
+ * value must match {@code CatalogConnectorMetadataAdapter.RESERVED_VIEW_OWNER_PROPERTY} in the
+ * trino-connector module. Its absence means the view is {@code SECURITY INVOKER}.
+ */
+ static final String TRINO_VIEW_OWNER_PROPERTY = "trino.internal.view.owner";
+
/**
* The HMS-level representation derived from a logical view definition: the columns, comment, and
* {@code viewOriginalText} actually stored on the underlying HMS table. For a Trino dialect view
@@ -158,7 +166,7 @@ class HiveViewCatalogOperations implements ViewCatalog {
.withProperties(params)
.withAuditInfo(
AuditInfo.builder()
- .withCreator(PrincipalUtils.getCurrentUserName())
+ .withCreator(resolveHmsOwner(sqlRepresentation.dialect(), params))
.withCreateTime(Instant.now())
.build())
.withCatalogName(catalogName())
@@ -209,11 +217,15 @@ class HiveViewCatalogOperations implements ViewCatalog {
// here too, instead of being silently treated as a non-Trino view.
boolean isTrinoView =
Dialects.TRINO.equalsIgnoreCase(HiveView.detectDialect(currentHiveTable.properties()));
- // Gravitino's view model has no owner/runAsInvoker/path concept, so replacing a native Trino
- // view that carries a non-default value for any of them would silently discard it (e.g. a
- // SECURITY DEFINER view with an owner would silently become an ownerless SECURITY INVOKER
- // view). Reject the replace instead of doing that.
- boolean currentTrinoViewHasUnrepresentableFields = false;
+ // Owner/runAsInvoker round-trip through the TRINO_VIEW_OWNER_PROPERTY reserved property (see
+ // toHmsViewOriginalText()/loadHiveView()), but Gravitino's view model still has no path
+ // concept, so altering a native Trino view with a non-empty SQL path would silently discard
+ // it on the next load. Reject the whole alterView() call upfront - before any change is
+ // applied to HMS - rather than only guarding ReplaceView: toHiveView() (used to build the
+ // return value for every change type, including a plain rename) now also rejects a
+ // non-empty path, and discovering that only after c.alterTable() already ran would report
+ // a successful HMS mutation as a thrown exception.
+ String currentOwner = null;
if (isTrinoView) {
TrinoNativeViewCodec.ViewDefinition currentDefinition;
try {
@@ -226,15 +238,31 @@ class HiveViewCatalogOperations implements ViewCatalog {
+ "decoded",
e);
}
- currentTrinoViewHasUnrepresentableFields =
- currentDefinition.owner != null
- || !currentDefinition.runAsInvoker
- || !currentDefinition.path.isEmpty();
+ if (!currentDefinition.path.isEmpty()) {
+ throw new UnsupportedOperationException(
+ "View "
+ + ident
+ + " is a native Trino view with a non-empty SQL path; Gravitino cannot "
+ + "represent this field, so altering it would silently discard it");
+ }
+ if (currentDefinition.owner != null) {
+ String hmsOwner =
+ currentHiveTable.auditInfo() == null ? null : currentHiveTable.auditInfo().creator();
+ currentOwner = preferNonEmpty(hmsOwner, currentDefinition.owner);
+ }
}
String newViewName = currentHiveTable.name();
String updatedViewOriginalText = currentHiveTable.viewOriginalText();
Map<String, String> updatedProperties = Maps.newHashMap(currentHiveTable.properties());
+ // A native Trino view's owner lives only in the encoded payload, not in the raw HMS
+ // parameters just copied above, so seed it here. Without this, replacing such a view as the
+ // same owner looks like no change to computePropertyChanges() (it compares against the
+ // decoded owner exposed by toHiveView()), so no SetProperty is emitted, and ReplaceView would
+ // encode the new payload with this property missing, silently downgrading it to INVOKER.
+ if (currentOwner != null) {
+ updatedProperties.put(TRINO_VIEW_OWNER_PROPERTY, currentOwner);
+ }
Column[] updatedColumns = copyColumns(currentHiveTable.columns());
String updatedComment = currentHiveTable.comment();
updatedProperties.remove(COMMENT);
@@ -285,14 +313,6 @@ class HiveViewCatalogOperations implements ViewCatalog {
updatedProperties.remove(property);
}
} else if (change instanceof ViewChange.ReplaceView) {
- if (currentTrinoViewHasUnrepresentableFields) {
- throw new UnsupportedOperationException(
- "View "
- + ident
- + " is a native Trino view with a non-default owner, runAsInvoker, or SQL "
- + "path; Gravitino cannot represent these fields, so replacing it would "
- + "silently discard them");
- }
ViewChange.ReplaceView replace = (ViewChange.ReplaceView) change;
SQLRepresentation sqlRepresentation =
validateSQLRepresentation(
@@ -321,9 +341,26 @@ class HiveViewCatalogOperations implements ViewCatalog {
}
}
+ // Native Trino prioritizes the live HMS table owner over the (possibly stale) owner encoded
+ // in the view payload, so a Gravitino-managed replace/property change must keep the HMS
+ // owner in sync with TRINO_VIEW_OWNER_PROPERTY or the two would immediately diverge again.
+ AuditInfo updatedAuditInfo = currentHiveTable.auditInfo();
+ if (isTrinoView && updatedProperties.containsKey(TRINO_VIEW_OWNER_PROPERTY)) {
+ String targetOwner = resolveHmsOwner(Dialects.TRINO, updatedProperties);
+ String currentCreator = updatedAuditInfo == null ? null : updatedAuditInfo.creator();
+ if (!targetOwner.equals(currentCreator)) {
+ updatedAuditInfo =
+ AuditInfo.builder()
+ .withCreator(targetOwner)
+ .withCreateTime(
+ updatedAuditInfo == null ? Instant.now() : updatedAuditInfo.createTime())
+ .build();
+ }
+ }
+
HiveTable updatedHiveTable =
buildAlteredHiveView(
- currentHiveTable,
+ updatedAuditInfo,
schemaIdent,
newViewName,
updatedComment,
@@ -367,7 +404,7 @@ class HiveViewCatalogOperations implements ViewCatalog {
}
private HiveTable buildAlteredHiveView(
- HiveTable currentHiveTable,
+ AuditInfo auditInfo,
NameIdentifier schemaIdent,
String viewName,
String comment,
@@ -379,13 +416,37 @@ class HiveViewCatalogOperations implements ViewCatalog {
.withComment(comment)
.withColumns(copyColumns(columns))
.withProperties(properties)
- .withAuditInfo(currentHiveTable.auditInfo())
+ .withAuditInfo(auditInfo)
.withCatalogName(catalogName())
.withDatabaseName(schemaIdent.name())
.withViewOriginalText(viewOriginalText)
.build();
}
+ /**
+ * Resolves the HMS table owner that should back a Trino dialect view's {@code SECURITY DEFINER}
+ * owner: the connector-managed {@link #TRINO_VIEW_OWNER_PROPERTY}, if present, otherwise the
+ * current principal (matching native Trino, which always assigns an HMS owner regardless of
+ * security mode).
+ */
+ private String resolveHmsOwner(String dialect, Map<String, String> properties) {
+ if (Dialects.TRINO.equalsIgnoreCase(dialect)) {
+ return preferNonEmpty(
+ properties.get(TRINO_VIEW_OWNER_PROPERTY), PrincipalUtils.getCurrentUserName());
+ }
+ return PrincipalUtils.getCurrentUserName();
+ }
+
+ /**
+ * Returns {@code preferred} if non-empty, otherwise {@code fallback}. Names the single precedence
+ * rule shared by both directions of the HMS-owner / {@link #TRINO_VIEW_OWNER_PROPERTY}
+ * reconciliation: the live HMS owner wins on load (over the payload-decoded owner), and the
+ * connector-managed property wins on write (over the current principal).
+ */
+ private static String preferNonEmpty(String preferred, String fallback) {
+ return StringUtils.isNotEmpty(preferred) ? preferred : fallback;
+ }
+
@Override
public boolean dropView(NameIdentifier ident) {
NameIdentifier schemaIdent = NameIdentifier.of(ident.namespace().levels());
@@ -496,10 +557,27 @@ class HiveViewCatalogOperations implements ViewCatalog {
"View " + ident + " carries the presto_view marker but its payload cannot be decoded",
e);
}
+ if (!decoded.path.isEmpty()) {
+ // Gravitino's view model has no SQL path (SET PATH) concept, so silently dropping it on
+ // load would let an unqualified function resolve differently than the view's creator
+ // intended. Reject the view instead of exposing it with incorrect semantics.
+ throw new UnsupportedOperationException(
+ "View "
+ + ident
+ + " is a native Trino view with a non-empty SQL path; Gravitino cannot "
+ + "represent this field");
+ }
representationSql = decoded.originalSql;
resolvedComment = decoded.comment;
restoredDefaultCatalog = decoded.catalog;
restoredDefaultSchema = decoded.schema;
+ if (decoded.owner != null) {
+ // Native Trino prioritizes the live HMS table owner over the owner encoded in the view
+ // payload (e.g. after ALTER VIEW ... SET AUTHORIZATION, which updates only the HMS owner),
+ // so mirror that precedence here instead of trusting the payload unconditionally.
+ String hmsOwner = auditInfo == null ? null : auditInfo.creator();
+ params.put(TRINO_VIEW_OWNER_PROPERTY, preferNonEmpty(hmsOwner, decoded.owner));
+ }
resolvedColumns =
decoded.columns.stream()
.map(
@@ -647,7 +725,7 @@ class HiveViewCatalogOperations implements ViewCatalog {
applyTrinoViewMarker(properties, sqlRepresentation.dialect());
String viewOriginalText =
toHmsViewOriginalText(
- sqlRepresentation, columns, comment, defaultCatalog, defaultSchema, ident);
+ sqlRepresentation, columns, comment, defaultCatalog, defaultSchema, properties, ident);
String hmsComment =
Dialects.TRINO.equalsIgnoreCase(sqlRepresentation.dialect())
? TrinoNativeViewCodec.PRESTO_VIEW_COMMENT
@@ -662,6 +740,7 @@ class HiveViewCatalogOperations implements ViewCatalog {
String comment,
String defaultCatalog,
String defaultSchema,
+ Map<String, String> properties,
NameIdentifier ident) {
switch (representation.dialect().toLowerCase(Locale.ROOT)) {
case Dialects.HIVE:
@@ -678,6 +757,7 @@ class HiveViewCatalogOperations implements ViewCatalog {
TrinoNativeViewCodec.toTrinoTypeString(c.dataType()),
c.comment()))
.collect(Collectors.toList());
+ String owner = properties == null ? null : properties.get(TRINO_VIEW_OWNER_PROPERTY);
return TrinoNativeViewCodec.encode(
new TrinoNativeViewCodec.ViewDefinition(
representation.sql(),
@@ -685,8 +765,8 @@ class HiveViewCatalogOperations implements ViewCatalog {
defaultSchema,
viewColumns,
comment,
- /* owner= */ null,
- /* runAsInvoker= */ true,
+ /* owner= */ owner,
+ /* runAsInvoker= */ owner == null,
/* path= */ Collections.emptyList()));
default:
throw new UnsupportedOperationException(
diff --git a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java
index ee91894c26..d7a0f22e72 100644
--- a/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java
+++ b/catalogs/catalog-hive/src/test/java/org/apache/gravitino/catalog/hive/TestHiveCatalogOperations.java
@@ -63,12 +63,14 @@ import org.apache.gravitino.Namespace;
import org.apache.gravitino.connector.BaseCatalog;
import org.apache.gravitino.connector.PropertyEntry;
import org.apache.gravitino.exceptions.ConnectionFailedException;
+import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.exceptions.ViewAlreadyExistsException;
import org.apache.gravitino.hive.CachedClientPool;
import org.apache.gravitino.hive.HiveSchema;
import org.apache.gravitino.hive.HiveTable;
import org.apache.gravitino.hive.client.HiveClient;
import org.apache.gravitino.hive.client.HiveClientClassLoader.HiveVersion;
+import org.apache.gravitino.meta.AuditInfo;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Representation;
import org.apache.gravitino.rel.SQLRepresentation;
@@ -1062,10 +1064,16 @@ class TestHiveCatalogOperations {
}
@Test
- void testAlterViewReplaceRejectsExistingNonDefaultOwner() throws Exception {
- // Gravitino's view model has no owner concept; replacing a native Trino view that has a
- // non-null owner (a SECURITY DEFINER view) would silently turn it into an ownerless view.
- assertReplaceRejectsUnrepresentableNativeView(
+ void testAlterViewReplacePropagatesNewOwnerProperty() throws Exception {
+ // The owner round-trips through the TRINO_VIEW_OWNER_PROPERTY reserved property: a SetProperty
+ // change alongside ReplaceView must land in the re-encoded native Trino payload as the new
+ // SECURITY DEFINER owner.
+ HiveCatalogOperations op = new HiveCatalogOperations();
+ op.initialize(Maps.newHashMap(), null, HIVE_PROPERTIES_METADATA);
+
+ CachedClientPool clientPool = mock(CachedClientPool.class);
+ HiveClient hiveClient = mock(HiveClient.class);
+ String encoded =
TrinoNativeViewCodec.encode(
new TrinoNativeViewCodec.ViewDefinition(
"SELECT 1",
@@ -1073,16 +1081,67 @@ class TestHiveCatalogOperations {
null,
List.of(new TrinoNativeViewCodec.ViewColumn("c1", "integer", null)),
null,
- "alice",
+ null,
true,
- List.of())));
+ List.of()));
+ HiveTable currentTable =
+ HiveTable.builder()
+ .withName("v_hive")
+ .withCatalogName("hive")
+ .withDatabaseName("db")
+ .withColumns(new Column[0])
+ .withComment("Presto View")
+ .withProperties(
+ Maps.newHashMap(
+ ImmutableMap.of(
+ HiveConstants.TABLE_TYPE,
+ TableType.VIRTUAL_VIEW.name(),
+ "presto_view",
+ "true")))
+ .withViewOriginalText(encoded)
+ .build();
+ when(hiveClient.getTable(anyString(), anyString(), anyString())).thenReturn(currentTable);
+
+ ArgumentCaptor<HiveTable> hiveTableCaptor = ArgumentCaptor.forClass(HiveTable.class);
+ doNothing()
+ .when(hiveClient)
+ .alterTable(anyString(), anyString(), anyString(), hiveTableCaptor.capture());
+ when(clientPool.run(any()))
+ .thenAnswer(
+ invocation -> {
+ ClientPool.Action<?, HiveClient, ?> action = invocation.getArgument(0);
+ return action.run(hiveClient);
+ });
+ op.clientPool = clientPool;
+
+ op.alterView(
+ NameIdentifier.of("db", "v_hive"),
+ ViewChange.setProperty(HiveViewCatalogOperations.TRINO_VIEW_OWNER_PROPERTY, "alice"),
+ ViewChange.replaceView(
+ new Column[] {Column.of("c1", Types.IntegerType.get())},
+ new SQLRepresentation[] {
+ SQLRepresentation.builder().withDialect("trino").withSql("SELECT 2").build()
+ },
+ null,
+ null,
+ null));
+
+ TrinoNativeViewCodec.ViewDefinition decoded =
+ TrinoNativeViewCodec.decode(hiveTableCaptor.getValue().viewOriginalText());
+ Assertions.assertEquals("alice", decoded.owner);
+ Assertions.assertFalse(decoded.runAsInvoker);
}
@Test
- void testAlterViewReplaceRejectsExistingRunAsInvokerFalse() throws Exception {
- // runAsInvoker=false means SECURITY DEFINER; Gravitino always writes runAsInvoker=true, so
- // replacing such a view would silently downgrade it to SECURITY INVOKER.
- assertReplaceRejectsUnrepresentableNativeView(
+ void testAlterViewReplaceClearsOwnerWhenPropertyRemoved() throws Exception {
+ // Replacing a SECURITY DEFINER view with RemoveProperty(owner) alongside ReplaceView must
+ // clear the owner in the re-encoded payload, downgrading it to SECURITY INVOKER.
+ HiveCatalogOperations op = new HiveCatalogOperations();
+ op.initialize(Maps.newHashMap(), null, HIVE_PROPERTIES_METADATA);
+
+ CachedClientPool clientPool = mock(CachedClientPool.class);
+ HiveClient hiveClient = mock(HiveClient.class);
+ String encoded =
TrinoNativeViewCodec.encode(
new TrinoNativeViewCodec.ViewDefinition(
"SELECT 1",
@@ -1090,9 +1149,263 @@ class TestHiveCatalogOperations {
null,
List.of(new TrinoNativeViewCodec.ViewColumn("c1", "integer", null)),
null,
+ "alice",
+ false,
+ List.of()));
+ HiveTable currentTable =
+ HiveTable.builder()
+ .withName("v_hive")
+ .withCatalogName("hive")
+ .withDatabaseName("db")
+ .withColumns(new Column[0])
+ .withComment("Presto View")
+ .withProperties(
+ Maps.newHashMap(
+ ImmutableMap.of(
+ HiveConstants.TABLE_TYPE,
+ TableType.VIRTUAL_VIEW.name(),
+ "presto_view",
+ "true",
+ HiveViewCatalogOperations.TRINO_VIEW_OWNER_PROPERTY,
+ "alice")))
+ .withViewOriginalText(encoded)
+ .build();
+ when(hiveClient.getTable(anyString(), anyString(), anyString())).thenReturn(currentTable);
+
+ ArgumentCaptor<HiveTable> hiveTableCaptor = ArgumentCaptor.forClass(HiveTable.class);
+ doNothing()
+ .when(hiveClient)
+ .alterTable(anyString(), anyString(), anyString(), hiveTableCaptor.capture());
+ when(clientPool.run(any()))
+ .thenAnswer(
+ invocation -> {
+ ClientPool.Action<?, HiveClient, ?> action = invocation.getArgument(0);
+ return action.run(hiveClient);
+ });
+ op.clientPool = clientPool;
+
+ op.alterView(
+ NameIdentifier.of("db", "v_hive"),
+ ViewChange.removeProperty(HiveViewCatalogOperations.TRINO_VIEW_OWNER_PROPERTY),
+ ViewChange.replaceView(
+ new Column[] {Column.of("c1", Types.IntegerType.get())},
+ new SQLRepresentation[] {
+ SQLRepresentation.builder().withDialect("trino").withSql("SELECT 2").build()
+ },
+ null,
+ null,
+ null));
+
+ TrinoNativeViewCodec.ViewDefinition decoded =
+ TrinoNativeViewCodec.decode(hiveTableCaptor.getValue().viewOriginalText());
+ Assertions.assertNull(decoded.owner);
+ Assertions.assertTrue(decoded.runAsInvoker);
+ }
+
+ @Test
+ void testAlterViewReplacePreservesOwnerOfGenuinelyNativeViewWithUnchangedOwner()
+ throws Exception {
+ // A genuinely-native view's owner lives only in the encoded payload, never in the raw HMS
+ // parameters (unlike a Gravitino-created view, which also stores it as a property). Replacing
+ // such a view as the same owner emits no SetProperty for it (callers like
+ // CatalogConnectorMetadata.createView() only emit one when the owner actually changes), so
+ // ReplaceView alone must still preserve the owner instead of silently downgrading to INVOKER.
+ HiveCatalogOperations op = new HiveCatalogOperations();
+ op.initialize(Maps.newHashMap(), null, HIVE_PROPERTIES_METADATA);
+
+ CachedClientPool clientPool = mock(CachedClientPool.class);
+ HiveClient hiveClient = mock(HiveClient.class);
+ String encoded =
+ TrinoNativeViewCodec.encode(
+ new TrinoNativeViewCodec.ViewDefinition(
+ "SELECT 1",
+ null,
null,
+ List.of(new TrinoNativeViewCodec.ViewColumn("c1", "integer", null)),
+ null,
+ "alice",
false,
- List.of())));
+ List.of()));
+ HiveTable currentTable =
+ HiveTable.builder()
+ .withName("v_hive")
+ .withCatalogName("hive")
+ .withDatabaseName("db")
+ .withColumns(new Column[0])
+ .withComment("Presto View")
+ .withProperties(
+ Maps.newHashMap(
+ ImmutableMap.of(
+ HiveConstants.TABLE_TYPE,
+ TableType.VIRTUAL_VIEW.name(),
+ "presto_view",
+ "true")))
+ .withViewOriginalText(encoded)
+ .build();
+ when(hiveClient.getTable(anyString(), anyString(), anyString())).thenReturn(currentTable);
+
+ ArgumentCaptor<HiveTable> hiveTableCaptor = ArgumentCaptor.forClass(HiveTable.class);
+ doNothing()
+ .when(hiveClient)
+ .alterTable(anyString(), anyString(), anyString(), hiveTableCaptor.capture());
+ when(clientPool.run(any()))
+ .thenAnswer(
+ invocation -> {
+ ClientPool.Action<?, HiveClient, ?> action = invocation.getArgument(0);
+ return action.run(hiveClient);
+ });
+ op.clientPool = clientPool;
+
+ op.alterView(
+ NameIdentifier.of("db", "v_hive"),
+ ViewChange.replaceView(
+ new Column[] {Column.of("c1", Types.IntegerType.get())},
+ new SQLRepresentation[] {
+ SQLRepresentation.builder().withDialect("trino").withSql("SELECT 2").build()
+ },
+ null,
+ null,
+ null));
+
+ TrinoNativeViewCodec.ViewDefinition decoded =
+ TrinoNativeViewCodec.decode(hiveTableCaptor.getValue().viewOriginalText());
+ Assertions.assertEquals("alice", decoded.owner);
+ Assertions.assertFalse(decoded.runAsInvoker);
+ }
+
+ @Test
+ void testLoadViewPrefersHmsOwnerOverStalePayloadOwner() throws Exception {
+ // Native Trino treats the HMS table owner as authoritative over the owner encoded in the
+ // view payload: `ALTER VIEW v SET AUTHORIZATION USER bob` updates only the HMS owner, leaving
+ // the payload-encoded owner (here, alice) stale. Loading the view must surface the live HMS
+ // owner, not the stale payload one.
+ HiveClient hiveClient = mock(HiveClient.class);
+ HiveTable currentTable =
+ buildNativeTrinoViewTable(/* payloadOwner= */ "alice", /* hmsOwner= */ "bob", Map.of());
+ when(hiveClient.getTable(anyString(), anyString(), anyString())).thenReturn(currentTable);
+ HiveCatalogOperations op = newHiveCatalogOperationsBackedBy(hiveClient);
+
+ View loaded = op.loadView(NameIdentifier.of("db", "v_trino"));
+ Assertions.assertEquals(
+ "bob", loaded.properties().get(HiveViewCatalogOperations.TRINO_VIEW_OWNER_PROPERTY));
+ }
+
+ @Test
+ void testAlterViewReplaceSyncsHmsOwnerWithPayloadOwner() throws Exception {
+ // Fixing the load path to prefer the live HMS owner would, on its own, make a Gravitino
+ // replace that only updates the payload owner immediately "lose" that change on the next
+ // load. The HMS owner must be kept in sync whenever the connector-managed owner property
+ // changes.
+ HiveClient hiveClient = mock(HiveClient.class);
+ HiveTable currentTable =
+ buildNativeTrinoViewTable(
+ /* payloadOwner= */ "alice",
+ /* hmsOwner= */ "alice",
+ Map.of(HiveViewCatalogOperations.TRINO_VIEW_OWNER_PROPERTY, "alice"));
+ when(hiveClient.getTable(anyString(), anyString(), anyString())).thenReturn(currentTable);
+
+ ArgumentCaptor<HiveTable> hiveTableCaptor = ArgumentCaptor.forClass(HiveTable.class);
+ doNothing()
+ .when(hiveClient)
+ .alterTable(anyString(), anyString(), anyString(), hiveTableCaptor.capture());
+ HiveCatalogOperations op = newHiveCatalogOperationsBackedBy(hiveClient);
+
+ op.alterView(
+ NameIdentifier.of("db", "v_trino"),
+ ViewChange.setProperty(HiveViewCatalogOperations.TRINO_VIEW_OWNER_PROPERTY, "bob"),
+ ViewChange.replaceView(
+ new Column[] {Column.of("c1", Types.IntegerType.get())},
+ new SQLRepresentation[] {
+ SQLRepresentation.builder().withDialect("trino").withSql("SELECT 2").build()
+ },
+ null,
+ null,
+ null));
+
+ Assertions.assertEquals("bob", hiveTableCaptor.getValue().auditInfo().creator());
+ }
+
+ @Test
+ void testAlterViewReplacePreservesEffectiveOwnerWhenPayloadOwnerIsStale() throws Exception {
+ // The caller (e.g. CatalogConnectorMetadata.createView()) observes the current owner through
+ // loadView(), which already prefers the live HMS owner (bob) over the stale payload owner
+ // (alice). Replacing the view as bob therefore emits no owner SetProperty, since the caller
+ // sees no change. alterView() must seed its own notion of "current owner" from that same
+ // effective HMS owner, not the stale payload owner, or it silently overwrites HMS back to
+ // alice.
+ HiveClient hiveClient = mock(HiveClient.class);
+ HiveTable currentTable =
+ buildNativeTrinoViewTable(/* payloadOwner= */ "alice", /* hmsOwner= */ "bob", Map.of());
+ when(hiveClient.getTable(anyString(), anyString(), anyString())).thenReturn(currentTable);
+
+ ArgumentCaptor<HiveTable> hiveTableCaptor = ArgumentCaptor.forClass(HiveTable.class);
+ doNothing()
+ .when(hiveClient)
+ .alterTable(anyString(), anyString(), anyString(), hiveTableCaptor.capture());
+ HiveCatalogOperations op = newHiveCatalogOperationsBackedBy(hiveClient);
+
+ op.alterView(
+ NameIdentifier.of("db", "v_trino"),
+ ViewChange.replaceView(
+ new Column[] {Column.of("c1", Types.IntegerType.get())},
+ new SQLRepresentation[] {
+ SQLRepresentation.builder().withDialect("trino").withSql("SELECT 2").build()
+ },
+ null,
+ null,
+ null));
+
+ Assertions.assertEquals("bob", hiveTableCaptor.getValue().auditInfo().creator());
+ TrinoNativeViewCodec.ViewDefinition decoded =
+ TrinoNativeViewCodec.decode(hiveTableCaptor.getValue().viewOriginalText());
+ Assertions.assertEquals("bob", decoded.owner);
+ }
+
+ @Test
+ void testAlterViewRenamePreservesEffectiveOwnerWhenPayloadOwnerIsStale() throws Exception {
+ // A rename doesn't touch the owner at all, so it must not revert HMS ownership back to the
+ // stale payload owner either.
+ HiveClient hiveClient = mock(HiveClient.class);
+ HiveTable currentTable =
+ buildNativeTrinoViewTable(/* payloadOwner= */ "alice", /* hmsOwner= */ "bob", Map.of());
+ when(hiveClient.getTable(anyString(), anyString(), eq("v_trino"))).thenReturn(currentTable);
+ when(hiveClient.getTable(anyString(), anyString(), eq("v_trino2")))
+ .thenThrow(new NoSuchTableException("v_trino2 does not exist"));
+
+ ArgumentCaptor<HiveTable> hiveTableCaptor = ArgumentCaptor.forClass(HiveTable.class);
+ doNothing()
+ .when(hiveClient)
+ .alterTable(anyString(), anyString(), anyString(), hiveTableCaptor.capture());
+ HiveCatalogOperations op = newHiveCatalogOperationsBackedBy(hiveClient);
+
+ op.alterView(NameIdentifier.of("db", "v_trino"), ViewChange.rename("v_trino2"));
+
+ Assertions.assertEquals("bob", hiveTableCaptor.getValue().auditInfo().creator());
+ }
+
+ @Test
+ void testAlterViewRenameDoesNotReassignOwnerForInvokerView() throws Exception {
+ // A SECURITY INVOKER native view has no owner in its payload at all, so currentOwner stays
+ // null and TRINO_VIEW_OWNER_PROPERTY is never seeded into updatedProperties. The owner-sync
+ // block must not run in that case: resolveHmsOwner() falls back to the current principal when
+ // the property is absent, which would otherwise reassign real HMS ownership (here, alice) to
+ // whoever happens to run an unrelated change like this rename.
+ HiveClient hiveClient = mock(HiveClient.class);
+ HiveTable currentTable =
+ buildNativeTrinoViewTable(/* payloadOwner= */ null, /* hmsOwner= */ "alice", Map.of());
+ when(hiveClient.getTable(anyString(), anyString(), eq("v_trino"))).thenReturn(currentTable);
+ when(hiveClient.getTable(anyString(), anyString(), eq("v_trino2")))
+ .thenThrow(new NoSuchTableException("v_trino2 does not exist"));
+
+ ArgumentCaptor<HiveTable> hiveTableCaptor = ArgumentCaptor.forClass(HiveTable.class);
+ doNothing()
+ .when(hiveClient)
+ .alterTable(anyString(), anyString(), anyString(), hiveTableCaptor.capture());
+ HiveCatalogOperations op = newHiveCatalogOperationsBackedBy(hiveClient);
+
+ op.alterView(NameIdentifier.of("db", "v_trino"), ViewChange.rename("v_trino2"));
+
+ Assertions.assertEquals("alice", hiveTableCaptor.getValue().auditInfo().creator());
}
@Test
@@ -1101,17 +1414,92 @@ class TestHiveCatalogOperations {
// non-empty path would silently discard it. TrinoNativeViewCodec.encode() always writes an
// empty path (Gravitino itself never produces one), so this payload is built by hand to
// simulate a view created directly by a native Trino connector with a non-empty path.
- String encoded =
- "/* Presto View: "
- + Base64.getEncoder()
- .encodeToString(
- ("{\"originalSql\":\"SELECT 1\",\"catalog\":null,\"schema\":null,"
- + "\"columns\":[{\"name\":\"c1\",\"type\":\"integer\",\"comment\":null}],"
- + "\"comment\":null,\"owner\":null,\"runAsInvoker\":true,"
- + "\"path\":[{\"catalog\":\"c\",\"schema\":\"s\"}]}")
- .getBytes(StandardCharsets.UTF_8))
- + " */";
- assertReplaceRejectsUnrepresentableNativeView(encoded);
+ assertReplaceRejectsUnrepresentableNativeView(nativeViewPayloadWithNonEmptyPath());
+ }
+
+ @Test
+ void testAlterViewRenameRejectsExistingNonEmptyPathBeforeMutatingHms() throws Exception {
+ // A rename (or any non-ReplaceView change) doesn't touch the view's encoded payload, so it
+ // was previously allowed to proceed even on a native view with an unrepresentable non-empty
+ // path - only to have the HMS rename already succeed and then throw while toHiveView() built
+ // the return value, reporting a successful mutation as a failure. The rejection must happen
+ // upfront, before alterTable() is ever called.
+ String encoded = nativeViewPayloadWithNonEmptyPath();
+ HiveClient hiveClient = mock(HiveClient.class);
+ HiveTable currentTable =
+ HiveTable.builder()
+ .withName("v_trino")
+ .withCatalogName("hive")
+ .withDatabaseName("db")
+ .withColumns(new Column[0])
+ .withComment("Presto View")
+ .withProperties(
+ Maps.newHashMap(
+ ImmutableMap.of(
+ HiveConstants.TABLE_TYPE,
+ TableType.VIRTUAL_VIEW.name(),
+ "presto_view",
+ "true")))
+ .withViewOriginalText(encoded)
+ .build();
+ when(hiveClient.getTable(anyString(), anyString(), anyString())).thenReturn(currentTable);
+ HiveCatalogOperations op = newHiveCatalogOperationsBackedBy(hiveClient);
+
+ Assertions.assertThrows(
+ UnsupportedOperationException.class,
+ () -> op.alterView(NameIdentifier.of("db", "v_trino"), ViewChange.rename("v_trino2")));
+
+ verify(hiveClient, never()).alterTable(anyString(), anyString(), anyString(), any());
+ }
+
+ @Test
+ void testLoadViewRejectsNonEmptyPath() throws Exception {
+ // Gravitino's view model has no SQL path (SET PATH) concept; silently dropping a non-empty
+ // path on load would let an unqualified function resolve differently than the native Trino
+ // view's creator intended. TrinoNativeViewCodec.encode() always writes an empty path
+ // (Gravitino itself never produces one), so this payload is built by hand to simulate a view
+ // created directly by a native Trino connector with a non-empty path.
+ String encoded = nativeViewPayloadWithNonEmptyPath();
+ HiveClient hiveClient = mock(HiveClient.class);
+ HiveTable currentTable =
+ HiveTable.builder()
+ .withName("v_trino")
+ .withCatalogName("hive")
+ .withDatabaseName("db")
+ .withColumns(new Column[0])
+ .withComment("Presto View")
+ .withProperties(
+ Maps.newHashMap(
+ ImmutableMap.of(
+ HiveConstants.TABLE_TYPE,
+ TableType.VIRTUAL_VIEW.name(),
+ "presto_view",
+ "true")))
+ .withViewOriginalText(encoded)
+ .build();
+ when(hiveClient.getTable(anyString(), anyString(), anyString())).thenReturn(currentTable);
+ HiveCatalogOperations op = newHiveCatalogOperationsBackedBy(hiveClient);
+
+ Assertions.assertThrows(
+ UnsupportedOperationException.class, () -> op.loadView(NameIdentifier.of("db", "v_trino")));
+ }
+
+ /**
+ * Builds a native "Presto View" payload with a non-empty SQL path by hand.
+ * TrinoNativeViewCodec.encode() always writes an empty path (Gravitino itself never produces
+ * one), so this simulates a view created directly by a native Trino connector with a non-empty
+ * path (e.g. one set via {@code SET PATH} before {@code CREATE VIEW}).
+ */
+ private static String nativeViewPayloadWithNonEmptyPath() {
+ return "/* Presto View: "
+ + Base64.getEncoder()
+ .encodeToString(
+ ("{\"originalSql\":\"SELECT 1\",\"catalog\":null,\"schema\":null,"
+ + "\"columns\":[{\"name\":\"c1\",\"type\":\"integer\",\"comment\":null}],"
+ + "\"comment\":null,\"owner\":null,\"runAsInvoker\":true,"
+ + "\"path\":[{\"catalog\":\"c\",\"schema\":\"s\"}]}")
+ .getBytes(StandardCharsets.UTF_8))
+ + " */";
}
private void assertReplaceRejectsUnrepresentableNativeView(String encoded) throws Exception {
@@ -1776,4 +2164,59 @@ class TestHiveCatalogOperations {
Assertions.assertFalse(HiveCatalogOperations.canSkipStatsUpdate(new TableChange[] {}));
Assertions.assertFalse(HiveCatalogOperations.canSkipStatsUpdate(null));
}
+
+ /**
+ * Builds a native Trino "Presto View" {@code v_trino} table whose encoded payload carries {@code
+ * payloadOwner} while the live HMS table owner (audit creator) is {@code hmsOwner} — shared
+ * fixture for the HMS-owner-vs-payload-owner reconciliation tests.
+ */
+ private static HiveTable buildNativeTrinoViewTable(
+ String payloadOwner, String hmsOwner, Map<String, String> extraProperties) {
+ String encoded =
+ TrinoNativeViewCodec.encode(
+ new TrinoNativeViewCodec.ViewDefinition(
+ "SELECT 1",
+ null,
+ null,
+ List.of(new TrinoNativeViewCodec.ViewColumn("c1", "integer", null)),
+ null,
+ payloadOwner,
+ false,
+ List.of()));
+ Map<String, String> properties =
+ Maps.newHashMap(
+ ImmutableMap.of(
+ HiveConstants.TABLE_TYPE, TableType.VIRTUAL_VIEW.name(), "presto_view", "true"));
+ properties.putAll(extraProperties);
+ return HiveTable.builder()
+ .withName("v_trino")
+ .withCatalogName("hive")
+ .withDatabaseName("db")
+ .withColumns(new Column[0])
+ .withComment("Presto View")
+ .withProperties(properties)
+ .withViewOriginalText(encoded)
+ .withAuditInfo(AuditInfo.builder().withCreator(hmsOwner).build())
+ .build();
+ }
+
+ /**
+ * Creates a {@link HiveCatalogOperations} whose client pool delegates every call directly to
+ * {@code hiveClient}, for tests that only need to stub the client itself.
+ */
+ private static HiveCatalogOperations newHiveCatalogOperationsBackedBy(HiveClient hiveClient)
+ throws Exception {
+ HiveCatalogOperations op = new HiveCatalogOperations();
+ op.initialize(Maps.newHashMap(), null, HIVE_PROPERTIES_METADATA);
+
+ CachedClientPool clientPool = mock(CachedClientPool.class);
+ when(clientPool.run(any()))
+ .thenAnswer(
+ invocation -> {
+ ClientPool.Action<?, HiveClient, ?> action = invocation.getArgument(0);
+ return action.run(hiveClient);
+ });
+ op.clientPool = clientPool;
+ return op;
+ }
}
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
index 776f9e1810..622047e4cd 100644
--- 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
@@ -44,6 +44,8 @@ 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.Type;
+import org.apache.gravitino.rel.types.Types;
import org.apache.gravitino.utils.PrincipalUtils;
import org.apache.iceberg.MetadataUpdate;
import org.apache.iceberg.Schema;
@@ -127,7 +129,7 @@ class IcebergViewCatalogOperations {
org.apache.iceberg.catalog.Namespace icebergNamespace =
IcebergCatalogWrapperHelper.getIcebergNamespace(ident.namespace());
- Schema schema = ConvertUtil.toIcebergSchema(columns);
+ Schema schema = ConvertUtil.toIcebergSchema(widenVarcharColumns(columns));
List<ViewRepresentation> viewRepresentations = new ArrayList<>();
for (Representation representation : representations) {
viewRepresentations.add(toSqlViewRepresentation(representation));
@@ -231,6 +233,11 @@ class IcebergViewCatalogOperations {
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);
+ } catch (AlreadyExistsException e) {
+ throw new ViewAlreadyExistsException(
+ e,
+ "View %s already exists in Iceberg catalog",
+ NameIdentifier.of(ident.namespace(), rename.getNewName()));
}
}
@@ -367,7 +374,8 @@ class IcebergViewCatalogOperations {
int newVersionId =
currentVersion != null ? currentVersion.versionId() + 1 : INITIAL_VIEW_VERSION_ID;
- Schema replacementSchema = ConvertUtil.toIcebergSchema(replace.getColumns());
+ Schema replacementSchema =
+ ConvertUtil.toIcebergSchema(widenVarcharColumns(replace.getColumns()));
Optional<Schema> existingSchema =
metadata.schemas().stream()
.filter(schema -> schema.sameSchema(replacementSchema))
@@ -443,4 +451,57 @@ class IcebergViewCatalogOperations {
private static String currentUser() {
return PrincipalUtils.getCurrentUserName();
}
+
+ /**
+ * Iceberg has no length-bound string type, only its single unbounded {@code string}. A view's
+ * output column, unlike a physical table column, may legitimately carry Gravitino's {@link
+ * Types.VarCharType} (e.g. {@code SELECT 'x' AS c} produces varchar(1)), since the connector
+ * layer does not apply physical-storage type restrictions to view columns. Widen it, including
+ * any occurrence nested inside a list/map/struct (e.g. {@code ARRAY['x']}), to Iceberg's string
+ * type before building the schema, or {@link ConvertUtil#toIcebergSchema} rejects it as an
+ * unsupported type.
+ */
+ private static Column[] widenVarcharColumns(Column[] columns) {
+ return Arrays.stream(columns)
+ .map(
+ col ->
+ Column.of(
+ col.name(),
+ widenVarchar(col.dataType()),
+ col.comment(),
+ col.nullable(),
+ col.autoIncrement(),
+ col.defaultValue()))
+ .toArray(Column[]::new);
+ }
+
+ /** Recursively widens any {@link Types.VarCharType} nested inside {@code type}. */
+ private static Type widenVarchar(Type type) {
+ if (type instanceof Types.VarCharType) {
+ return Types.StringType.get();
+ } else if (type instanceof Types.ListType) {
+ Types.ListType listType = (Types.ListType) type;
+ return Types.ListType.of(widenVarchar(listType.elementType()), listType.elementNullable());
+ } else if (type instanceof Types.MapType) {
+ Types.MapType mapType = (Types.MapType) type;
+ return Types.MapType.of(
+ widenVarchar(mapType.keyType()),
+ widenVarchar(mapType.valueType()),
+ mapType.valueNullable());
+ } else if (type instanceof Types.StructType) {
+ Types.StructType structType = (Types.StructType) type;
+ Types.StructType.Field[] fields =
+ Arrays.stream(structType.fields())
+ .map(
+ field ->
+ Types.StructType.Field.of(
+ field.name(),
+ widenVarchar(field.type()),
+ field.nullable(),
+ field.comment()))
+ .toArray(Types.StructType.Field[]::new);
+ return Types.StructType.of(fields);
+ }
+ return type;
+ }
}
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
index 65ba63a7fa..01320f915f 100644
--- 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
@@ -20,6 +20,7 @@ package org.apache.gravitino.catalog.lakehouse.iceberg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -30,6 +31,7 @@ import java.util.Map;
import java.util.Set;
import org.apache.gravitino.NameIdentifier;
import org.apache.gravitino.exceptions.NoSuchViewException;
+import org.apache.gravitino.exceptions.ViewAlreadyExistsException;
import org.apache.gravitino.iceberg.common.ops.IcebergCatalogWrapper;
import org.apache.gravitino.rel.Column;
import org.apache.gravitino.rel.Representation;
@@ -41,8 +43,10 @@ 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.AlreadyExistsException;
import org.apache.iceberg.exceptions.ServiceFailureException;
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.LoadViewResponse;
import org.apache.iceberg.view.ViewMetadata;
@@ -108,6 +112,21 @@ public class TestIcebergViewCatalogOperations {
verify(wrapper, never()).renameView(any());
}
+ @Test
+ public void testAlterViewRenameTranslatesAlreadyExistsException() {
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+ doThrow(new AlreadyExistsException("view already exists"))
+ .when(wrapper)
+ .renameView(any(RenameTableRequest.class));
+
+ Assertions.assertThrows(
+ ViewAlreadyExistsException.class,
+ () -> operations.alterView(ident, ViewChange.rename("view2")));
+ }
+
@Test
public void testCreateViewRejectsSqlLikeRepresentationWithoutSqlRepresentationClass()
throws Exception {
@@ -216,6 +235,145 @@ public class TestIcebergViewCatalogOperations {
Assertions.assertNull(view.defaultCatalog());
}
+ @Test
+ public void testCreateViewWidensVarcharColumnToIcebergString() throws Exception {
+ // A view's output column may carry Gravitino's VarCharType (e.g. SELECT 'x' AS c produces
+ // varchar(1)), since the connector layer does not apply physical-table type restrictions to
+ // view columns. Iceberg has no length-bound string type, so this must be widened before
+ // reaching ConvertUtil.toIcebergSchema(), which otherwise rejects it as unsupported.
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+ Column[] columns = {Column.of("c", Types.VarCharType.of(1), null)};
+ SQLRepresentation representation =
+ SQLRepresentation.builder().withDialect("trino").withSql("SELECT 'x' AS c").build();
+
+ doAnswer(
+ invocation -> {
+ ImmutableCreateViewRequest request = invocation.getArgument(1);
+ Assertions.assertEquals(
+ org.apache.iceberg.types.Types.StringType.get(),
+ request.schema().findField("c").type());
+ return mockLoadViewResponse();
+ })
+ .when(wrapper)
+ .createView(
+ any(org.apache.iceberg.catalog.Namespace.class), any(ImmutableCreateViewRequest.class));
+
+ operations.createView(
+ ident,
+ null,
+ columns,
+ new Representation[] {representation},
+ null,
+ null,
+ Collections.emptyMap());
+ }
+
+ @Test
+ public void testCreateViewWidensNestedVarcharToIcebergString() throws Exception {
+ // widenVarcharColumns() must recurse into list/map/struct element types too: SELECT
+ // ARRAY['x'] AS c reaches ConvertUtil.toIcebergSchema() with a VarCharType nested inside a
+ // ListType, which ToIcebergType otherwise rejects just like a top-level VarCharType.
+ IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
+ IcebergViewCatalogOperations operations = new IcebergViewCatalogOperations(wrapper);
+
+ NameIdentifier ident = NameIdentifier.of("schema1", "view1");
+ Column[] columns = {
+ Column.of("list_col", Types.ListType.of(Types.VarCharType.of(1), true), null),
+ Column.of(
+ "map_col",
+ Types.MapType.of(Types.VarCharType.of(1), Types.VarCharType.of(2), true),
+ null),
+ Column.of(
+ "struct_col",
+ Types.StructType.of(Types.StructType.Field.nullableField("f", Types.VarCharType.of(1))),
+ null),
+ };
+ SQLRepresentation representation =
+ SQLRepresentation.builder().withDialect("trino").withSql("SELECT ...").build();
+
+ doAnswer(
+ invocation -> {
+ ImmutableCreateViewRequest request = invocation.getArgument(1);
+ org.apache.iceberg.types.Types.StringType icebergString =
+ org.apache.iceberg.types.Types.StringType.get();
+ Assertions.assertEquals(
+ icebergString,
+ request.schema().findField("list_col").type().asListType().elementType());
+ Assertions.assertEquals(
+ icebergString,
+ request.schema().findField("map_col").type().asMapType().keyType());
+ Assertions.assertEquals(
+ icebergString,
+ request.schema().findField("map_col").type().asMapType().valueType());
+ Assertions.assertEquals(
+ icebergString,
+ request
+ .schema()
+ .findField("struct_col")
+ .type()
+ .asStructType()
+ .fields()
+ .get(0)
+ .type());
+ return mockLoadViewResponse();
+ })
+ .when(wrapper)
+ .createView(
+ any(org.apache.iceberg.catalog.Namespace.class), any(ImmutableCreateViewRequest.class));
+
+ operations.createView(
+ ident,
+ null,
+ columns,
+ new Representation[] {representation},
+ null,
+ null,
+ Collections.emptyMap());
+ }
+
+ @Test
+ public void testAlterViewReplaceWidensVarcharColumnToIcebergString() throws Exception {
+ // Fixing createView() alone would leave replace broken: a view initially created with only
+ // StringType columns, then replaced with a query that now produces a varchar(n) output
+ // column, must still succeed at the server boundary.
+ 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("c", Types.VarCharType.of(1), null)};
+ SQLRepresentation representation =
+ SQLRepresentation.builder().withDialect("trino").withSql("SELECT 'x' AS c").build();
+
+ doAnswer(
+ invocation -> {
+ UpdateTableRequest request = invocation.getArgument(1);
+ Assertions.assertEquals(
+ org.apache.iceberg.types.Types.StringType.get(),
+ extractAddedSchema(request.updates()).findField("c").type());
+ return mockLoadViewResponse();
+ })
+ .when(wrapper)
+ .updateView(any(TableIdentifier.class), any(UpdateTableRequest.class));
+
+ operations.alterView(
+ ident,
+ ViewChange.replaceView(columns, new Representation[] {representation}, null, null, null));
+
+ verify(wrapper).updateView(any(TableIdentifier.class), any(UpdateTableRequest.class));
+ }
+
@Test
public void testAlterViewSetAfterRemoveKeepsProperty() throws Exception {
IcebergCatalogWrapper wrapper = Mockito.mock(IcebergCatalogWrapper.class);
@@ -374,4 +532,12 @@ public class TestIcebergViewCatalogOperations {
.findFirst()
.orElse(java.util.Collections.emptySet());
}
+
+ private static org.apache.iceberg.Schema extractAddedSchema(List<MetadataUpdate> updates) {
+ return updates.stream()
+ .filter(update -> update instanceof MetadataUpdate.AddSchema)
+ .map(update -> ((MetadataUpdate.AddSchema) update).schema())
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("No AddSchema update found"));
+ }
}
diff --git a/docs/trino-connector/sql-support.md b/docs/trino-connector/sql-support.md
index 7d4ff4f0db..7c6c919232 100644
--- a/docs/trino-connector/sql-support.md
+++ b/docs/trino-connector/sql-support.md
@@ -45,6 +45,38 @@ The connector provides read access and write access to data and metadata stored
- [DROP SCHEMA](https://trino.io/docs/current/sql/drop-schema.html)
- [COMMENT](https://trino.io/docs/current/sql/comment.html)
+### View Management
+
+- [CREATE VIEW](https://trino.io/docs/current/sql/create-view.html)
+- [CREATE OR REPLACE VIEW](https://trino.io/docs/current/sql/create-view.html)
+- [SHOW CREATE VIEW](https://trino.io/docs/current/sql/show-create-view.html)
+- [DROP VIEW](https://trino.io/docs/current/sql/drop-view.html)
+- [ALTER VIEW ... RENAME TO](https://trino.io/docs/current/sql/alter-view.html)
+
+View management is only supported for catalogs backed by Hive or Iceberg; other catalogs
+(e.g. Glue, JDBC, Memory) do not support view operations. A view stored by Gravitino may carry SQL
+representations for multiple engines (Hive, Spark, Flink, Trino); the Trino connector only reads and
+writes the Trino dialect representation. A view that has no Trino SQL representation is silently
+invisible to Trino (it does not appear in `SHOW TABLES`/`information_schema` and cannot be loaded),
+rather than causing an error. View owner (`SECURITY DEFINER`/`SECURITY INVOKER`) is persisted and
+reloaded via a reserved internal property; for Hive-backed catalogs this round-trips through
+Trino's native "Presto View" Hive Metastore format, with the live Hive Metastore table owner taking
+precedence over a possibly-stale owner encoded in that payload. The SQL path (`SET PATH`) and
+view-level `WITH (...)` properties are not supported: a view with a non-empty path is rejected
+rather than silently discarding it, and a `WITH (...)` clause on `CREATE VIEW` is rejected because
+no view property is registered.
+
+Some catalogs (e.g. Iceberg) can store a view with a default schema but no default catalog. In
+single-metalake mode this is resolved against the current Trino catalog. In multi-metalake mode it
+cannot be resolved reliably, so loading such a view fails with an error instead of silently
+resolving to a possibly incorrect catalog.
+
+For Hive-backed catalogs, Trino dialect views are stored using Trino's own native "Presto View"
+Hive Metastore format, so views are interoperable with a native Trino (or Presto) Hive connector
+pointed at the same Hive Metastore: a view created directly through a native Trino Hive connector
+is visible and queryable through Gravitino, and a view created through Gravitino is visible and
+queryable through a native Trino Hive connector.
+
### Transactions
- [START TRANSACTION](https://trino.io/docs/current/sql/start-transaction.html)
diff --git a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryIT.java b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryIT.java
index abac1493a6..5ef9e7b532 100644
--- a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryIT.java
+++ b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryIT.java
@@ -289,7 +289,7 @@ public class TrinoQueryIT extends TrinoQueryITBase {
* @param result the actual result
* @return false if the expected result is empty or the actual result does not match the expected.
* For {@literal <BLANK_LINE>} case, return true if the actual result is empty. For {@literal
- * <QUERY_FAILED>} case, replace the placeholder with "^Query \\w+ failed.*: " and do match.
+ * <QUERY_FAILED>} case, match the query failure prefix and the remaining expected result.
*/
static boolean match(String expectResult, String result) {
if (expectResult.isEmpty()) {
@@ -314,11 +314,9 @@ public class TrinoQueryIT extends TrinoQueryITBase {
// expectResult:
// <QUERY_FAILED> Schema must be specified when session schema is not set
if (expectResult.startsWith("<QUERY_FAILED>")) {
- return Pattern.compile(
- "^Query \\w+ failed.*: "
- + Pattern.quote(expectResult.replace("<QUERY_FAILED>", "").trim()))
- .matcher(result)
- .find();
+ String failureMessage = expectResult.replace("<QUERY_FAILED>", "").trim();
+ return wildcardMatch(
+ "^Query \\w+ failed.*: " + wildcardPattern(failureMessage), result, false);
}
// match text
@@ -338,11 +336,20 @@ public class TrinoQueryIT extends TrinoQueryITBase {
//
// location = 'hdfs://%:9000/user/hive/warehouse/gt_db1.db/tb01',
// ...
- expectResult = expectResult.replace("\n", "");
- expectResult = "^\\Q" + expectResult.replace("%", "\\E.*?\\Q") + "\\E$";
+ return wildcardMatch("^" + wildcardPattern(expectResult), result, true);
+ }
+
+ private static boolean wildcardMatch(String expectPattern, String result, boolean matchEnd) {
+ expectPattern = expectPattern.replace("\n", "");
+ if (matchEnd) {
+ expectPattern += "$";
+ }
result = result.replace("\n", "");
- match = Pattern.compile(expectResult).matcher(result).find();
- return match;
+ return Pattern.compile(expectPattern).matcher(result).find();
+ }
+
+ private static String wildcardPattern(String expectResult) {
+ return "\\Q" + expectResult.replace("%", "\\E.*?\\Q") + "\\E";
}
public void testSql() throws Exception {
@@ -480,6 +487,7 @@ public class TrinoQueryIT extends TrinoQueryITBase {
String testSetDirName, String filename, TrinoQueryRunner queryRunner) throws Exception {
String path = ITUtils.joinPath(testSetDirName, filename);
String sqls = TrinoQueryITBase.readFileToString(path);
+ sqls = removeSqlComments(sqls);
String resultFileName = path.replace(".sql", ".txt");
FileOutputStream outputStream = new FileOutputStream(resultFileName);
diff --git a/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/00019_view.sql b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/00019_view.sql
new file mode 100644
index 0000000000..8bc72fead5
--- /dev/null
+++ b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/00019_view.sql
@@ -0,0 +1,59 @@
+CREATE SCHEMA gt_hive.gt_hive_view_db;
+CREATE TABLE gt_hive.gt_hive_view_db.t01 (id integer, name varchar, salary integer);
+INSERT INTO gt_hive.gt_hive_view_db.t01 VALUES (1, 'alice', 100), (2, 'bob', 200);
+
+-- create + query + show tables
+CREATE VIEW gt_hive.gt_hive_view_db.v01 AS SELECT id, name FROM gt_hive.gt_hive_view_db.t01 WHERE salary > 100;
+SHOW TABLES FROM gt_hive.gt_hive_view_db;
+SELECT * FROM gt_hive.gt_hive_view_db.v01 ORDER BY id;
+
+-- show create view
+SHOW CREATE VIEW gt_hive.gt_hive_view_db.v01;
+
+-- create or replace
+CREATE OR REPLACE VIEW gt_hive.gt_hive_view_db.v01 AS SELECT id, name, salary FROM gt_hive.gt_hive_view_db.t01;
+SELECT * FROM gt_hive.gt_hive_view_db.v01 ORDER BY id;
+
+-- rename + drop
+ALTER VIEW gt_hive.gt_hive_view_db.v01 RENAME TO gt_hive.gt_hive_view_db.v02;
+SHOW TABLES FROM gt_hive.gt_hive_view_db;
+DROP VIEW gt_hive.gt_hive_view_db.v02;
+SHOW TABLES FROM gt_hive.gt_hive_view_db;
+
+-- default catalog/schema round trip: create a view via USE with an unqualified source table
+-- reference, then switch the session default elsewhere before querying it, so the query can only
+-- succeed if the view's own stored default catalog/schema (not the ambient session) is used to
+-- resolve "t01".
+USE gt_hive.gt_hive_view_db;
+CREATE VIEW v03 AS SELECT id, name FROM t01 WHERE salary > 100;
+USE gt_hive.information_schema;
+SELECT * FROM gt_hive.gt_hive_view_db.v03 ORDER BY id;
+DROP VIEW gt_hive.gt_hive_view_db.v03;
+
+-- error cases: drop nonexistent view; create view colliding with existing table name (HMS natural rejection)
+DROP VIEW gt_hive.gt_hive_view_db.nonexistent_view;
+CREATE VIEW gt_hive.gt_hive_view_db.t01 AS SELECT 1;
+
+-- native Trino view interop: a view created directly through Trino's own native Hive connector
+-- (bypassing Gravitino) is encoded using Trino's own native "Presto View" format; Gravitino's
+-- Trino connector recognizes this format directly, so the view is visible and queryable through
+-- gt_hive too, without going through Gravitino at all to create it.
+CREATE VIEW native_hive.gt_hive_view_db.native_v01 AS SELECT id, name FROM native_hive.gt_hive_view_db.t01;
+SHOW TABLES FROM gt_hive.gt_hive_view_db;
+SELECT * FROM gt_hive.gt_hive_view_db.native_v01 ORDER BY id;
+DROP VIEW native_hive.gt_hive_view_db.native_v01;
+
+-- reverse direction: a view created through gt_hive is persisted to Hive Metastore using Trino's
+-- own native "Presto View" format, so it is directly visible and queryable through Trino's native
+-- Hive connector (native_hive) without going through Gravitino at all, including a timestamp(3)
+-- output column.
+CREATE TABLE gt_hive.gt_hive_view_db.t02 (id integer, name varchar, created_at timestamp(3));
+INSERT INTO gt_hive.gt_hive_view_db.t02 VALUES (1, 'alice', TIMESTAMP '2024-01-01 00:00:00.000'), (2, 'bob', TIMESTAMP '2024-01-02 00:00:00.000');
+CREATE VIEW gt_hive.gt_hive_view_db.v04 AS SELECT id, name, created_at FROM gt_hive.gt_hive_view_db.t02 WHERE id = 2;
+SHOW CREATE VIEW native_hive.gt_hive_view_db.v04;
+SELECT * FROM native_hive.gt_hive_view_db.v04 ORDER BY id;
+DROP VIEW gt_hive.gt_hive_view_db.v04;
+DROP TABLE gt_hive.gt_hive_view_db.t02;
+
+DROP TABLE gt_hive.gt_hive_view_db.t01;
+DROP SCHEMA gt_hive.gt_hive_view_db;
diff --git a/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/00019_view.txt b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/00019_view.txt
new file mode 100644
index 0000000000..415a21a2ce
--- /dev/null
+++ b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/00019_view.txt
@@ -0,0 +1,83 @@
+CREATE SCHEMA
+
+CREATE TABLE
+
+INSERT: 2 rows
+
+CREATE VIEW
+
+"t01"
+"v01"
+
+"2","bob"
+
+"CREATE VIEW gt_hive.gt_hive_view_db.v01 SECURITY DEFINER AS
+SELECT
+ id
+, name
+FROM
+ gt_hive.gt_hive_view_db.t01
+WHERE (salary > 100)"
+
+CREATE VIEW
+
+"1","alice","100"
+"2","bob","200"
+
+RENAME VIEW
+
+"t01"
+"v02"
+
+DROP VIEW
+
+"t01"
+
+USE
+
+CREATE VIEW
+
+USE
+
+"2","bob"
+
+DROP VIEW
+
+<QUERY_FAILED> View 'gt_hive.gt_hive_view_db.nonexistent_view' does not exist
+
+<QUERY_FAILED> Table already exists: 'gt_hive.gt_hive_view_db.t01'
+
+CREATE VIEW
+
+"native_v01"
+"t01"
+
+"1","alice"
+"2","bob"
+
+DROP VIEW
+
+CREATE TABLE
+
+INSERT: 2 rows
+
+CREATE VIEW
+
+"CREATE VIEW native_hive.gt_hive_view_db.v04 SECURITY DEFINER AS
+SELECT
+ id
+, name
+, created_at
+FROM
+ gt_hive.gt_hive_view_db.t02
+WHERE (id = 2)"
+
+"2","bob","2024-01-02 00:00:00.000"
+
+DROP VIEW
+
+DROP TABLE
+
+DROP TABLE
+
+DROP SCHEMA
diff --git a/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/catalog_hive_cleanup.sql b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/catalog_hive_cleanup.sql
index a5fbf61e92..b0b51c29d2 100644
--- a/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/catalog_hive_cleanup.sql
+++ b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/catalog_hive_cleanup.sql
@@ -1 +1,2 @@
-CALL gravitino.system.drop_catalog('gt_hive');
\ No newline at end of file
+CALL gravitino.system.drop_catalog('gt_hive');
+DROP CATALOG native_hive;
\ No newline at end of file
diff --git a/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/catalog_hive_prepare.sql b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/catalog_hive_prepare.sql
index b392ae230b..24dc9c6f86 100644
--- a/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/catalog_hive_prepare.sql
+++ b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/hive/catalog_hive_prepare.sql
@@ -5,4 +5,10 @@ call gravitino.system.create_catalog(
array['metastore.uris'],
array['${hive_uri}']
)
+);
+
+CREATE CATALOG native_hive USING hive
+WITH (
+ "hive.metastore.uri" = '${hive_uri}',
+ "fs.hadoop.enabled" = 'true'
);
\ No newline at end of file
diff --git a/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/lakehouse-iceberg/00014_view.sql b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/lakehouse-iceberg/00014_view.sql
new file mode 100644
index 0000000000..8a7bdff0de
--- /dev/null
+++ b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/lakehouse-iceberg/00014_view.sql
@@ -0,0 +1,22 @@
+CREATE SCHEMA gt_view_db;
+CREATE TABLE gt_view_db.t01 (id integer, name varchar, salary integer);
+INSERT INTO gt_view_db.t01 VALUES (1, 'alice', 100), (2, 'bob', 200);
+
+CREATE VIEW gt_view_db.v01 AS SELECT id, name FROM gt_view_db.t01 WHERE salary > 100;
+SHOW TABLES FROM gt_view_db;
+SELECT * FROM gt_view_db.v01 ORDER BY id;
+
+SHOW CREATE VIEW gt_view_db.v01;
+
+CREATE OR REPLACE VIEW gt_view_db.v01 AS SELECT id, name, salary FROM gt_view_db.t01;
+SELECT * FROM gt_view_db.v01 ORDER BY id;
+
+ALTER VIEW gt_view_db.v01 RENAME TO gt_view_db.v02;
+SHOW TABLES FROM gt_view_db;
+DROP VIEW gt_view_db.v02;
+SHOW TABLES FROM gt_view_db;
+
+DROP VIEW gt_view_db.nonexistent_view;
+
+DROP TABLE gt_view_db.t01;
+DROP SCHEMA gt_view_db;
diff --git a/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/lakehouse-iceberg/00014_view.txt b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/lakehouse-iceberg/00014_view.txt
new file mode 100644
index 0000000000..6a34bb4c5a
--- /dev/null
+++ b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/lakehouse-iceberg/00014_view.txt
@@ -0,0 +1,40 @@
+CREATE SCHEMA
+
+CREATE TABLE
+
+INSERT: 2 rows
+
+CREATE VIEW
+
+"t01"
+"v01"
+
+"2","bob"
+
+"CREATE VIEW gt_iceberg%.gt_view_db.v01 SECURITY DEFINER AS
+SELECT
+ id
+, name
+FROM
+ gt_view_db.t01
+WHERE (salary > 100)"
+
+CREATE VIEW
+
+"1","alice","100"
+"2","bob","200"
+
+RENAME VIEW
+
+"t01"
+"v02"
+
+DROP VIEW
+
+"t01"
+
+<QUERY_FAILED> View '%.gt_view_db.nonexistent_view' does not exist
+
+DROP TABLE
+
+DROP SCHEMA
diff --git a/trino-connector/trino-connector-440-445/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata440.java b/trino-connector/trino-connector-440-445/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata440.java
index 8734d52378..efa8764a00 100644
--- a/trino-connector/trino-connector-440-445/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata440.java
+++ b/trino-connector/trino-connector-440-445/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata440.java
@@ -27,6 +27,7 @@ import io.trino.spi.connector.ConnectorOutputTableHandle;
import io.trino.spi.connector.ConnectorSession;
import io.trino.spi.connector.ConnectorTableExecuteHandle;
import io.trino.spi.connector.ConnectorTableHandle;
+import io.trino.spi.connector.ConnectorViewDefinition;
import io.trino.spi.connector.RetryMode;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.statistics.ComputedStatistics;
@@ -125,4 +126,13 @@ public class GravitinoMetadata440 extends GravitinoMetadata {
internalMetadata.finishMerge(
session, GravitinoHandle.unWrap(mergeTableHandle), fragments, computedStatistics);
}
+
+ @Override
+ public void createView(
+ ConnectorSession session,
+ SchemaTableName viewName,
+ ConnectorViewDefinition definition,
+ boolean replace) {
+ createViewInternal(viewName, definition, Map.of(), replace);
+ }
}
diff --git a/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector446.java b/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector446.java
index f222edc471..1d906656b7 100644
--- a/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector446.java
+++ b/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector446.java
@@ -21,6 +21,8 @@ package org.apache.gravitino.trino.connector;
import io.trino.spi.connector.ConnectorMetadata;
import io.trino.spi.connector.ConnectorNodePartitioningProvider;
import io.trino.spi.connector.ConnectorSplitManager;
+import io.trino.spi.session.PropertyMetadata;
+import java.util.List;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadata;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadataAdapter;
@@ -52,4 +54,9 @@ public class GravitinoConnector446 extends GravitinoConnector {
catalogConnectorContext.getInternalConnector().getNodePartitioningProvider();
return new GravitinoNodePartitioningProvider446(nodePartitioningProvider);
}
+
+ @Override
+ public List<PropertyMetadata<?>> getViewProperties() {
+ return catalogConnectorContext.getViewProperties();
+ }
}
diff --git a/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata446.java b/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata446.java
index 07a871dcd3..7cad43e79a 100644
--- a/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata446.java
+++ b/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata446.java
@@ -27,6 +27,7 @@ import io.trino.spi.connector.ConnectorOutputTableHandle;
import io.trino.spi.connector.ConnectorSession;
import io.trino.spi.connector.ConnectorTableExecuteHandle;
import io.trino.spi.connector.ConnectorTableHandle;
+import io.trino.spi.connector.ConnectorViewDefinition;
import io.trino.spi.connector.RetryMode;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.statistics.ComputedStatistics;
@@ -125,4 +126,14 @@ public class GravitinoMetadata446 extends GravitinoMetadata {
internalMetadata.finishMerge(
session, GravitinoHandle.unWrap(mergeTableHandle), fragments, computedStatistics);
}
+
+ @Override
+ public void createView(
+ ConnectorSession session,
+ SchemaTableName viewName,
+ ConnectorViewDefinition definition,
+ Map<String, Object> viewProperties,
+ boolean replace) {
+ createViewInternal(viewName, definition, viewProperties, replace);
+ }
}
diff --git a/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector452.java b/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector452.java
index e2cbd08873..182c0e1a66 100644
--- a/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector452.java
+++ b/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector452.java
@@ -23,6 +23,8 @@ import io.trino.spi.connector.ConnectorMetadata;
import io.trino.spi.connector.ConnectorNodePartitioningProvider;
import io.trino.spi.connector.ConnectorPageSourceProviderFactory;
import io.trino.spi.connector.ConnectorSplitManager;
+import io.trino.spi.session.PropertyMetadata;
+import java.util.List;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadata;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadataAdapter;
@@ -64,4 +66,9 @@ public class GravitinoConnector452 extends GravitinoConnector {
new GravitinoDataSourceProvider(
internalConnectorPageSourceProviderFactory.createPageSourceProvider());
}
+
+ @Override
+ public List<PropertyMetadata<?>> getViewProperties() {
+ return catalogConnectorContext.getViewProperties();
+ }
}
diff --git a/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata452.java b/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata452.java
index 31fb9159eb..bc67deed83 100644
--- a/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata452.java
+++ b/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata452.java
@@ -27,6 +27,7 @@ import io.trino.spi.connector.ConnectorOutputTableHandle;
import io.trino.spi.connector.ConnectorSession;
import io.trino.spi.connector.ConnectorTableExecuteHandle;
import io.trino.spi.connector.ConnectorTableHandle;
+import io.trino.spi.connector.ConnectorViewDefinition;
import io.trino.spi.connector.RetryMode;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.statistics.ComputedStatistics;
@@ -131,4 +132,21 @@ public class GravitinoMetadata452 extends GravitinoMetadata {
fragments,
computedStatistics);
}
+
+ @Override
+ public void createView(
+ ConnectorSession session,
+ SchemaTableName viewName,
+ ConnectorViewDefinition definition,
+ Map<String, Object> viewProperties,
+ boolean replace) {
+ createViewInternal(viewName, definition, viewProperties, replace);
+ }
+
+ @Override
+ public boolean isView(ConnectorSession session, SchemaTableName viewName) {
+ return catalogConnectorMetadata
+ .getViewIfPresent(viewName.getSchemaName(), viewName.getTableName())
+ .isPresent();
+ }
}
diff --git a/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector469.java b/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector469.java
index eba983b738..4924ea74ac 100644
--- a/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector469.java
+++ b/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector469.java
@@ -23,6 +23,8 @@ import io.trino.spi.connector.ConnectorMetadata;
import io.trino.spi.connector.ConnectorNodePartitioningProvider;
import io.trino.spi.connector.ConnectorPageSourceProviderFactory;
import io.trino.spi.connector.ConnectorSplitManager;
+import io.trino.spi.session.PropertyMetadata;
+import java.util.List;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadata;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadataAdapter;
@@ -64,4 +66,9 @@ public class GravitinoConnector469 extends GravitinoConnector {
new GravitinoDataSourceProvider(
internalConnectorPageSourceProviderFactory.createPageSourceProvider());
}
+
+ @Override
+ public List<PropertyMetadata<?>> getViewProperties() {
+ return catalogConnectorContext.getViewProperties();
+ }
}
diff --git a/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata469.java b/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata469.java
index b95358e1de..8ce044358e 100644
--- a/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata469.java
+++ b/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata469.java
@@ -30,6 +30,7 @@ import io.trino.spi.connector.ConnectorOutputTableHandle;
import io.trino.spi.connector.ConnectorSession;
import io.trino.spi.connector.ConnectorTableExecuteHandle;
import io.trino.spi.connector.ConnectorTableHandle;
+import io.trino.spi.connector.ConnectorViewDefinition;
import io.trino.spi.connector.RetryMode;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.statistics.ComputedStatistics;
@@ -142,4 +143,21 @@ public class GravitinoMetadata469 extends GravitinoMetadata {
fragments,
computedStatistics);
}
+
+ @Override
+ public void createView(
+ ConnectorSession session,
+ SchemaTableName viewName,
+ ConnectorViewDefinition definition,
+ Map<String, Object> viewProperties,
+ boolean replace) {
+ createViewInternal(viewName, definition, viewProperties, replace);
+ }
+
+ @Override
+ public boolean isView(ConnectorSession session, SchemaTableName viewName) {
+ return catalogConnectorMetadata
+ .getViewIfPresent(viewName.getSchemaName(), viewName.getTableName())
+ .isPresent();
+ }
}
diff --git a/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector478.java b/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector478.java
index 2c069e1241..3a449644b8 100644
--- a/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector478.java
+++ b/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector478.java
@@ -23,6 +23,8 @@ import io.trino.spi.connector.ConnectorMetadata;
import io.trino.spi.connector.ConnectorNodePartitioningProvider;
import io.trino.spi.connector.ConnectorPageSourceProviderFactory;
import io.trino.spi.connector.ConnectorSplitManager;
+import io.trino.spi.session.PropertyMetadata;
+import java.util.List;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadata;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadataAdapter;
@@ -64,4 +66,9 @@ public class GravitinoConnector478 extends GravitinoConnector {
new GravitinoDataSourceProvider(
internalConnectorPageSourceProviderFactory.createPageSourceProvider());
}
+
+ @Override
+ public List<PropertyMetadata<?>> getViewProperties() {
+ return catalogConnectorContext.getViewProperties();
+ }
}
diff --git a/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata478.java b/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata478.java
index 261621cdfa..a47b4d4486 100644
--- a/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata478.java
+++ b/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata478.java
@@ -30,6 +30,7 @@ import io.trino.spi.connector.ConnectorOutputTableHandle;
import io.trino.spi.connector.ConnectorSession;
import io.trino.spi.connector.ConnectorTableExecuteHandle;
import io.trino.spi.connector.ConnectorTableHandle;
+import io.trino.spi.connector.ConnectorViewDefinition;
import io.trino.spi.connector.RetryMode;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.statistics.ComputedStatistics;
@@ -165,4 +166,21 @@ public class GravitinoMetadata478 extends GravitinoMetadata {
fragments,
computedStatistics);
}
+
+ @Override
+ public void createView(
+ ConnectorSession session,
+ SchemaTableName viewName,
+ ConnectorViewDefinition definition,
+ Map<String, Object> viewProperties,
+ boolean replace) {
+ createViewInternal(viewName, definition, viewProperties, replace);
+ }
+
+ @Override
+ public boolean isView(ConnectorSession session, SchemaTableName viewName) {
+ return catalogConnectorMetadata
+ .getViewIfPresent(viewName.getSchemaName(), viewName.getTableName())
+ .isPresent();
+ }
}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector.java
index 8f130f2974..7737e6606f 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector.java
@@ -86,10 +86,11 @@ public class GravitinoConnector implements Connector {
public GravitinoConnector(CatalogConnectorContext catalogConnectorContext) {
this.catalogIdentifier = catalogConnectorContext.getCatalog().geNameIdentifier();
this.catalogConnectorContext = catalogConnectorContext;
+ GravitinoConfig config = catalogConnectorContext.getConfig();
this.connectorMetadata =
- new CatalogConnectorMetadata(catalogConnectorContext.getMetalake(), this.catalogIdentifier);
+ new CatalogConnectorMetadata(
+ catalogConnectorContext.getMetalake(), this.catalogIdentifier, config);
- GravitinoConfig config = catalogConnectorContext.getConfig();
this.forwardUser = config.isForwardUser();
this.perUserSessionCache = forwardUser ? buildSessionCache(config) : null;
}
@@ -296,7 +297,9 @@ public class GravitinoConnector implements Connector {
GravitinoMetalake userMetalake =
userClient.loadMetalake(catalogConnectorContext.getMetalake().name());
return new UserSession(
- userClient, new CatalogConnectorMetadata(userMetalake, catalogIdentifier));
+ userClient,
+ new CatalogConnectorMetadata(
+ userMetalake, catalogIdentifier, catalogConnectorContext.getConfig()));
})
.metadata;
} catch (ExecutionException | UncheckedExecutionException e) {
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoErrorCode.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoErrorCode.java
index 9d48feb2d0..03779f1032 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoErrorCode.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoErrorCode.java
@@ -92,8 +92,12 @@ public enum GravitinoErrorCode implements ErrorCodeSupplier {
GRAVITINO_DUPLICATED_CATALOGS(24, EXTERNAL),
/** Expression error. */
GRAVITINO_EXPRESSION_ERROR(25, EXTERNAL),
+ /** View not exists. */
+ GRAVITINO_VIEW_NOT_EXISTS(26, EXTERNAL),
+ /** View already exists. */
+ GRAVITINO_VIEW_ALREADY_EXISTS(27, EXTERNAL),
/** Failed to connect to the Gravitino server or to the underlying source of a catalog. */
- GRAVITINO_CONNECTION_FAILED(26, EXTERNAL);
+ GRAVITINO_CONNECTION_FAILED(28, EXTERNAL);
// suppress ImmutableEnumChecker because ErrorCode is outside the project.
@SuppressWarnings("ImmutableEnumChecker")
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata.java
index ebc337e410..286290ca99 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata.java
@@ -43,6 +43,7 @@ import io.trino.spi.connector.ConnectorTableHandle;
import io.trino.spi.connector.ConnectorTableLayout;
import io.trino.spi.connector.ConnectorTableMetadata;
import io.trino.spi.connector.ConnectorTableVersion;
+import io.trino.spi.connector.ConnectorViewDefinition;
import io.trino.spi.connector.Constraint;
import io.trino.spi.connector.ConstraintApplicationResult;
import io.trino.spi.connector.JoinApplicationResult;
@@ -72,6 +73,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -91,6 +93,7 @@ import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadata;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadataAdapter;
import org.apache.gravitino.trino.connector.metadata.GravitinoSchema;
import org.apache.gravitino.trino.connector.metadata.GravitinoTable;
+import org.apache.gravitino.trino.connector.metadata.GravitinoView;
import org.apache.gravitino.trino.connector.util.TrinoRoutineSpecification;
/**
@@ -207,9 +210,10 @@ public abstract class GravitinoMetadata implements ConnectorMetadata {
ImmutableList.Builder<SchemaTableName> builder = ImmutableList.builder();
for (String schemaName : schemaNames) {
- List<String> tableNames = catalogConnectorMetadata.listTables(schemaName);
- for (String tableName : tableNames) {
- builder.add(new SchemaTableName(schemaName, tableName));
+ Set<String> names = new LinkedHashSet<>(catalogConnectorMetadata.listTables(schemaName));
+ names.addAll(catalogConnectorMetadata.listViews(schemaName));
+ for (String name : names) {
+ builder.add(new SchemaTableName(schemaName, name));
}
}
return builder.build();
@@ -846,6 +850,65 @@ public abstract class GravitinoMetadata implements ConnectorMetadata {
session, GravitinoHandle.unWrap(tableExecuteHandle), fragments, tableExecuteState);
}
+ @Override
+ public List<SchemaTableName> listViews(ConnectorSession session, Optional<String> schemaName) {
+ Set<String> schemaNames =
+ schemaName
+ .map(ImmutableSet::of)
+ .orElseGet(() -> ImmutableSet.copyOf(listSchemaNames(session)));
+
+ ImmutableList.Builder<SchemaTableName> builder = ImmutableList.builder();
+ for (String schema : schemaNames) {
+ List<String> viewNames = catalogConnectorMetadata.listViews(schema);
+ for (String viewName : viewNames) {
+ builder.add(new SchemaTableName(schema, viewName));
+ }
+ }
+ return builder.build();
+ }
+
+ @Override
+ public Optional<ConnectorViewDefinition> getView(
+ ConnectorSession session, SchemaTableName viewName) {
+ return catalogConnectorMetadata
+ .getViewIfPresent(viewName.getSchemaName(), viewName.getTableName())
+ .map(
+ view ->
+ metadataAdapter.getViewDefinition(
+ view,
+ catalogConnectorMetadata.getCatalogName(),
+ catalogConnectorMetadata.isSingleMetalakeMode()));
+ }
+
+ @Override
+ public void dropView(ConnectorSession session, SchemaTableName viewName) {
+ catalogConnectorMetadata.dropView(viewName.getSchemaName(), viewName.getTableName());
+ }
+
+ @Override
+ public void renameView(ConnectorSession session, SchemaTableName source, SchemaTableName target) {
+ catalogConnectorMetadata.renameView(source, target);
+ }
+
+ /**
+ * Shared helper used by the per-Trino-version {@code createView} overrides in this connector's
+ * version shim modules.
+ *
+ * @param viewName the schema-qualified view name
+ * @param definition the Trino view definition
+ * @param viewProperties the Trino view properties, merged as-is into the Gravitino view's generic
+ * properties
+ * @param replace whether to replace the view if it already exists
+ */
+ protected void createViewInternal(
+ SchemaTableName viewName,
+ ConnectorViewDefinition definition,
+ Map<String, Object> viewProperties,
+ boolean replace) {
+ GravitinoView view = metadataAdapter.createView(viewName, definition, viewProperties);
+ catalogConnectorMetadata.createView(view, replace);
+ }
+
protected SchemaTableName getTableName(ConnectorTableHandle tableHandle) {
return ((GravitinoTableHandle) tableHandle).toSchemaTableName();
}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorAdapter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorAdapter.java
index 79af26d0cf..3fe0144505 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorAdapter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorAdapter.java
@@ -72,4 +72,11 @@ public interface CatalogConnectorAdapter {
default List<PropertyMetadata<?>> getColumnProperties() {
return emptyList();
}
+
+ /**
+ * @return ViewProperties list that used to validate view properties.
+ */
+ default List<PropertyMetadata<?>> getViewProperties() {
+ return emptyList();
+ }
}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorContext.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorContext.java
index d529e07a61..d151e1240e 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorContext.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorContext.java
@@ -161,6 +161,15 @@ public class CatalogConnectorContext {
return adapter.getColumnProperties();
}
+ /**
+ * Returns the view properties associated with this context.
+ *
+ * @return the view properties
+ */
+ public List<PropertyMetadata<?>> getViewProperties() {
+ return adapter.getViewProperties();
+ }
+
/**
* Returns the Gravitino connector configuration.
*
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadata.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadata.java
index c618649b68..9d987c9d43 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadata.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadata.java
@@ -18,13 +18,17 @@
*/
package org.apache.gravitino.trino.connector.catalog;
+import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import io.airlift.log.Logger;
import io.trino.spi.TrinoException;
import io.trino.spi.connector.SchemaTableName;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
import javax.annotation.Nullable;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.gravitino.Catalog;
@@ -37,20 +41,29 @@ import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchFunctionException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
import org.apache.gravitino.exceptions.NoSuchTableException;
+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.function.Function;
import org.apache.gravitino.function.FunctionCatalog;
+import org.apache.gravitino.rel.Dialects;
+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.types.Type;
+import org.apache.gravitino.trino.connector.GravitinoConfig;
import org.apache.gravitino.trino.connector.GravitinoErrorCode;
import org.apache.gravitino.trino.connector.metadata.GravitinoColumn;
import org.apache.gravitino.trino.connector.metadata.GravitinoSchema;
import org.apache.gravitino.trino.connector.metadata.GravitinoTable;
+import org.apache.gravitino.trino.connector.metadata.GravitinoView;
/** This class implements Apache Gravitino metadata operators. */
public class CatalogConnectorMetadata {
@@ -61,6 +74,7 @@ public class CatalogConnectorMetadata {
private static final String SCHEMA_DOES_NOT_EXIST_MSG = "Schema does not exist";
private final String catalogName;
+ private final boolean singleMetalakeMode;
private final SupportsSchemas schemaCatalog;
private final TableCatalog tableCatalog;
@Nullable private final FunctionCatalog functionCatalog;
@@ -71,8 +85,11 @@ public class CatalogConnectorMetadata {
*
* @param metalake the Gravitino metalake
* @param catalogIdentifier the name of the catalog
+ * @param config the Gravitino Trino connector configuration
*/
- public CatalogConnectorMetadata(GravitinoMetalake metalake, NameIdentifier catalogIdentifier) {
+ public CatalogConnectorMetadata(
+ GravitinoMetalake metalake, NameIdentifier catalogIdentifier, GravitinoConfig config) {
+ this.singleMetalakeMode = !config.catalogNameWithMetalake();
try {
this.catalogName = catalogIdentifier.name();
Catalog catalog = metalake.loadCatalog(catalogName);
@@ -106,6 +123,24 @@ public class CatalogConnectorMetadata {
}
}
+ /**
+ * Retrieves the name of this Trino catalog.
+ *
+ * @return the catalog name
+ */
+ public String getCatalogName() {
+ return catalogName;
+ }
+
+ /**
+ * Indicates whether the Gravitino Trino connector is running in single-metalake mode.
+ *
+ * @return true if the connector is running in single-metalake mode
+ */
+ public boolean isSingleMetalakeMode() {
+ return singleMetalakeMode;
+ }
+
/**
* Lists the names of all schemas in the catalog.
*
@@ -516,4 +551,316 @@ public class CatalogConnectorMetadata {
throw GravitinoErrorCode.toTrinoException(e);
}
}
+
+ /**
+ * Checks whether the catalog supports view operations.
+ *
+ * @return true if the catalog supports view operations, false otherwise
+ */
+ public boolean supportsViews() {
+ return viewCatalog != null;
+ }
+
+ /**
+ * Retrieves the Gravitino view for the specified name, if it exists and has a Trino dialect SQL
+ * representation.
+ *
+ * @param schemaName the name of the schema
+ * @param viewName the name of the view
+ * @return an {@link Optional} containing the Gravitino view, or {@link Optional#empty()} if the
+ * view does not exist or has no Trino dialect SQL representation
+ */
+ public Optional<GravitinoView> getViewIfPresent(String schemaName, String viewName) {
+ if (!supportsViews()) {
+ return Optional.empty();
+ }
+ try {
+ View view = viewCatalog.loadView(NameIdentifier.of(schemaName, viewName));
+ GravitinoView gravitinoView = new GravitinoView(schemaName, viewName, view);
+ if (gravitinoView.getSql() == null) {
+ // The view exists but has no Trino dialect SQL representation, so it is not visible to
+ // Trino.
+ LOG.debug(
+ "View {}.{} in catalog {} has no Trino dialect SQL representation, hiding it from"
+ + " Trino",
+ schemaName,
+ viewName,
+ catalogName);
+ return Optional.empty();
+ }
+ return Optional.of(gravitinoView);
+ } catch (NoSuchViewException e) {
+ return Optional.empty();
+ } catch (UnsupportedOperationException e) {
+ LOG.debug(
+ "Catalog {} does not support loading view {}.{}", catalogName, schemaName, viewName, e);
+ return Optional.empty();
+ }
+ }
+
+ /**
+ * Retrieves the Gravitino view for the specified name.
+ *
+ * @param schemaName the name of the schema
+ * @param viewName the name of the view
+ * @return the Gravitino view
+ * @throws TrinoException if the view does not exist or has no Trino dialect SQL representation
+ */
+ public GravitinoView getView(String schemaName, String viewName) {
+ return getViewIfPresent(schemaName, viewName)
+ .orElseThrow(
+ () ->
+ new TrinoException(
+ GravitinoErrorCode.GRAVITINO_VIEW_NOT_EXISTS, "View does not exist"));
+ }
+
+ /**
+ * Lists the names of all views in the specified schema.
+ *
+ * @param schemaName the name of the schema
+ * @return a list of view names, or an empty list if the catalog does not support views or the
+ * schema does not exist
+ */
+ public List<String> listViews(String schemaName) {
+ if (!supportsViews()) {
+ return List.of();
+ }
+ try {
+ NameIdentifier[] views = viewCatalog.listViews(Namespace.of(schemaName));
+ return Arrays.stream(views)
+ .map(NameIdentifier::name)
+ .filter(viewName -> getViewIfPresent(schemaName, viewName).isPresent())
+ .toList();
+ } catch (UnsupportedOperationException e) {
+ LOG.debug(
+ "Catalog {} does not support listing views for schema {}", catalogName, schemaName, e);
+ return List.of();
+ } catch (NoSuchSchemaException e) {
+ // ConnectorMetadata.listViews() must return an empty list for a non-existent schema rather
+ // than fail, matching the contract Trino relies on for catalog-wide SHOW/information_schema
+ // scans.
+ return List.of();
+ }
+ }
+
+ /**
+ * Creates or replaces a view in the catalog.
+ *
+ * <p>Only views with a Trino dialect SQL representation are considered visible to Trino; if an
+ * entity with the same name already exists but has no Trino representation (e.g. a view created
+ * by another engine), it is never silently replaced.
+ *
+ * @param view the Gravitino view, with the Trino dialect SQL definition set
+ * @param replace whether to replace the view if it already exists
+ */
+ public void createView(GravitinoView view, boolean replace) {
+ if (!supportsViews()) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION, "Catalog does not support views");
+ }
+ Preconditions.checkArgument(
+ view.getSql() != null,
+ "View %s.%s has no Trino dialect SQL representation",
+ view.getSchemaName(),
+ view.getName());
+ NameIdentifier identifier = NameIdentifier.of(view.getSchemaName(), view.getName());
+ SQLRepresentation[] representations = {
+ SQLRepresentation.builder().withDialect(Dialects.TRINO).withSql(view.getSql()).build()
+ };
+ try {
+ boolean exists = viewCatalog.viewExists(identifier);
+ if (exists) {
+ View existingView = viewCatalog.loadView(identifier);
+ if (!existingView.sqlFor(Dialects.TRINO).isPresent()) {
+ // An entity with this name already exists but is not visible to Trino (e.g. a view
+ // created by another engine), so it must not be treated as replaceable.
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_VIEW_ALREADY_EXISTS, "View already exists");
+ }
+ if (!replace) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_VIEW_ALREADY_EXISTS, "View already exists");
+ }
+ if (hasNonTrinoRepresentation(existingView.representations())) {
+ // Trino cannot regenerate SQL for other engines' dialects, so replacing here would
+ // leave those representations referring to a schema/body that no longer matches.
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION,
+ "Cannot replace view "
+ + view.getSchemaName()
+ + "."
+ + view.getName()
+ + " because it has SQL representations in other dialects");
+ }
+ // Property changes must precede ReplaceView: Hive's ReplaceView handling encodes the new
+ // native Trino view payload (including the owner) from whatever properties have been
+ // applied so far in this array, so the owner update needs to land before ReplaceView reads
+ // it, not after.
+ List<ViewChange> changes = new ArrayList<>();
+ changes.addAll(computePropertyChanges(existingView.properties(), view.getProperties()));
+ if (existingView
+ .properties()
+ .containsKey(CatalogConnectorMetadataAdapter.RESERVED_VIEW_OWNER_PROPERTY)
+ && !view.getProperties()
+ .containsKey(CatalogConnectorMetadataAdapter.RESERVED_VIEW_OWNER_PROPERTY)) {
+ // computePropertyChanges never removes properties (see its Javadoc), but a replace that
+ // switches the view from SECURITY DEFINER back to SECURITY INVOKER must still clear the
+ // stale owner, or it would incorrectly keep reporting SECURITY DEFINER on reload.
+ changes.add(
+ ViewChange.removeProperty(
+ CatalogConnectorMetadataAdapter.RESERVED_VIEW_OWNER_PROPERTY));
+ }
+ changes.add(
+ ViewChange.replaceView(
+ view.getRawColumns(),
+ representations,
+ view.getDefaultCatalog(),
+ view.getDefaultSchema(),
+ view.getComment()));
+ viewCatalog.alterView(identifier, changes.toArray(new ViewChange[0]));
+ } else {
+ viewCatalog.createView(
+ identifier,
+ view.getComment(),
+ view.getRawColumns(),
+ representations,
+ view.getDefaultCatalog(),
+ view.getDefaultSchema(),
+ view.getProperties());
+ }
+ } catch (NoSuchSchemaException e) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_SCHEMA_NOT_EXISTS, SCHEMA_DOES_NOT_EXIST_MSG, e);
+ } catch (ViewAlreadyExistsException e) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_VIEW_ALREADY_EXISTS, "View already exists", e);
+ } catch (NoSuchViewException e) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_VIEW_NOT_EXISTS, "View does not exist", e);
+ } catch (UnsupportedOperationException e) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION,
+ "Catalog does not support this view operation",
+ e);
+ }
+ }
+
+ /**
+ * Drops a view from the catalog.
+ *
+ * <p>Only views with a Trino dialect SQL representation are considered visible to Trino; views
+ * created by other engines without one are treated as not existing, so this method never drops
+ * them.
+ *
+ * @param schemaName the name of the schema
+ * @param viewName the name of the view
+ */
+ public void dropView(String schemaName, String viewName) {
+ if (!supportsViews()) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION, "Catalog does not support views");
+ }
+ // Ensures the view is visible to Trino (exists and has a Trino dialect representation) before
+ // dropping it, so views created by other engines without a Trino representation are never
+ // silently dropped.
+ getView(schemaName, viewName);
+ boolean dropped;
+ try {
+ dropped = viewCatalog.dropView(NameIdentifier.of(schemaName, viewName));
+ } catch (UnsupportedOperationException e) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION,
+ "Catalog does not support this view operation",
+ e);
+ }
+ if (!dropped) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_OPERATION_FAILED,
+ "Failed to drop view " + schemaName + "." + viewName);
+ }
+ }
+
+ /**
+ * Renames a view in the catalog.
+ *
+ * <p>Only views with a Trino dialect SQL representation are considered visible to Trino; views
+ * created by other engines without one are treated as not existing, so this method never renames
+ * them.
+ *
+ * @param oldViewName the old name of the view
+ * @param newViewName the new name of the view
+ */
+ public void renameView(SchemaTableName oldViewName, SchemaTableName newViewName) {
+ if (!supportsViews()) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION, "Catalog does not support views");
+ }
+ if (!oldViewName.getSchemaName().equals(newViewName.getSchemaName())) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION, "Cannot rename view across schemas");
+ }
+ // Ensures the view is visible to Trino before renaming it, for the same reason as dropView.
+ getView(oldViewName.getSchemaName(), oldViewName.getTableName());
+ if (oldViewName.getTableName().equals(newViewName.getTableName())) {
+ return;
+ }
+ try {
+ viewCatalog.alterView(
+ NameIdentifier.of(oldViewName.getSchemaName(), oldViewName.getTableName()),
+ ViewChange.rename(newViewName.getTableName()));
+ } catch (NoSuchViewException e) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_VIEW_NOT_EXISTS, "View does not exist", e);
+ } catch (ViewAlreadyExistsException e) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_VIEW_ALREADY_EXISTS, "View already exists", e);
+ } catch (UnsupportedOperationException e) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION,
+ "Catalog does not support this view operation",
+ e);
+ }
+ }
+
+ /**
+ * Checks whether any of the given representations belongs to a dialect other than {@link
+ * Dialects#TRINO}.
+ *
+ * @param representations the representations to check
+ * @return true if a non-Trino dialect representation is present
+ */
+ private static boolean hasNonTrinoRepresentation(Representation[] representations) {
+ return Arrays.stream(representations)
+ .anyMatch(
+ representation ->
+ representation instanceof SQLRepresentation
+ && !Dialects.TRINO.equalsIgnoreCase(
+ ((SQLRepresentation) representation).dialect()));
+ }
+
+ /**
+ * Computes the {@link ViewChange} operations needed to apply {@code desired} on top of a view's
+ * current properties, so that {@code CREATE OR REPLACE VIEW ... WITH (...)} applies the new
+ * properties instead of silently leaving them unset ({@link ViewChange#replaceView} does not
+ * affect properties).
+ *
+ * <p>Only additions/updates are applied, never removals: {@code current} is the view's full
+ * underlying property map, which can include catalog-internal/reserved entries (e.g. Hive's
+ * {@code transient_lastDdlTime}) that this connector does not own and must not attempt to remove,
+ * so a key absent from {@code desired} is left untouched rather than being deleted.
+ *
+ * @param current the view's current properties
+ * @param desired the view's desired properties after the replace
+ * @return the property changes needed to apply {@code desired} onto {@code current}
+ */
+ private static List<ViewChange> computePropertyChanges(
+ Map<String, String> current, Map<String, String> desired) {
+ List<ViewChange> changes = new ArrayList<>();
+ for (Map.Entry<String, String> entry : desired.entrySet()) {
+ if (!Objects.equals(current.get(entry.getKey()), entry.getValue())) {
+ changes.add(ViewChange.setProperty(entry.getKey(), entry.getValue()));
+ }
+ }
+ return changes;
+ }
}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadataAdapter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadataAdapter.java
index d61f1d79e8..ec51848477 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadataAdapter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorMetadataAdapter.java
@@ -18,12 +18,18 @@
*/
package org.apache.gravitino.trino.connector.catalog;
+import com.google.common.base.Preconditions;
import io.airlift.log.Logger;
+import io.trino.spi.TrinoException;
import io.trino.spi.connector.ColumnMetadata;
import io.trino.spi.connector.ConnectorTableMetadata;
import io.trino.spi.connector.ConnectorTableProperties;
+import io.trino.spi.connector.ConnectorViewDefinition;
+import io.trino.spi.connector.ConnectorViewDefinition.ViewColumn;
import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.session.PropertyMetadata;
+import io.trino.spi.type.Type;
+import io.trino.spi.type.TypeManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -32,10 +38,13 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.NotImplementedException;
+import org.apache.gravitino.trino.connector.GravitinoErrorCode;
import org.apache.gravitino.trino.connector.metadata.GravitinoColumn;
import org.apache.gravitino.trino.connector.metadata.GravitinoSchema;
import org.apache.gravitino.trino.connector.metadata.GravitinoTable;
+import org.apache.gravitino.trino.connector.metadata.GravitinoView;
import org.apache.gravitino.trino.connector.util.GeneralDataTypeTransformer;
+import org.apache.gravitino.trino.connector.util.json.JsonCodec;
/**
* This interface is used to handle different parts of catalog metadata from different catalog
@@ -45,6 +54,29 @@ public class CatalogConnectorMetadataAdapter {
private static final Logger LOG = Logger.get(CatalogConnectorMetadataAdapter.class);
+ /**
+ * Reserved, namespaced Gravitino view property used to round-trip a Trino native view's {@code
+ * SECURITY DEFINER} owner through {@code createView}/{@code getViewDefinition}; it is stripped
+ * from and never settable via caller-supplied {@code viewProperties} ({@code WITH (...)}) so it
+ * cannot be spoofed. Its absence means the view is {@code SECURITY INVOKER}.
+ *
+ * <p>Package-visible so {@link CatalogConnectorMetadata#createView} can explicitly remove it on
+ * {@code CREATE OR REPLACE VIEW} when the new definition has no owner, since {@code
+ * computePropertyChanges} only ever adds/updates properties and never removes them.
+ */
+ static final String RESERVED_VIEW_OWNER_PROPERTY = "trino.internal.view.owner";
+
+ /**
+ * View output columns are never physically stored by the underlying catalog (only the view's SQL
+ * text is), so unlike table columns they must not be constrained by a catalog's physical storage
+ * restrictions (e.g. Iceberg rejecting {@code varchar(n)}, Hive rejecting {@code timestamp with
+ * time zone}); doing so has rejected otherwise-valid view output types, or accepted them on
+ * create only to reject the same type when reloading the view. Use the unrestricted base
+ * transformer for view columns instead of the catalog-specific {@link #dataTypeTransformer}.
+ */
+ private static final GeneralDataTypeTransformer VIEW_DATA_TYPE_TRANSFORMER =
+ new GeneralDataTypeTransformer();
+
/** The list of schema properties supported by this catalog connector. */
protected final List<PropertyMetadata<?>> schemaProperties;
@@ -147,6 +179,123 @@ public class CatalogConnectorMetadataAdapter {
return new GravitinoTable(schemaName, tableName, columns, comment, properties);
}
+ /**
+ * Transform Gravitino view metadata to Trino ConnectorViewDefinition. The view's {@code SECURITY
+ * DEFINER} owner, if any, is read back from the {@link #RESERVED_VIEW_OWNER_PROPERTY} reserved
+ * property (set by {@link #createView}); its absence means the view is {@code SECURITY INVOKER},
+ * matching Trino's own invariant that {@code runAsInvoker} and a present owner are mutually
+ * exclusive.
+ *
+ * <p>{@link ConnectorViewDefinition} requires a catalog to be present whenever a schema is
+ * present. Some catalogs (e.g. Iceberg) can store a default schema without a default catalog; in
+ * single-metalake mode the current Trino catalog is used as a fallback, since the schema is
+ * implicitly relative to it. In multi-metalake mode the bare Gravitino catalog name is not the
+ * name Trino actually resolves catalogs by, so this fallback cannot be applied and the view is
+ * rejected instead of being exposed with a wrong or unresolvable catalog.
+ *
+ * @param view the Gravitino view
+ * @param catalogName the name of the Trino catalog this view belongs to
+ * @param singleMetalakeMode whether the connector is running in single-metalake mode
+ * @return the Trino ConnectorViewDefinition
+ */
+ public ConnectorViewDefinition getViewDefinition(
+ GravitinoView view, String catalogName, boolean singleMetalakeMode) {
+ Preconditions.checkArgument(
+ view.getSql() != null,
+ "View %s.%s has no Trino dialect SQL representation",
+ view.getSchemaName(),
+ view.getName());
+ List<ViewColumn> columns =
+ view.getColumns().stream()
+ .map(
+ column ->
+ new ViewColumn(
+ column.getName(),
+ VIEW_DATA_TYPE_TRANSFORMER.getTrinoType(column.getType()).getTypeId(),
+ Optional.ofNullable(column.getComment())))
+ .collect(Collectors.toList());
+
+ String defaultCatalog = view.getDefaultCatalog();
+ if (defaultCatalog == null && view.getDefaultSchema() != null) {
+ if (!singleMetalakeMode) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION,
+ String.format(
+ "View %s.%s has a default schema without a default catalog, which is not "
+ + "supported in multi-metalake mode",
+ view.getSchemaName(), view.getName()));
+ }
+ defaultCatalog = catalogName;
+ }
+
+ String ownerProperty = view.getProperties().get(RESERVED_VIEW_OWNER_PROPERTY);
+ return new ConnectorViewDefinition(
+ view.getSql(),
+ Optional.ofNullable(defaultCatalog),
+ Optional.ofNullable(view.getDefaultSchema()),
+ columns,
+ Optional.ofNullable(view.getComment()),
+ Optional.ofNullable(ownerProperty),
+ ownerProperty == null,
+ List.of());
+ }
+
+ /**
+ * Transform Trino ConnectorViewDefinition to Gravitino view metadata. The {@code viewProperties}
+ * are merged as-is into the resulting view's generic properties; the caller cannot set {@link
+ * #RESERVED_VIEW_OWNER_PROPERTY} directly through them since it is reserved to round-trip the
+ * definition's own owner/{@code runAsInvoker}.
+ *
+ * <p>Gravitino views have no field to persist the view's {@code path} (the catalogs/schemas used
+ * to resolve unqualified function names, set via {@code SET PATH}), so a definition with a
+ * non-empty path is rejected rather than silently discarding it; loading a view therefore always
+ * returns an empty path, which is safe because no view with a non-empty path is ever stored.
+ *
+ * @param viewName the schema-qualified view name
+ * @param definition the Trino ConnectorViewDefinition
+ * @param viewProperties the Trino view properties
+ * @return the Gravitino view metadata
+ */
+ public GravitinoView createView(
+ SchemaTableName viewName,
+ ConnectorViewDefinition definition,
+ Map<String, Object> viewProperties) {
+ if (!definition.getPath().isEmpty()) {
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION,
+ "View " + viewName + " has a non-empty path (SET PATH), which Gravitino cannot persist");
+ }
+ TypeManager typeManager = JsonCodec.getTypeManager(getClass().getClassLoader());
+ List<GravitinoColumn> columns = new ArrayList<>();
+ List<ViewColumn> viewColumns = definition.getColumns();
+ for (int i = 0; i < viewColumns.size(); i++) {
+ ViewColumn column = viewColumns.get(i);
+ Type trinoType = typeManager.getType(column.getType());
+ columns.add(
+ new GravitinoColumn(
+ column.getName(),
+ VIEW_DATA_TYPE_TRANSFORMER.getGravitinoType(trinoType),
+ i,
+ column.getComment().orElse(null),
+ true,
+ false,
+ Map.of()));
+ }
+
+ Map<String, String> properties = new HashMap<>(toGravitinoTableProperties(viewProperties));
+ properties.remove(RESERVED_VIEW_OWNER_PROPERTY);
+ definition.getOwner().ifPresent(owner -> properties.put(RESERVED_VIEW_OWNER_PROPERTY, owner));
+ return new GravitinoView(
+ viewName.getSchemaName(),
+ viewName.getTableName(),
+ columns,
+ definition.getComment().orElse(null),
+ properties,
+ definition.getOriginalSql(),
+ definition.getCatalog().orElse(null),
+ definition.getSchema().orElse(null));
+ }
+
/**
* Removes specified keys from a map of properties.
*
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/metadata/GravitinoView.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/metadata/GravitinoView.java
new file mode 100644
index 0000000000..1deb10d1e0
--- /dev/null
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/metadata/GravitinoView.java
@@ -0,0 +1,204 @@
+/*
+ * 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.trino.connector.metadata;
+
+import com.google.common.collect.ImmutableList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import javax.annotation.Nullable;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Dialects;
+import org.apache.gravitino.rel.SQLRepresentation;
+import org.apache.gravitino.rel.View;
+
+/**
+ * Helps the Apache Gravitino connector access view metadata using the Trino dialect SQL
+ * representation from the Gravitino client.
+ */
+public class GravitinoView {
+
+ private final String schemaName;
+ private final String viewName;
+ private final List<GravitinoColumn> columns;
+ @Nullable private final String comment;
+ private final Map<String, String> properties;
+ @Nullable private final String sql;
+ @Nullable private final String defaultCatalog;
+ @Nullable private final String defaultSchema;
+
+ /**
+ * Constructs a new GravitinoView by unwrapping the {@link Dialects#TRINO} SQL representation from
+ * a Gravitino {@link View}.
+ *
+ * @param schemaName the schema name
+ * @param viewName the view name
+ * @param view the Gravitino view metadata
+ */
+ public GravitinoView(String schemaName, String viewName, View view) {
+ this.schemaName = schemaName;
+ this.viewName = viewName;
+
+ ImmutableList.Builder<GravitinoColumn> viewColumns = ImmutableList.builder();
+ for (int i = 0; i < view.columns().length; i++) {
+ viewColumns.add(new GravitinoColumn(view.columns()[i], i));
+ }
+ this.columns = viewColumns.build();
+ this.comment = view.comment();
+ this.properties = view.properties();
+
+ Optional<SQLRepresentation> trinoRepresentation = view.sqlFor(Dialects.TRINO);
+ this.sql = trinoRepresentation.map(SQLRepresentation::sql).orElse(null);
+ this.defaultCatalog = view.defaultCatalog();
+ this.defaultSchema = view.defaultSchema();
+ }
+
+ /**
+ * Constructs a new GravitinoView for the Trino-to-Gravitino creation direction.
+ *
+ * @param schemaName the schema name
+ * @param viewName the view name
+ * @param columns the view output columns
+ * @param comment the view comment
+ * @param properties the view properties
+ * @param sql the Trino dialect SQL definition of the view
+ * @param defaultCatalog the default catalog used to resolve unqualified identifiers referenced by
+ * the view definition, or {@code null} if not set
+ * @param defaultSchema the default schema used to resolve unqualified identifiers referenced by
+ * the view definition, or {@code null} if not set
+ */
+ public GravitinoView(
+ String schemaName,
+ String viewName,
+ List<GravitinoColumn> columns,
+ @Nullable String comment,
+ Map<String, String> properties,
+ String sql,
+ @Nullable String defaultCatalog,
+ @Nullable String defaultSchema) {
+ this.schemaName = schemaName;
+ this.viewName = viewName;
+ this.columns = columns;
+ this.comment = comment;
+ this.properties = properties;
+ this.sql = sql;
+ this.defaultCatalog = defaultCatalog;
+ this.defaultSchema = defaultSchema;
+ }
+
+ /**
+ * Retrieves the schema name of the view.
+ *
+ * @return the schema name of the view
+ */
+ public String getSchemaName() {
+ return schemaName;
+ }
+
+ /**
+ * Retrieves the name of the view.
+ *
+ * @return the name of the view
+ */
+ public String getName() {
+ return viewName;
+ }
+
+ /**
+ * Retrieves the columns of the view.
+ *
+ * @return the columns of the view
+ */
+ public List<GravitinoColumn> getColumns() {
+ return columns;
+ }
+
+ /**
+ * Retrieves the raw columns of the view.
+ *
+ * @return the raw columns of the view
+ */
+ public Column[] getRawColumns() {
+ Column[] gravitinoColumns = new Column[columns.size()];
+ for (int i = 0; i < columns.size(); i++) {
+ GravitinoColumn column = columns.get(i);
+ gravitinoColumns[i] =
+ Column.of(
+ column.getName(),
+ column.getType(),
+ column.getComment(),
+ column.isNullable(),
+ column.isAutoIncrement(),
+ column.getDefaultValue());
+ }
+ return gravitinoColumns;
+ }
+
+ /**
+ * Retrieves the comment of the view.
+ *
+ * @return the comment of the view, or {@code null} if not set
+ */
+ @Nullable
+ public String getComment() {
+ return comment;
+ }
+
+ /**
+ * Retrieves the properties of the view.
+ *
+ * @return the properties of the view
+ */
+ public Map<String, String> getProperties() {
+ return properties;
+ }
+
+ /**
+ * Retrieves the Trino dialect SQL definition of the view, or {@code null} if the view does not
+ * have a Trino dialect representation.
+ *
+ * @return the Trino dialect SQL, or {@code null}
+ */
+ @Nullable
+ public String getSql() {
+ return sql;
+ }
+
+ /**
+ * Retrieves the default catalog used to resolve unqualified identifiers referenced by the view
+ * definition, or {@code null} if not set.
+ *
+ * @return the default catalog, or {@code null}
+ */
+ @Nullable
+ public String getDefaultCatalog() {
+ return defaultCatalog;
+ }
+
+ /**
+ * Retrieves the default schema used to resolve unqualified identifiers referenced by the view
+ * definition, or {@code null} if not set.
+ *
+ * @return the default schema, or {@code null}
+ */
+ @Nullable
+ public String getDefaultSchema() {
+ return defaultSchema;
+ }
+}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/util/GeneralDataTypeTransformer.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/util/GeneralDataTypeTransformer.java
index 069d61f4e0..9d2988e147 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/util/GeneralDataTypeTransformer.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/util/GeneralDataTypeTransformer.java
@@ -43,8 +43,11 @@ import io.trino.spi.type.TypeOperators;
import io.trino.spi.type.UuidType;
import io.trino.spi.type.VarcharType;
import java.util.Arrays;
+import java.util.HashSet;
import java.util.List;
+import java.util.Locale;
import java.util.Optional;
+import java.util.Set;
import java.util.stream.Collectors;
import org.apache.gravitino.rel.types.Types;
import org.apache.gravitino.rel.types.Types.BooleanType;
@@ -177,14 +180,29 @@ public class GeneralDataTypeTransformer {
}
private StructType trinoRowTypeToGravitinoRowType(RowType rowType) {
- StructType.Field[] fields =
- rowType.getFields().stream()
- .map(
- field ->
- StructType.Field.nullableField(
- field.getName().get(), getGravitinoType(field.getType())))
- .toArray(StructType.Field[]::new);
-
+ List<Field> trinoFields = rowType.getFields();
+ Set<String> usedNamesLower = new HashSet<>();
+ for (Field trinoField : trinoFields) {
+ trinoField.getName().ifPresent(n -> usedNamesLower.add(n.toLowerCase(Locale.ROOT)));
+ }
+ StructType.Field[] fields = new StructType.Field[trinoFields.size()];
+ int anonymousSeq = 0;
+ for (int i = 0; i < trinoFields.size(); i++) {
+ Field trinoField = trinoFields.get(i);
+ String name;
+ if (trinoField.getName().isPresent()) {
+ name = trinoField.getName().get();
+ } else {
+ // Trino resolves row fields case-insensitively and allows anonymous ones (e.g.
+ // ROW(1, 'x') with no AS), so synthesize a name that cannot collide, case-insensitively,
+ // with an explicitly-named sibling field (e.g. ROW(1, 'x' AS "FIELD0")).
+ do {
+ name = "field" + anonymousSeq++;
+ } while (usedNamesLower.contains(name));
+ usedNamesLower.add(name);
+ }
+ fields[i] = StructType.Field.nullableField(name, getGravitinoType(trinoField.getType()));
+ }
return StructType.of(fields);
}
@@ -229,8 +247,11 @@ public class GeneralDataTypeTransformer {
} else if (typeClass == io.trino.spi.type.CharType.class) {
return Types.FixedCharType.of(((io.trino.spi.type.CharType) type).getLength());
} else if (typeClass == io.trino.spi.type.VarcharType.class) {
- return Types.VarCharType.of(
- ((io.trino.spi.type.VarcharType) type).getLength().orElse(Integer.MAX_VALUE - 1));
+ io.trino.spi.type.VarcharType varcharType = (io.trino.spi.type.VarcharType) type;
+ if (varcharType.getLength().isEmpty()) {
+ return Types.StringType.get();
+ }
+ return Types.VarCharType.of(varcharType.getLength().get());
} else if (typeClass == io.trino.spi.type.VarbinaryType.class) {
return Types.BinaryType.get();
} else if (typeClass == io.trino.spi.type.DateType.class) {
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/util/json/JsonCodec.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/util/json/JsonCodec.java
index 0be9dfe73f..71f6e5b890 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/util/json/JsonCodec.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/util/json/JsonCodec.java
@@ -65,6 +65,7 @@ public class JsonCodec {
private static final Logger LOG = Logger.get(JsonCodec.class);
private static volatile ObjectMapper mapper;
private static volatile Type jsonType;
+ private static volatile TypeManager typeManagerInstance;
private static ObjectMapper buildMapper(ClassLoader classLoader) {
try {
@@ -383,4 +384,32 @@ public class JsonCodec {
return jsonType;
}
}
+
+ /**
+ * Gets the singleton {@link TypeManager} instance, used to resolve a {@link
+ * io.trino.spi.type.TypeId} (an opaque, serializable type identifier) back into a full Trino
+ * {@link Type}.
+ *
+ * @param classLoader the class loader to use for loading Trino internal classes
+ * @return the {@link TypeManager} instance
+ */
+ public static TypeManager getTypeManager(ClassLoader classLoader) {
+ if (typeManagerInstance != null) {
+ return typeManagerInstance;
+ }
+
+ synchronized (JsonCodec.class) {
+ if (typeManagerInstance != null) {
+ return typeManagerInstance;
+ }
+ ClassLoader appClassLoader =
+ GravitinoConnectorPluginManager.instance(classLoader).getAppClassloader();
+ try {
+ typeManagerInstance = createTypeManager(appClassLoader);
+ } catch (Exception e) {
+ throw new TrinoException(GRAVITINO_RUNTIME_ERROR, "Failed to build TypeManager", e);
+ }
+ return typeManagerInstance;
+ }
+ }
}
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoMetadataView.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoMetadataView.java
new file mode 100644
index 0000000000..b00edbf392
--- /dev/null
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoMetadataView.java
@@ -0,0 +1,196 @@
+/*
+ * 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.trino.connector;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import io.trino.spi.connector.ConnectorMetadata;
+import io.trino.spi.connector.ConnectorSession;
+import io.trino.spi.connector.ConnectorViewDefinition;
+import io.trino.spi.connector.SchemaTableName;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadata;
+import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadataAdapter;
+import org.apache.gravitino.trino.connector.metadata.GravitinoView;
+import org.junit.jupiter.api.Test;
+
+public class TestGravitinoMetadataView {
+
+ @Test
+ public void testListViewsForSingleSchema() {
+ CatalogConnectorMetadata catalogMetadata = mock(CatalogConnectorMetadata.class);
+ when(catalogMetadata.listViews("test_schema")).thenReturn(List.of("v1", "v2"));
+
+ GravitinoMetadata metadata = createTestMetadata(catalogMetadata);
+ ConnectorSession session = mock(ConnectorSession.class);
+
+ List<SchemaTableName> views = metadata.listViews(session, Optional.of("test_schema"));
+ assertEquals(2, views.size());
+ assertTrue(views.contains(new SchemaTableName("test_schema", "v1")));
+ assertTrue(views.contains(new SchemaTableName("test_schema", "v2")));
+ }
+
+ @Test
+ public void testListViewsAcrossAllSchemas() {
+ CatalogConnectorMetadata catalogMetadata = mock(CatalogConnectorMetadata.class);
+ when(catalogMetadata.listSchemaNames()).thenReturn(List.of("s1"));
+ when(catalogMetadata.listViews("s1")).thenReturn(List.of("v1"));
+
+ GravitinoMetadata metadata = createTestMetadata(catalogMetadata);
+ ConnectorSession session = mock(ConnectorSession.class);
+
+ List<SchemaTableName> views = metadata.listViews(session, Optional.empty());
+ assertEquals(1, views.size());
+ assertEquals(new SchemaTableName("s1", "v1"), views.get(0));
+ }
+
+ @Test
+ public void testGetViewReturnsEmptyWhenNotPresent() {
+ CatalogConnectorMetadata catalogMetadata = mock(CatalogConnectorMetadata.class);
+ when(catalogMetadata.getViewIfPresent("s", "v1")).thenReturn(Optional.empty());
+
+ GravitinoMetadata metadata = createTestMetadata(catalogMetadata);
+ ConnectorSession session = mock(ConnectorSession.class);
+
+ Optional<ConnectorViewDefinition> definition =
+ metadata.getView(session, new SchemaTableName("s", "v1"));
+ assertTrue(definition.isEmpty());
+ }
+
+ @Test
+ public void testGetViewReturnsDefinitionWhenPresent() {
+ GravitinoView view =
+ new GravitinoView("s", "v1", List.of(), null, Map.of(), "select 1", null, null);
+ CatalogConnectorMetadata catalogMetadata = mock(CatalogConnectorMetadata.class);
+ when(catalogMetadata.getViewIfPresent("s", "v1")).thenReturn(Optional.of(view));
+ when(catalogMetadata.getCatalogName()).thenReturn("c");
+ when(catalogMetadata.isSingleMetalakeMode()).thenReturn(true);
+
+ ConnectorViewDefinition connectorViewDefinition = mock(ConnectorViewDefinition.class);
+ CatalogConnectorMetadataAdapter metadataAdapter = mock(CatalogConnectorMetadataAdapter.class);
+ when(metadataAdapter.getViewDefinition(view, "c", true)).thenReturn(connectorViewDefinition);
+
+ GravitinoMetadata metadata = createTestMetadata(catalogMetadata, metadataAdapter);
+ ConnectorSession session = mock(ConnectorSession.class);
+
+ Optional<ConnectorViewDefinition> definition =
+ metadata.getView(session, new SchemaTableName("s", "v1"));
+ assertTrue(definition.isPresent());
+ assertEquals(connectorViewDefinition, definition.get());
+ }
+
+ @Test
+ public void testDropViewDelegates() {
+ CatalogConnectorMetadata catalogMetadata = mock(CatalogConnectorMetadata.class);
+ GravitinoMetadata metadata = createTestMetadata(catalogMetadata);
+ ConnectorSession session = mock(ConnectorSession.class);
+
+ metadata.dropView(session, new SchemaTableName("s", "v1"));
+ verify(catalogMetadata, times(1)).dropView("s", "v1");
+ }
+
+ @Test
+ public void testRenameViewDelegates() {
+ CatalogConnectorMetadata catalogMetadata = mock(CatalogConnectorMetadata.class);
+ GravitinoMetadata metadata = createTestMetadata(catalogMetadata);
+ ConnectorSession session = mock(ConnectorSession.class);
+
+ SchemaTableName source = new SchemaTableName("s", "v1");
+ SchemaTableName target = new SchemaTableName("s", "v2");
+ metadata.renameView(session, source, target);
+ verify(catalogMetadata, times(1)).renameView(source, target);
+ }
+
+ @Test
+ public void testCreateViewInternalDelegatesToAdapterAndCatalogMetadata() {
+ CatalogConnectorMetadata catalogMetadata = mock(CatalogConnectorMetadata.class);
+ CatalogConnectorMetadataAdapter metadataAdapter = mock(CatalogConnectorMetadataAdapter.class);
+ ConnectorViewDefinition definition = mock(ConnectorViewDefinition.class);
+ SchemaTableName viewName = new SchemaTableName("s", "v1");
+ Map<String, Object> viewProperties = Map.of("k", "v");
+ GravitinoView view =
+ new GravitinoView("s", "v1", List.of(), null, Map.of(), "select 1", null, null);
+ when(metadataAdapter.createView(viewName, definition, viewProperties)).thenReturn(view);
+
+ ExposedGravitinoMetadata metadata = createTestMetadata(catalogMetadata, metadataAdapter);
+ metadata.exposedCreateViewInternal(viewName, definition, viewProperties, true);
+
+ verify(catalogMetadata, times(1)).createView(eq(view), eq(true));
+ }
+
+ @Test
+ public void testCreateViewInternalNotReplace() {
+ CatalogConnectorMetadata catalogMetadata = mock(CatalogConnectorMetadata.class);
+ CatalogConnectorMetadataAdapter metadataAdapter = mock(CatalogConnectorMetadataAdapter.class);
+ ConnectorViewDefinition definition = mock(ConnectorViewDefinition.class);
+ SchemaTableName viewName = new SchemaTableName("s", "v1");
+ GravitinoView view =
+ new GravitinoView("s", "v1", List.of(), null, Map.of(), "select 1", null, null);
+ when(metadataAdapter.createView(viewName, definition, Map.of())).thenReturn(view);
+
+ ExposedGravitinoMetadata metadata = createTestMetadata(catalogMetadata, metadataAdapter);
+ metadata.exposedCreateViewInternal(viewName, definition, Map.of(), false);
+
+ verify(catalogMetadata, times(1)).createView(eq(view), eq(false));
+ verify(catalogMetadata, never()).createView(any(), eq(true));
+ }
+
+ private ExposedGravitinoMetadata createTestMetadata(CatalogConnectorMetadata catalogMetadata) {
+ CatalogConnectorMetadataAdapter metadataAdapter = mock(CatalogConnectorMetadataAdapter.class);
+ return createTestMetadata(catalogMetadata, metadataAdapter);
+ }
+
+ private ExposedGravitinoMetadata createTestMetadata(
+ CatalogConnectorMetadata catalogMetadata, CatalogConnectorMetadataAdapter metadataAdapter) {
+ ConnectorMetadata internalMetadata = mock(ConnectorMetadata.class);
+ return new ExposedGravitinoMetadata(catalogMetadata, metadataAdapter, internalMetadata);
+ }
+
+ /**
+ * Test-only subclass that exposes the protected {@code createViewInternal} helper for direct
+ * verification, since {@link GravitinoMetadata} is abstract and the helper is only otherwise
+ * reachable through the per-Trino-version {@code createView} overrides.
+ */
+ private static final class ExposedGravitinoMetadata extends GravitinoMetadata {
+ ExposedGravitinoMetadata(
+ CatalogConnectorMetadata catalogConnectorMetadata,
+ CatalogConnectorMetadataAdapter metadataAdapter,
+ ConnectorMetadata internalMetadata) {
+ super(catalogConnectorMetadata, metadataAdapter, internalMetadata);
+ }
+
+ void exposedCreateViewInternal(
+ SchemaTableName viewName,
+ ConnectorViewDefinition definition,
+ Map<String, Object> viewProperties,
+ boolean replace) {
+ createViewInternal(viewName, definition, viewProperties, replace);
+ }
+ }
+}
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataAdapterView.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataAdapterView.java
new file mode 100644
index 0000000000..52833a11e5
--- /dev/null
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataAdapterView.java
@@ -0,0 +1,257 @@
+/*
+ * 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.trino.connector.catalog;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import io.trino.spi.TrinoException;
+import io.trino.spi.connector.CatalogSchemaName;
+import io.trino.spi.connector.ConnectorViewDefinition;
+import io.trino.spi.connector.ConnectorViewDefinition.ViewColumn;
+import io.trino.spi.connector.SchemaTableName;
+import io.trino.spi.type.TimestampWithTimeZoneType;
+import io.trino.spi.type.VarcharType;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.types.Types;
+import org.apache.gravitino.trino.connector.GravitinoErrorCode;
+import org.apache.gravitino.trino.connector.catalog.hive.HiveDataTypeTransformer;
+import org.apache.gravitino.trino.connector.catalog.iceberg.IcebergDataTypeTransformer;
+import org.apache.gravitino.trino.connector.metadata.GravitinoColumn;
+import org.apache.gravitino.trino.connector.metadata.GravitinoView;
+import org.apache.gravitino.trino.connector.util.GeneralDataTypeTransformer;
+import org.junit.jupiter.api.Test;
+
+public class TestCatalogConnectorMetadataAdapterView {
+
+ private final CatalogConnectorMetadataAdapter adapter =
+ new CatalogConnectorMetadataAdapter(
+ List.of(), List.of(), List.of(), new GeneralDataTypeTransformer());
+
+ @Test
+ public void testGetViewDefinitionNormalizesCatalogWhenSchemaPresentWithoutCatalog() {
+ GravitinoColumn column = new GravitinoColumn(Column.of("id", Types.StringType.get()), 0);
+ GravitinoView view =
+ new GravitinoView(
+ "s", "v1", List.of(column), null, Map.of(), "select 1", null, "default_schema");
+
+ ConnectorViewDefinition definition =
+ adapter.getViewDefinition(view, "current_catalog", /* singleMetalakeMode= */ true);
+
+ // Iceberg views may store a default schema without a default catalog; since Trino requires a
+ // catalog whenever a schema is present, the current Trino catalog is used.
+ assertEquals(Optional.of("current_catalog"), definition.getCatalog());
+ assertEquals(Optional.of("default_schema"), definition.getSchema());
+ }
+
+ @Test
+ public void testGetViewDefinitionRejectsSchemaWithoutCatalogInMultiMetalakeMode() {
+ GravitinoColumn column = new GravitinoColumn(Column.of("id", Types.StringType.get()), 0);
+ GravitinoView view =
+ new GravitinoView(
+ "s", "v1", List.of(column), null, Map.of(), "select 1", null, "default_schema");
+
+ TrinoException exception =
+ assertThrows(
+ TrinoException.class,
+ () ->
+ adapter.getViewDefinition(
+ view, "current_catalog", /* singleMetalakeMode= */ false));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION.toErrorCode(), exception.getErrorCode());
+ }
+
+ @Test
+ public void testGetViewDefinitionKeepsNullSchemaWhenCatalogAbsent() {
+ GravitinoColumn column = new GravitinoColumn(Column.of("id", Types.StringType.get()), 0);
+ GravitinoView view =
+ new GravitinoView("s", "v1", List.of(column), null, Map.of(), "select 1", null, null);
+
+ ConnectorViewDefinition definition =
+ adapter.getViewDefinition(view, "current_catalog", /* singleMetalakeMode= */ false);
+
+ assertEquals(Optional.empty(), definition.getCatalog());
+ assertEquals(Optional.empty(), definition.getSchema());
+ }
+
+ @Test
+ public void testGetViewDefinitionIsRunAsInvokerWhenNoOwnerProperty() {
+ GravitinoColumn column = new GravitinoColumn(Column.of("id", Types.StringType.get()), 0);
+ GravitinoView view =
+ new GravitinoView("s", "v1", List.of(column), null, Map.of(), "select 1", null, null);
+
+ ConnectorViewDefinition definition =
+ adapter.getViewDefinition(view, "current_catalog", /* singleMetalakeMode= */ true);
+
+ assertEquals(Optional.empty(), definition.getOwner());
+ assertEquals(true, definition.isRunAsInvoker());
+ }
+
+ @Test
+ public void testGetViewDefinitionIsRunAsDefinerWhenOwnerPropertyPresent() {
+ GravitinoColumn column = new GravitinoColumn(Column.of("id", Types.StringType.get()), 0);
+ GravitinoView view =
+ new GravitinoView(
+ "s",
+ "v1",
+ List.of(column),
+ null,
+ Map.of("trino.internal.view.owner", "alice"),
+ "select 1",
+ null,
+ null);
+
+ ConnectorViewDefinition definition =
+ adapter.getViewDefinition(view, "current_catalog", /* singleMetalakeMode= */ true);
+
+ assertEquals(Optional.of("alice"), definition.getOwner());
+ assertEquals(false, definition.isRunAsInvoker());
+ }
+
+ @Test
+ public void testCreateViewPersistsOwnerAsReservedProperty() {
+ ViewColumn column = new ViewColumn("id", VarcharType.VARCHAR.getTypeId(), Optional.empty());
+ ConnectorViewDefinition definition =
+ new ConnectorViewDefinition(
+ "select 1",
+ Optional.empty(),
+ Optional.empty(),
+ List.of(column),
+ Optional.empty(),
+ Optional.of("alice"),
+ false,
+ List.of());
+
+ GravitinoView view = adapter.createView(new SchemaTableName("s", "v1"), definition, Map.of());
+
+ assertEquals("alice", view.getProperties().get("trino.internal.view.owner"));
+ }
+
+ @Test
+ public void testCreateViewIgnoresCallerSuppliedOwnerProperty() {
+ ViewColumn column = new ViewColumn("id", VarcharType.VARCHAR.getTypeId(), Optional.empty());
+ ConnectorViewDefinition definition =
+ new ConnectorViewDefinition(
+ "select 1",
+ Optional.empty(),
+ Optional.empty(),
+ List.of(column),
+ Optional.empty(),
+ Optional.empty(),
+ true,
+ List.of());
+
+ GravitinoView view =
+ adapter.createView(
+ new SchemaTableName("s", "v1"),
+ definition,
+ Map.of("trino.internal.view.owner", "spoofed"));
+
+ assertEquals(null, view.getProperties().get("trino.internal.view.owner"));
+ }
+
+ @Test
+ public void testCreateViewRejectsNonEmptyPath() {
+ ViewColumn column = new ViewColumn("id", VarcharType.VARCHAR.getTypeId(), Optional.empty());
+ ConnectorViewDefinition definition =
+ new ConnectorViewDefinition(
+ "select 1",
+ Optional.empty(),
+ Optional.empty(),
+ List.of(column),
+ Optional.empty(),
+ Optional.empty(),
+ true,
+ List.of(new CatalogSchemaName("c", "s")));
+
+ TrinoException exception =
+ assertThrows(
+ TrinoException.class,
+ () -> adapter.createView(new SchemaTableName("s", "v1"), definition, Map.of()));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION.toErrorCode(), exception.getErrorCode());
+ }
+
+ @Test
+ public void testCreateViewAllowsIcebergVarcharWithLength() {
+ // A view's output columns are never physically stored, so Iceberg's "VARCHAR must have no
+ // length" table-column restriction must not apply to them (e.g. SELECT 'x' AS c naturally
+ // produces varchar(1)); IcebergDataTypeTransformer.getGravitinoType() would otherwise reject
+ // it.
+ CatalogConnectorMetadataAdapter icebergAdapter =
+ new CatalogConnectorMetadataAdapter(
+ List.of(), List.of(), List.of(), new IcebergDataTypeTransformer());
+ ViewColumn column =
+ new ViewColumn("c", VarcharType.createVarcharType(1).getTypeId(), Optional.empty());
+ ConnectorViewDefinition definition =
+ new ConnectorViewDefinition(
+ "select 'x' as c",
+ Optional.empty(),
+ Optional.empty(),
+ List.of(column),
+ Optional.empty(),
+ Optional.empty(),
+ true,
+ List.of());
+
+ GravitinoView view =
+ icebergAdapter.createView(new SchemaTableName("s", "v1"), definition, Map.of());
+
+ assertEquals(Types.VarCharType.of(1), view.getColumns().get(0).getType());
+ }
+
+ @Test
+ public void testViewRoundTripsHiveTimestampWithTimeZone() {
+ // A view's output columns are never physically stored, so Hive's "no timestamp with time
+ // zone" table-column restriction must not apply to them; HiveDataTypeTransformer previously
+ // accepted this type on create (falling through to the unrestricted base transformer) but
+ // rejected it on getTrinoType(), so the view could be created but never reloaded.
+ CatalogConnectorMetadataAdapter hiveAdapter =
+ new CatalogConnectorMetadataAdapter(
+ List.of(), List.of(), List.of(), new HiveDataTypeTransformer());
+ ViewColumn column =
+ new ViewColumn(
+ "c",
+ TimestampWithTimeZoneType.createTimestampWithTimeZoneType(3).getTypeId(),
+ Optional.empty());
+ ConnectorViewDefinition definition =
+ new ConnectorViewDefinition(
+ "select current_timestamp as c",
+ Optional.empty(),
+ Optional.empty(),
+ List.of(column),
+ Optional.empty(),
+ Optional.empty(),
+ true,
+ List.of());
+
+ GravitinoView view =
+ hiveAdapter.createView(new SchemaTableName("s", "v1"), definition, Map.of());
+ assertEquals(Types.TimestampType.withTimeZone(3), view.getColumns().get(0).getType());
+
+ ConnectorViewDefinition reloaded =
+ hiveAdapter.getViewDefinition(view, "current_catalog", /* singleMetalakeMode= */ true);
+ assertEquals(
+ TimestampWithTimeZoneType.createTimestampWithTimeZoneType(3).getTypeId(),
+ reloaded.getColumns().get(0).getType());
+ }
+}
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataErrors.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataErrors.java
index a5742203df..548b8af109 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataErrors.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataErrors.java
@@ -40,6 +40,7 @@ import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchTableException;
import org.apache.gravitino.exceptions.SchemaAlreadyExistsException;
import org.apache.gravitino.rel.TableCatalog;
+import org.apache.gravitino.trino.connector.GravitinoConfig;
import org.apache.gravitino.trino.connector.GravitinoErrorCode;
import org.apache.gravitino.trino.connector.metadata.GravitinoSchema;
import org.apache.gravitino.trino.connector.metadata.GravitinoTable;
@@ -58,7 +59,9 @@ public class TestCatalogConnectorMetadataErrors {
TrinoException e =
assertThrows(
TrinoException.class,
- () -> new CatalogConnectorMetadata(metalake, NameIdentifier.of("m", "c")));
+ () ->
+ new CatalogConnectorMetadata(
+ metalake, NameIdentifier.of("m", "c"), mock(GravitinoConfig.class)));
assertEquals(PERMISSION_DENIED.toErrorCode(), e.getErrorCode());
assertEquals(DENIED_MESSAGE, e.getMessage());
}
@@ -174,7 +177,9 @@ public class TestCatalogConnectorMetadataErrors {
TrinoException e =
assertThrows(
TrinoException.class,
- () -> new CatalogConnectorMetadata(metalake, NameIdentifier.of("m", "c")));
+ () ->
+ new CatalogConnectorMetadata(
+ metalake, NameIdentifier.of("m", "c"), mock(GravitinoConfig.class)));
assertEquals(CATALOG_UNAVAILABLE.toErrorCode(), e.getErrorCode());
assertEquals(message, e.getMessage());
}
@@ -218,6 +223,7 @@ public class TestCatalogConnectorMetadataErrors {
when(catalog.asSchemas()).thenReturn(schemas);
when(catalog.asTableCatalog()).thenReturn(tableCatalog);
when(catalog.asFunctionCatalog()).thenThrow(new UnsupportedOperationException("unsupported"));
- return new CatalogConnectorMetadata(metalake, NameIdentifier.of("m", "c"));
+ return new CatalogConnectorMetadata(
+ metalake, NameIdentifier.of("m", "c"), mock(GravitinoConfig.class));
}
}
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataFunction.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataFunction.java
index 2a9a20a075..1a74ee1afa 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataFunction.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataFunction.java
@@ -41,6 +41,7 @@ import org.apache.gravitino.function.FunctionCatalog;
import org.apache.gravitino.function.FunctionDefinition;
import org.apache.gravitino.function.FunctionType;
import org.apache.gravitino.rel.TableCatalog;
+import org.apache.gravitino.trino.connector.GravitinoConfig;
import org.junit.jupiter.api.Test;
public class TestCatalogConnectorMetadataFunction {
@@ -120,7 +121,8 @@ public class TestCatalogConnectorMetadataFunction {
when(catalog.asFunctionCatalog())
.thenThrow(new UnsupportedOperationException("Not supported"));
}
- return new CatalogConnectorMetadata(metalake, NameIdentifier.of("metalake", "test_catalog"));
+ return new CatalogConnectorMetadata(
+ metalake, NameIdentifier.of("metalake", "test_catalog"), mock(GravitinoConfig.class));
}
private CatalogConnectorMetadata createMetadataWithMockFunctionCatalog(
@@ -132,7 +134,8 @@ public class TestCatalogConnectorMetadataFunction {
when(catalog.asSchemas()).thenReturn(mock(SupportsSchemas.class));
when(catalog.asTableCatalog()).thenReturn(mock(TableCatalog.class));
when(catalog.asFunctionCatalog()).thenReturn(functionCatalog);
- return new CatalogConnectorMetadata(metalake, NameIdentifier.of("metalake", "test_catalog"));
+ return new CatalogConnectorMetadata(
+ metalake, NameIdentifier.of("metalake", "test_catalog"), mock(GravitinoConfig.class));
}
private Function createMockFunction(String name) {
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataView.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataView.java
index 8e11a67d30..896715d90c 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataView.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorMetadataView.java
@@ -25,35 +25,579 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import io.trino.spi.TrinoException;
+import io.trino.spi.connector.SchemaTableName;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
import org.apache.gravitino.SupportsSchemas;
import org.apache.gravitino.client.GravitinoMetalake;
import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.exceptions.NoSuchSchemaException;
+import org.apache.gravitino.exceptions.NoSuchViewException;
+import org.apache.gravitino.exceptions.ViewAlreadyExistsException;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Dialects;
+import org.apache.gravitino.rel.Representation;
+import org.apache.gravitino.rel.SQLRepresentation;
import org.apache.gravitino.rel.TableCatalog;
+import org.apache.gravitino.rel.View;
import org.apache.gravitino.rel.ViewCatalog;
+import org.apache.gravitino.rel.ViewChange;
+import org.apache.gravitino.trino.connector.GravitinoConfig;
+import org.apache.gravitino.trino.connector.GravitinoErrorCode;
+import org.apache.gravitino.trino.connector.metadata.GravitinoView;
import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
public class TestCatalogConnectorMetadataView {
+ @Test
+ public void testSupportsViewsWhenCatalogSupports() {
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(mock(ViewCatalog.class));
+ assertTrue(metadata.supportsViews());
+ }
+
+ @Test
+ public void testSupportsViewsWhenCatalogDoesNotSupport() {
+ CatalogConnectorMetadata metadata = createMetadataWithoutViewCatalog();
+ assertFalse(metadata.supportsViews());
+ }
+
+ @Test
+ public void testGetViewIfPresentReturnsEmptyWhenUnsupported() {
+ CatalogConnectorMetadata metadata = createMetadataWithoutViewCatalog();
+ assertTrue(metadata.getViewIfPresent("db", "v1").isEmpty());
+ }
+
+ @Test
+ public void testGetViewIfPresentReturnsEmptyWhenNotFound() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ when(viewCatalog.loadView(any())).thenThrow(new NoSuchViewException("not found"));
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ assertTrue(metadata.getViewIfPresent("db", "v1").isEmpty());
+ }
+
+ @Test
+ public void testGetViewIfPresentReturnsEmptyWhenViewOperationUnsupported() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ when(viewCatalog.loadView(any())).thenThrow(new UnsupportedOperationException("unsupported"));
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ assertTrue(metadata.getViewIfPresent("db", "v1").isEmpty());
+ }
+
+ @Test
+ public void testGetViewIfPresentReturnsEmptyWhenNoTrinoRepresentation() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View view = createView(Dialects.HIVE, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(view);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ assertTrue(metadata.getViewIfPresent("db", "v1").isEmpty());
+ }
+
+ @Test
+ public void testGetViewIfPresentReturnsValueWhenTrinoRepresentationExists() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View mockView = createView(Dialects.TRINO, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(mockView);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ Optional<GravitinoView> view = metadata.getViewIfPresent("db", "v1");
+ assertTrue(view.isPresent());
+ assertEquals("select 1", view.get().getSql());
+ }
+
+ @Test
+ public void testGetViewThrowsWhenNotPresent() {
+ CatalogConnectorMetadata metadata = createMetadataWithoutViewCatalog();
+ TrinoException exception =
+ assertThrows(TrinoException.class, () -> metadata.getView("db", "v1"));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_VIEW_NOT_EXISTS.toErrorCode(), exception.getErrorCode());
+ }
+
+ @Test
+ public void testListViewsReturnsEmptyWhenUnsupported() {
+ CatalogConnectorMetadata metadata = createMetadataWithoutViewCatalog();
+ assertTrue(metadata.listViews("db").isEmpty());
+ }
+
+ @Test
+ public void testListViewsReturnsEmptyWhenViewOperationUnsupported() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ when(viewCatalog.listViews(any(Namespace.class)))
+ .thenThrow(new UnsupportedOperationException("unsupported"));
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ assertTrue(metadata.listViews("db").isEmpty());
+ }
+
+ @Test
+ public void testListViewsReturnsEmptyWhenSchemaDoesNotExist() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ when(viewCatalog.listViews(any(Namespace.class)))
+ .thenThrow(new NoSuchSchemaException("schema does not exist"));
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ assertTrue(metadata.listViews("db").isEmpty());
+ }
+
+ @Test
+ public void testListViewsReturnsNames() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View view = createView(Dialects.TRINO, "select 1");
+ when(viewCatalog.listViews(any(Namespace.class)))
+ .thenReturn(new NameIdentifier[] {NameIdentifier.of("db", "v1")});
+ when(viewCatalog.loadView(NameIdentifier.of("db", "v1"))).thenReturn(view);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ List<String> views = metadata.listViews("db");
+ assertEquals(1, views.size());
+ assertEquals("v1", views.get(0));
+ }
+
+ @Test
+ public void testListViewsFiltersViewsWithoutTrinoRepresentation() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View trinoView = createView(Dialects.TRINO, "select 1");
+ View hiveView = createView(Dialects.HIVE, "select 2");
+ when(viewCatalog.listViews(any(Namespace.class)))
+ .thenReturn(
+ new NameIdentifier[] {NameIdentifier.of("db", "v1"), NameIdentifier.of("db", "v2")});
+ when(viewCatalog.loadView(NameIdentifier.of("db", "v1"))).thenReturn(trinoView);
+ when(viewCatalog.loadView(NameIdentifier.of("db", "v2"))).thenReturn(hiveView);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+
+ assertEquals(List.of("v1"), metadata.listViews("db"));
+ }
+
+ @Test
+ public void testCreateViewThrowsWhenUnsupported() {
+ CatalogConnectorMetadata metadata = createMetadataWithoutViewCatalog();
+ GravitinoView view = createGravitinoView("db", "v1", "select 1");
+ assertThrows(TrinoException.class, () -> metadata.createView(view, false));
+ }
+
+ @Test
+ public void testCreateViewThrowsWhenUnderlyingCatalogUnsupported() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ when(viewCatalog.viewExists(any())).thenReturn(false);
+ when(viewCatalog.createView(any(), any(), any(), any(), any(), any(), any()))
+ .thenThrow(new UnsupportedOperationException("createView is not supported"));
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ GravitinoView view = createGravitinoView("db", "v1", "select 1");
+ TrinoException exception =
+ assertThrows(TrinoException.class, () -> metadata.createView(view, false));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION.toErrorCode(), exception.getErrorCode());
+ }
+
+ @Test
+ public void testCreateViewRejectsViewWithoutTrinoSql() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ GravitinoView view = createGravitinoView("db", "v1", null);
+
+ assertThrows(IllegalArgumentException.class, () -> metadata.createView(view, false));
+ }
+
+ @Test
+ public void testCreateViewCreatesWhenNotExists() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ when(viewCatalog.viewExists(any())).thenReturn(false);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ GravitinoView view = createGravitinoView("db", "v1", "select 1");
+ metadata.createView(view, false);
+
+ verify(viewCatalog, times(1))
+ .createView(eq(NameIdentifier.of("db", "v1")), any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ public void testCreateViewThrowsWhenExistsAndNotReplace() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ when(viewCatalog.viewExists(any())).thenReturn(true);
+ View existingView = createView(Dialects.TRINO, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(existingView);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ GravitinoView view = createGravitinoView("db", "v1", "select 1");
+ TrinoException exception =
+ assertThrows(TrinoException.class, () -> metadata.createView(view, false));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_VIEW_ALREADY_EXISTS.toErrorCode(), exception.getErrorCode());
+ }
+
+ @Test
+ public void testCreateViewReplacesWhenExistsAndReplace() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ when(viewCatalog.viewExists(any())).thenReturn(true);
+ View existingView = createView(Dialects.TRINO, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(existingView);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ GravitinoView view = createGravitinoView("db", "v1", "select 1");
+ metadata.createView(view, true);
+
+ verify(viewCatalog, times(1))
+ .alterView(eq(NameIdentifier.of("db", "v1")), any(ViewChange.ReplaceView.class));
+ }
+
+ @Test
+ public void testCreateViewReplaceAppliesPropertyChanges() {
+ // ViewChange.replaceView() does not affect properties, so CREATE OR REPLACE VIEW must apply
+ // any property diff itself. Only additions/updates are applied - not removals - since the
+ // view's current properties can include catalog-internal/reserved entries (e.g. Hive's
+ // transient_lastDdlTime) that must never be targeted for removal.
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ when(viewCatalog.viewExists(any())).thenReturn(true);
+ View existingView = createView(Dialects.TRINO, "select 1");
+ when(existingView.properties())
+ .thenReturn(Map.of("keep", "same", "transient_lastDdlTime", "12345"));
+ when(viewCatalog.loadView(any())).thenReturn(existingView);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ GravitinoView view =
+ new GravitinoView(
+ "db",
+ "v1",
+ List.of(),
+ null,
+ Map.of("keep", "same", "add_me", "y"),
+ "select 1",
+ null,
+ null);
+ metadata.createView(view, true);
+
+ ArgumentCaptor<ViewChange[]> captor = ArgumentCaptor.forClass(ViewChange[].class);
+ verify(viewCatalog, times(1)).alterView(eq(NameIdentifier.of("db", "v1")), captor.capture());
+ List<ViewChange> changes = Arrays.asList(captor.getValue());
+
+ assertTrue(
+ changes.stream()
+ .anyMatch(
+ c ->
+ c instanceof ViewChange.SetProperty
+ && "add_me".equals(((ViewChange.SetProperty) c).getProperty())
+ && "y".equals(((ViewChange.SetProperty) c).getValue())));
+ assertTrue(changes.stream().noneMatch(c -> c instanceof ViewChange.RemoveProperty));
+ assertTrue(
+ changes.stream()
+ .noneMatch(
+ c ->
+ c instanceof ViewChange.SetProperty
+ && "keep".equals(((ViewChange.SetProperty) c).getProperty())));
+ }
+
+ @Test
+ public void testCreateViewReplaceRemovesStaleOwnerPropertyWhenSwitchingToInvoker() {
+ // computePropertyChanges never removes properties, but replacing a SECURITY DEFINER view with
+ // a SECURITY INVOKER one must still clear the stale owner, or SHOW CREATE VIEW would keep
+ // reporting SECURITY DEFINER after reload.
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ when(viewCatalog.viewExists(any())).thenReturn(true);
+ View existingView = createView(Dialects.TRINO, "select 1");
+ when(existingView.properties()).thenReturn(Map.of("trino.internal.view.owner", "alice"));
+ when(viewCatalog.loadView(any())).thenReturn(existingView);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ GravitinoView view = createGravitinoView("db", "v1", "select 1");
+ metadata.createView(view, true);
+
+ ArgumentCaptor<ViewChange[]> captor = ArgumentCaptor.forClass(ViewChange[].class);
+ verify(viewCatalog, times(1)).alterView(eq(NameIdentifier.of("db", "v1")), captor.capture());
+ List<ViewChange> changes = Arrays.asList(captor.getValue());
+
+ assertTrue(
+ changes.stream()
+ .anyMatch(
+ c ->
+ c instanceof ViewChange.RemoveProperty
+ && "trino.internal.view.owner"
+ .equals(((ViewChange.RemoveProperty) c).getProperty())));
+ }
+
+ @Test
+ public void testCreateViewReplaceRejectsWhenOtherDialectRepresentationsPresent() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ when(viewCatalog.viewExists(any())).thenReturn(true);
+ View existingView = mock(View.class);
+ when(existingView.columns()).thenReturn(new Column[0]);
+ Representation[] existingRepresentations = {
+ SQLRepresentation.builder().withDialect(Dialects.TRINO).withSql("select 1").build(),
+ SQLRepresentation.builder().withDialect(Dialects.HIVE).withSql("select 1 from t").build()
+ };
+ when(existingView.representations()).thenReturn(existingRepresentations);
+ when(existingView.sqlFor(Dialects.TRINO))
+ .thenReturn(Optional.of((SQLRepresentation) existingRepresentations[0]));
+ when(viewCatalog.loadView(any())).thenReturn(existingView);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ GravitinoView view = createGravitinoView("db", "v1", "select 2");
+ TrinoException exception =
+ assertThrows(TrinoException.class, () -> metadata.createView(view, true));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION.toErrorCode(), exception.getErrorCode());
+ verify(viewCatalog, never()).alterView(any(), any(ViewChange.ReplaceView.class));
+ }
+
+ @Test
+ public void testCreateViewThrowsWhenExistsWithoutTrinoRepresentationAndReplace() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ when(viewCatalog.viewExists(any())).thenReturn(true);
+ View existingView = createView(Dialects.HIVE, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(existingView);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ GravitinoView view = createGravitinoView("db", "v1", "select 1");
+ TrinoException exception =
+ assertThrows(TrinoException.class, () -> metadata.createView(view, true));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_VIEW_ALREADY_EXISTS.toErrorCode(), exception.getErrorCode());
+ verify(viewCatalog, never()).alterView(any(), any(ViewChange.ReplaceView.class));
+ }
+
+ @Test
+ public void testDropViewThrowsWhenUnsupported() {
+ CatalogConnectorMetadata metadata = createMetadataWithoutViewCatalog();
+ TrinoException exception =
+ assertThrows(TrinoException.class, () -> metadata.dropView("db", "v1"));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION.toErrorCode(), exception.getErrorCode());
+ }
+
+ @Test
+ public void testDropView() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View view = createView(Dialects.TRINO, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(view);
+ when(viewCatalog.dropView(any())).thenReturn(true);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ metadata.dropView("db", "v1");
+ verify(viewCatalog, times(1)).dropView(NameIdentifier.of("db", "v1"));
+ }
+
+ @Test
+ public void testDropViewThrowsWhenFailed() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View view = createView(Dialects.TRINO, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(view);
+ when(viewCatalog.dropView(any())).thenReturn(false);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ assertThrows(TrinoException.class, () -> metadata.dropView("db", "v1"));
+ }
+
+ @Test
+ public void testDropViewThrowsWhenUnderlyingCatalogUnsupported() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View view = createView(Dialects.TRINO, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(view);
+ when(viewCatalog.dropView(any()))
+ .thenThrow(new UnsupportedOperationException("dropView is not supported"));
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ TrinoException exception =
+ assertThrows(TrinoException.class, () -> metadata.dropView("db", "v1"));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION.toErrorCode(), exception.getErrorCode());
+ }
+
+ @Test
+ public void testDropViewThrowsWhenNoTrinoRepresentation() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View view = createView(Dialects.HIVE, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(view);
+
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+ TrinoException exception =
+ assertThrows(TrinoException.class, () -> metadata.dropView("db", "v1"));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_VIEW_NOT_EXISTS.toErrorCode(), exception.getErrorCode());
+ verify(viewCatalog, never()).dropView(any());
+ }
+
+ @Test
+ public void testRenameViewThrowsWhenUnsupported() {
+ CatalogConnectorMetadata metadata = createMetadataWithoutViewCatalog();
+ SchemaTableName oldName = new SchemaTableName("db", "v1");
+ SchemaTableName newName = new SchemaTableName("db", "v2");
+ TrinoException exception =
+ assertThrows(TrinoException.class, () -> metadata.renameView(oldName, newName));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION.toErrorCode(), exception.getErrorCode());
+ }
+
+ @Test
+ public void testRenameViewRejectsCrossSchema() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+
+ SchemaTableName oldName = new SchemaTableName("db1", "v1");
+ SchemaTableName newName = new SchemaTableName("db2", "v1");
+ assertThrows(TrinoException.class, () -> metadata.renameView(oldName, newName));
+ verify(viewCatalog, never()).alterView(any(), any());
+ }
+
+ @Test
+ public void testRenameViewSameNameIsNoop() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View view = createView(Dialects.TRINO, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(view);
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+
+ SchemaTableName oldName = new SchemaTableName("db", "v1");
+ SchemaTableName newName = new SchemaTableName("db", "v1");
+ metadata.renameView(oldName, newName);
+ verify(viewCatalog, never()).alterView(any(), any());
+ }
+
+ @Test
+ public void testRenameViewDelegatesToAlterView() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View view = createView(Dialects.TRINO, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(view);
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+
+ SchemaTableName oldName = new SchemaTableName("db", "v1");
+ SchemaTableName newName = new SchemaTableName("db", "v2");
+ metadata.renameView(oldName, newName);
+ verify(viewCatalog, times(1))
+ .alterView(eq(NameIdentifier.of("db", "v1")), any(ViewChange.RenameView.class));
+ }
+
+ @Test
+ public void testRenameViewThrowsWhenUnderlyingCatalogUnsupported() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View view = createView(Dialects.TRINO, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(view);
+ when(viewCatalog.alterView(any(), any(ViewChange.RenameView.class)))
+ .thenThrow(new UnsupportedOperationException("alterView is not supported"));
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+
+ SchemaTableName oldName = new SchemaTableName("db", "v1");
+ SchemaTableName newName = new SchemaTableName("db", "v2");
+ TrinoException exception =
+ assertThrows(TrinoException.class, () -> metadata.renameView(oldName, newName));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION.toErrorCode(), exception.getErrorCode());
+ }
+
+ @Test
+ public void testRenameViewThrowsWhenTargetAlreadyExists() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View view = createView(Dialects.TRINO, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(view);
+ when(viewCatalog.alterView(any(), any(ViewChange.RenameView.class)))
+ .thenThrow(new ViewAlreadyExistsException("View exists"));
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+
+ SchemaTableName oldName = new SchemaTableName("db", "v1");
+ SchemaTableName newName = new SchemaTableName("db", "v2");
+ TrinoException exception =
+ assertThrows(TrinoException.class, () -> metadata.renameView(oldName, newName));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_VIEW_ALREADY_EXISTS.toErrorCode(), exception.getErrorCode());
+ }
+
+ @Test
+ public void testRenameViewThrowsWhenNoTrinoRepresentation() {
+ ViewCatalog viewCatalog = mock(ViewCatalog.class);
+ View view = createView(Dialects.HIVE, "select 1");
+ when(viewCatalog.loadView(any())).thenReturn(view);
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
+
+ SchemaTableName oldName = new SchemaTableName("db", "v1");
+ SchemaTableName newName = new SchemaTableName("db", "v2");
+ TrinoException exception =
+ assertThrows(TrinoException.class, () -> metadata.renameView(oldName, newName));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_VIEW_NOT_EXISTS.toErrorCode(), exception.getErrorCode());
+ verify(viewCatalog, never()).alterView(any(), any());
+ }
+
+ private static View createView(String dialect, String sql) {
+ View view = mock(View.class);
+ when(view.columns()).thenReturn(new Column[0]);
+ when(view.comment()).thenReturn(null);
+ when(view.properties()).thenReturn(Collections.emptyMap());
+ Representation[] representations = {
+ SQLRepresentation.builder().withDialect(dialect).withSql(sql).build()
+ };
+ when(view.representations()).thenReturn(representations);
+ when(view.sqlFor(anyString()))
+ .thenAnswer(
+ invocation -> {
+ String requestedDialect = invocation.getArgument(0);
+ if (requestedDialect.equalsIgnoreCase(dialect)) {
+ return Optional.of(representations[0]);
+ }
+ return Optional.empty();
+ });
+ when(view.defaultCatalog()).thenReturn(null);
+ when(view.defaultSchema()).thenReturn(null);
+ return view;
+ }
+
+ private static GravitinoView createGravitinoView(String schemaName, String viewName, String sql) {
+ return new GravitinoView(schemaName, viewName, List.of(), null, Map.of(), sql, null, null);
+ }
+
+ private CatalogConnectorMetadata createMetadataWithViewCatalog(ViewCatalog viewCatalog) {
+ GravitinoMetalake metalake = mock(GravitinoMetalake.class);
+ Catalog catalog = mock(Catalog.class);
+ when(catalog.name()).thenReturn("test_catalog");
+ when(metalake.loadCatalog(anyString())).thenReturn(catalog);
+ when(catalog.asSchemas()).thenReturn(mock(SupportsSchemas.class));
+ when(catalog.asTableCatalog()).thenReturn(mock(TableCatalog.class));
+ when(catalog.asViewCatalog()).thenReturn(viewCatalog);
+ return new CatalogConnectorMetadata(
+ metalake, NameIdentifier.of("metalake", "test_catalog"), mock(GravitinoConfig.class));
+ }
+
+ private CatalogConnectorMetadata createMetadataWithoutViewCatalog() {
+ GravitinoMetalake metalake = mock(GravitinoMetalake.class);
+ Catalog catalog = mock(Catalog.class);
+ when(catalog.name()).thenReturn("test_catalog");
+ when(metalake.loadCatalog(anyString())).thenReturn(catalog);
+ when(catalog.asSchemas()).thenReturn(mock(SupportsSchemas.class));
+ when(catalog.asTableCatalog()).thenReturn(mock(TableCatalog.class));
+ when(catalog.asViewCatalog()).thenThrow(new UnsupportedOperationException("Not supported"));
+ return new CatalogConnectorMetadata(
+ metalake, NameIdentifier.of("metalake", "test_catalog"), mock(GravitinoConfig.class));
+ }
+
@Test
public void testViewExists() {
ViewCatalog viewCatalog = mock(ViewCatalog.class);
when(viewCatalog.viewExists(any())).thenReturn(true);
- assertTrue(createMetadata(viewCatalog).viewExists("s", "v"));
+ assertTrue(createMetadataWithViewCatalog(viewCatalog).viewExists("s", "v"));
verify(viewCatalog).viewExists(NameIdentifier.of("s", "v"));
}
@Test
public void testCatalogWithoutViewCatalogHasNoViews() {
- assertFalse(createMetadata(null).viewExists("s", "v"));
+ assertFalse(createMetadataWithoutViewCatalog().viewExists("s", "v"));
}
@Test
@@ -62,7 +606,7 @@ public class TestCatalogConnectorMetadataView {
when(viewCatalog.viewExists(any()))
.thenThrow(new UnsupportedOperationException("Views are not supported"));
- assertFalse(createMetadata(viewCatalog).viewExists("s", "v"));
+ assertFalse(createMetadataWithViewCatalog(viewCatalog).viewExists("s", "v"));
}
@Test
@@ -70,31 +614,16 @@ public class TestCatalogConnectorMetadataView {
ViewCatalog viewCatalog = mock(ViewCatalog.class);
when(viewCatalog.viewExists(any())).thenThrow(new NoSuchSchemaException("missing"));
- assertFalse(createMetadata(viewCatalog).viewExists("s", "v"));
+ assertFalse(createMetadataWithViewCatalog(viewCatalog).viewExists("s", "v"));
}
@Test
public void testViewExistsDeniedIsPermissionDenied() {
ViewCatalog viewCatalog = mock(ViewCatalog.class);
when(viewCatalog.viewExists(any())).thenThrow(new ForbiddenException("denied"));
- CatalogConnectorMetadata metadata = createMetadata(viewCatalog);
+ CatalogConnectorMetadata metadata = createMetadataWithViewCatalog(viewCatalog);
TrinoException e = assertThrows(TrinoException.class, () -> metadata.viewExists("s", "v"));
assertEquals(PERMISSION_DENIED.toErrorCode(), e.getErrorCode());
}
-
- private static CatalogConnectorMetadata createMetadata(ViewCatalog viewCatalog) {
- GravitinoMetalake metalake = mock(GravitinoMetalake.class);
- Catalog catalog = mock(Catalog.class);
- when(metalake.loadCatalog(anyString())).thenReturn(catalog);
- when(catalog.asSchemas()).thenReturn(mock(SupportsSchemas.class));
- when(catalog.asTableCatalog()).thenReturn(mock(TableCatalog.class));
- when(catalog.asFunctionCatalog()).thenThrow(new UnsupportedOperationException("unsupported"));
- if (viewCatalog == null) {
- when(catalog.asViewCatalog()).thenThrow(new UnsupportedOperationException("unsupported"));
- } else {
- when(catalog.asViewCatalog()).thenReturn(viewCatalog);
- }
- return new CatalogConnectorMetadata(metalake, NameIdentifier.of("m", "c"));
- }
}
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/util/TestDataTypeTransformer.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/util/TestDataTypeTransformer.java
index a073c2273a..ca796b90c8 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/util/TestDataTypeTransformer.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/util/TestDataTypeTransformer.java
@@ -114,6 +114,42 @@ public class TestDataTypeTransformer {
Types.StructType.Field.nullableField("a", Types.IntegerType.get()),
Types.StructType.Field.nullableField("b", Types.VarCharType.of(10))));
+ // Trino allows anonymous row fields (e.g. ROW(1, 'x') with no AS), but Gravitino's
+ // StructType.Field requires a name; it must be synthesized instead of throwing.
+ Assertions.assertEquals(
+ dataTypeTransformer.getGravitinoType(
+ RowType.from(
+ ImmutableList.of(
+ new Field(Optional.empty(), IntegerType.INTEGER),
+ new Field(Optional.of("b"), VarcharType.createVarcharType(10))))),
+ Types.StructType.of(
+ Types.StructType.Field.nullableField("field0", Types.IntegerType.get()),
+ Types.StructType.Field.nullableField("b", Types.VarCharType.of(10))));
+
+ // The synthesized name for an anonymous field must not collide with a sibling field that is
+ // explicitly named "field0".
+ Assertions.assertEquals(
+ dataTypeTransformer.getGravitinoType(
+ RowType.from(
+ ImmutableList.of(
+ new Field(Optional.empty(), IntegerType.INTEGER),
+ new Field(Optional.of("field0"), VarcharType.createVarcharType(10))))),
+ Types.StructType.of(
+ Types.StructType.Field.nullableField("field1", Types.IntegerType.get()),
+ Types.StructType.Field.nullableField("field0", Types.VarCharType.of(10))));
+
+ // Trino resolves row fields case-insensitively, so the collision check against an
+ // explicitly-named sibling must also be case-insensitive (e.g. a sibling named "FIELD0").
+ Assertions.assertEquals(
+ dataTypeTransformer.getGravitinoType(
+ RowType.from(
+ ImmutableList.of(
+ new Field(Optional.empty(), IntegerType.INTEGER),
+ new Field(Optional.of("FIELD0"), VarcharType.createVarcharType(10))))),
+ Types.StructType.of(
+ Types.StructType.Field.nullableField("field1", Types.IntegerType.get()),
+ Types.StructType.Field.nullableField("FIELD0", Types.VarCharType.of(10))));
+
Assertions.assertEquals(
dataTypeTransformer.getGravitinoType(UuidType.UUID), Types.UUIDType.get());