ldsantos0911 commented on code in PR #13979:
URL: https://github.com/apache/iceberg/pull/13979#discussion_r2934169257


##########
spark/v4.1/spark-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveViews.scala:
##########
@@ -161,17 +220,29 @@ case class ResolveViews(spark: SparkSession) extends 
Rule[LogicalPlan] with Look
    */
   private def qualifyTableIdentifiers(
       child: LogicalPlan,
-      catalogAndNamespace: Seq[String]): LogicalPlan =
+      catalogAndNamespace: Seq[String],
+      viewChain: Option[Seq[Seq[String]]]): LogicalPlan = {
     child transform {
-      case u @ UnresolvedRelation(Seq(table), _, _) =>
-        u.copy(multipartIdentifier = catalogAndNamespace :+ table)
-      case u @ UnresolvedRelation(parts, _, _) if !isCatalog(parts.head) =>
-        u.copy(multipartIdentifier = catalogAndNamespace.head +: parts)
+      case u @ UnresolvedRelation(parts, options, isStreaming) =>
+        val qualifiedTableId = parts match {
+          case Seq(table) => catalogAndNamespace :+ table
+          case _ if !isCatalog(parts.head) => catalogAndNamespace.head +: parts
+          case _ => parts // fallback for other cases
+        }
+
+        viewChain match {
+          case Some(chain) =>
+            UnResolvedRelationFromView(qualifiedTableId, chain, options, 
isStreaming)
+          case _ =>

Review Comment:
   This should be impossible, shouldn't it? Would it make sense to throw an 
error in this case?



##########
spark/v4.1/spark-extensions/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/views/UnResolvedRelationFromView.scala:
##########
@@ -0,0 +1,67 @@
+/*
+ * 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.spark.sql.catalyst.plans.logical.views
+
+import org.apache.spark.sql.catalyst.expressions.Attribute
+import org.apache.spark.sql.catalyst.plans.logical.LeafNode
+import org.apache.spark.sql.catalyst.util.quoteIfNeeded
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/**
+ * Represents an unresolved table/relation that was referenced from within a 
view.
+ * This node carries both the table identifier and the chain of view 
identifiers that
+ * referenced it, enabling view-aware authorization and security mechanisms.
+ *
+ * This allows catalogs to implement different security models such as:
+ * - Definer rights: Use view creator's permissions to access the underlying 
table
+ * - Invoker rights: Use current user's permissions to access the underlying 
table
+ *
+ * @param tableMultipartIdentifier The multipart identifier for the target 
table
+ * @param viewChain The chain of view identifiers that reference this table, 
ordered from
+ *                  outermost view first to innermost view last. Each element 
is a multipart
+ *                  identifier (Seq[String]).
+ * @param options Options passed to the table (similar to UnresolvedRelation)
+ * @param isStreaming Whether this is a streaming relation
+ */
+case class UnResolvedRelationFromView(
+    tableMultipartIdentifier: Seq[String],
+    viewChain: Seq[Seq[String]],
+    options: CaseInsensitiveStringMap = CaseInsensitiveStringMap.empty(),
+    override val isStreaming: Boolean = false)
+    extends LeafNode {
+
+  override def output: Seq[Attribute] = Nil
+
+  override lazy val resolved = false
+
+  def tableName: String = 
tableMultipartIdentifier.map(quoteIfNeeded).mkString(".")
+
+  def viewName: String = 
viewChain.map(_.map(quoteIfNeeded).mkString(".")).mkString(" -> ")
+
+  override def simpleString(maxFields: Int): String = {
+    s"'UnresolvedRelationFromView [table=$tableName, views=$viewName, " +
+      s"${if (isStreaming) "streaming=true, " else ""}options=$options]"
+  }
+
+  override def toString: String = {
+    val chainStr = viewChain.map(parts => s"[${parts.mkString(", 
")}]").mkString(", ")
+    s"UnresolvedRelationFromView([${tableMultipartIdentifier.mkString(", ")}], 
" +

Review Comment:
   nit: The capitalization is mismatched between the string representation and 
the class name. My vote would be to align with the capitalization in this 
method.



##########
core/src/main/java/org/apache/iceberg/rest/RESTSessionCatalog.java:
##########
@@ -436,21 +437,108 @@ private LoadTableResponse loadInternal(
       SnapshotMode mode,
       Map<String, String> headers,
       Consumer<Map<String, String>> responseHeaders) {
+    return loadInternal(context, identifier, mode, Map.of(), headers, 
responseHeaders);
+  }
+
+  private LoadTableResponse loadInternal(
+      SessionContext context,
+      TableIdentifier identifier,
+      SnapshotMode mode,
+      Map<String, Object> loadingContext,
+      Map<String, String> headers,
+      Consumer<Map<String, String>> responseHeaders) {
     Endpoint.check(endpoints, Endpoint.V1_LOAD_TABLE);
     AuthSession contextualSession = authManager.contextualSession(context, 
catalogAuth);
     return client
         .withAuthSession(contextualSession)
         .get(
             paths.table(identifier),
-            snapshotModeToParam(mode),
+            paramsForLoadTable(mode, loadingContext),
             LoadTableResponse.class,
             headers,
             ErrorHandlers.tableErrorHandler(),
             responseHeaders);
   }
 
+  // Visible for testing
+  Map<String, String> paramsForLoadTable(SnapshotMode mode, Map<String, 
Object> loadingContext) {
+    return referencedByToQueryParam(snapshotModeToParam(mode), loadingContext);

Review Comment:
   I feel like this presents an opportunity to create an easier path forward 
for extending the catalog interface further via query params. Would you be open 
to entertaining wrapping this logic in a functional interface called something 
like a `LoadingContextHandler` which could be supplied at the class level or 
via config? This PR could introduce an implementation like 
`ReferencedByContextHandler` which performs the functionality in 
`referencedByToQueryParam` then the predefined handler can be used here.  



##########
spark/v4.1/spark-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveViews.scala:
##########
@@ -62,6 +68,48 @@ case class ResolveViews(spark: SparkSession) extends 
Rule[LogicalPlan] with Look
         .map(_ => ResolvedV2View(catalog.asViewCatalog, ident))
         .getOrElse(u)
 
+    case u @ UnResolvedRelationFromView(
+          tableParts @ CatalogAndIdentifier(catalog, tableIdent),
+          viewChain,
+          options,
+          isStreaming) =>
+      // Build List<TableIdentifier> from the view chain.
+      // Each chain element is [catalog, ns1, ns2, ..., viewName] — skip the 
catalog (first element)
+      // since TableIdentifier only contains namespace + name.
+      val viewIdentifiers = viewChain.map { parts =>
+        val nsParts = parts.drop(1).init // drop catalog, then drop name
+        val ns = Namespace.of(nsParts: _*)
+        TableIdentifier.of(ns, parts.last)
+      }
+      val context = new java.util.HashMap[String, Object]()
+      context.put(
+        org.apache.iceberg.catalog.ContextAwareCatalog.VIEW_IDENTIFIER_KEY,
+        viewIdentifiers.asJava)
+      try {
+        catalog match {
+          case contextAwareCatalog: ContextAwareCatalog =>
+            val table = contextAwareCatalog.loadTable(tableIdent, context)
+            DataSourceV2Relation.create(table, Some(catalog), 
Some(tableIdent), options)
+          case catalog if 
catalog.asTableCatalog.isInstanceOf[ContextAwareCatalog] =>
+            val table =
+              catalog.asTableCatalog
+                .asInstanceOf[ContextAwareCatalog]
+                .loadTable(tableIdent, context)
+            DataSourceV2Relation.create(table, Some(catalog), 
Some(tableIdent), options)
+          case _ =>
+            val table = catalog.asTableCatalog.loadTable(tableIdent)
+            DataSourceV2Relation.create(table, Some(catalog), 
Some(tableIdent), options)
+        }
+      } catch {
+        case _: NoSuchTableException =>
+          // The target might be a view, not a table. Try loading as a view
+          // and recursively resolve with the accumulated chain.
+          ViewUtil
+            .loadView(catalog, tableIdent, context)
+            .map(view => createViewRelation(tableParts, view, Some(viewChain)))
+            .getOrElse(UnresolvedRelation(tableParts, options, isStreaming))

Review Comment:
   Similar to below, do we want to be falling back to the default resolution 
path, or would it make sense to throw an error if the expected view chain is 
broken somehow?



##########
spark/v4.1/spark-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveViews.scala:
##########
@@ -62,6 +68,48 @@ case class ResolveViews(spark: SparkSession) extends 
Rule[LogicalPlan] with Look
         .map(_ => ResolvedV2View(catalog.asViewCatalog, ident))
         .getOrElse(u)
 
+    case u @ UnResolvedRelationFromView(
+          tableParts @ CatalogAndIdentifier(catalog, tableIdent),
+          viewChain,
+          options,
+          isStreaming) =>
+      // Build List<TableIdentifier> from the view chain.
+      // Each chain element is [catalog, ns1, ns2, ..., viewName] — skip the 
catalog (first element)
+      // since TableIdentifier only contains namespace + name.
+      val viewIdentifiers = viewChain.map { parts =>
+        val nsParts = parts.drop(1).init // drop catalog, then drop name
+        val ns = Namespace.of(nsParts: _*)
+        TableIdentifier.of(ns, parts.last)
+      }
+      val context = new java.util.HashMap[String, Object]()
+      context.put(
+        org.apache.iceberg.catalog.ContextAwareCatalog.VIEW_IDENTIFIER_KEY,
+        viewIdentifiers.asJava)
+      try {
+        catalog match {
+          case contextAwareCatalog: ContextAwareCatalog =>

Review Comment:
   I believe this flow may be missing handling of time travel/versioning.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to