huaxingao commented on code in PR #19001:
URL: https://github.com/apache/iceberg/pull/19001#discussion_r4672796324


##########
spark/v4.1/spark-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveViews.scala:
##########
@@ -104,34 +121,136 @@ case class ResolveViews(spark: SparkSession) extends 
Rule[LogicalPlan] with Look
     }
   }
 
-  private def createViewRelation(nameParts: Seq[String], view: View): 
LogicalPlan = {
-    val parsed = parseViewText(nameParts.quoted, view.query)
+  private def resolveRelationFromView(
+      relation: UnResolvedRelationFromView,
+      catalog: CatalogPlugin,
+      ident: Identifier): LogicalPlan = {
+    val parts = relation.tableMultipartIdentifier
+    val referencedBy = ViewUtil.buildReferencedByChain(relation.viewChain, 
catalog.name())
+    catalog match {
+      case contextual: TableCatalog with SparkSupportsLoadContext if 
!relation.isStreaming =>
+        val context = LoadContext.builder().referencedBy(referencedBy).build()
+        val timeTravelSpec = TimeTravelSpec.create(
+          relation.timeTravelTimestamp,
+          relation.timeTravelVersion,
+          conf.sessionLocalTimeZone)
+        try {
+          ViewUtil.loadTable(contextual, ident, context, timeTravelSpec) match 
{
+            case _: V1Table =>
+              toUnresolvedRelation(relation)
+            case table =>
+              val relationCatalog = if (timeTravelSpec.isEmpty) {
+                LoadContextTableCatalog(contextual, context)
+              } else {
+                contextual
+              }
+              SubqueryAlias(
+                catalog.name +: ident.asMultipartIdentifier,
+                DataSourceV2Relation.create(
+                  table,
+                  Some(relationCatalog),
+                  Some(ident),
+                  relation.options,
+                  timeTravelSpec))
+          }
+        } catch {
+          case _: NoSuchTableException =>
+            ViewUtil
+              .loadView(catalog, ident, context)
+              .map(createViewRelation(parts, catalog, ident, _, 
relation.viewChain))
+              .getOrElse(toUnresolvedRelation(relation))
+        }
+
+      case _ =>
+        toUnresolvedRelation(relation)
+    }
+  }
+
+  private def toUnresolvedRelation(relation: UnResolvedRelationFromView): 
LogicalPlan = {
+    val unresolved =
+      UnresolvedRelation(relation.tableMultipartIdentifier, relation.options, 
relation.isStreaming)
+    if (relation.timeTravelVersion.isEmpty && 
relation.timeTravelTimestamp.isEmpty) {
+      unresolved
+    } else {
+      RelationTimeTravel(unresolved, relation.timeTravelTimestamp, 
relation.timeTravelVersion)
+    }
+  }
+
+  private def createViewRelation(
+      nameParts: Seq[String],
+      catalog: CatalogPlugin,
+      ident: Identifier,
+      view: View,
+      existingChain: Seq[Seq[String]] = Seq.empty): LogicalPlan = {
+    // Session settings are read before switching to the view's captured SQL 
configs, which
+    // don't include them
+    val sessionConf = spark.sessionState.conf
+    val viewIdent = catalog.name +: ident.asMultipartIdentifier
+    val viewChain = if (ViewUtil.referencedByEnabled(sessionConf)) {
+      existingChain :+ viewIdent
+    } else {
+      Seq.empty
+    }
+    val compensate = viewSchemaMode(sessionConf) == 
SparkSQLProperties.VIEW_SCHEMA_MODE_COMPENSATION
 
-    // Apply any necessary rewrites to preserve correct resolution
-    val viewCatalogAndNamespace: Seq[String] = view.currentCatalog +: 
view.currentNamespace.toSeq
-    val rewritten = rewriteIdentifiers(parsed, viewCatalogAndNamespace);
+    // Like Spark's own views, the view body is parsed and analyzed with the 
SQL configs captured
+    // at creation, and nested views are expanded within the outer view's 
analysis
+    ViewUtil.withNestedView(viewIdent, sessionConf.maxNestedViewDepth) {
+      val viewConf = ViewNode.effectiveSQLConf(ViewUtil.sqlConfigs(view), 
isTempView = false)
+      SQLConf.withExistingConf(viewConf) {
+        val parsed = parseViewText(nameParts.quoted, view.query)
+
+        // Apply any necessary rewrites to preserve correct resolution
+        val viewCatalogAndNamespace: Seq[String] =
+          view.currentCatalog +: view.currentNamespace.toSeq
+        val rewritten = rewriteIdentifiers(parsed, viewCatalogAndNamespace, 
viewChain)
+
+        val columns = viewColumns(nameParts.quoted, view, viewConf, compensate)
+        val analyzed = spark.sessionState.analyzer.execute(Project(columns, 
rewritten))
+        spark.sessionState.analyzer.checkAnalysis(analyzed)
+        SubqueryAlias(nameParts, analyzed)
+      }
+    }
+  }
+
+  private def viewColumns(
+      viewName: String,
+      view: View,
+      viewConf: SQLConf,
+      compensate: Boolean): Seq[NamedExpression] = {
+    val queryColumnNames = view.queryColumnNames.toIndexedSeq
+    val bindByName = queryColumnNames.length == view.schema.length

Review Comment:
   This changes how view columns bind for everyone on 3.5/4.0/4.1, even with 
`spark.sql.iceberg.referenced-by.enabled` off. Iceberg's `ResolveViews` has 
bound view columns by position on purpose (the removed comment: "BINDING is 
more strict because it doesn't allow resolution by field name"). 4.2 binds by 
name only because it now uses Spark's own view resolution.
   
   Binding by name fixes reordered columns (as `readFromViewBindsColumnsByName` 
shows), but I'd expect it to break a `SELECT *` view over a table whose column 
was later renamed, which works today.
   
   Since referenced-by doesn't seem to need this, could we remove this behavior 
change from this PR? 



##########
spark/v4.1/spark-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteViewCommands.scala:
##########
@@ -60,7 +60,8 @@ case class RewriteViewCommands(spark: SparkSession) extends 
Rule[LogicalPlan] wi
           query,
           allowExisting,
           replace,
-          _) =>
+          viewSchemaMode) =>
+      verifySchemaModeSupported(resolved, viewSchemaMode)

Review Comment:
   This also changes behavior regardless of the referenced-by flag: CREATE VIEW 
... WITH SCHEMA EVOLUTION / TYPE EVOLUTION succeeds today (the clause is 
ignored) and would fail after upgrade. Could we remove this behavior change, 
since it's unrelated to referenced-by?



##########
spark/v4.1/spark-extensions/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveViews.scala:
##########
@@ -104,34 +121,136 @@ case class ResolveViews(spark: SparkSession) extends 
Rule[LogicalPlan] with Look
     }
   }
 
-  private def createViewRelation(nameParts: Seq[String], view: View): 
LogicalPlan = {
-    val parsed = parseViewText(nameParts.quoted, view.query)
+  private def resolveRelationFromView(
+      relation: UnResolvedRelationFromView,
+      catalog: CatalogPlugin,
+      ident: Identifier): LogicalPlan = {
+    val parts = relation.tableMultipartIdentifier
+    val referencedBy = ViewUtil.buildReferencedByChain(relation.viewChain, 
catalog.name())
+    catalog match {
+      case contextual: TableCatalog with SparkSupportsLoadContext if 
!relation.isStreaming =>
+        val context = LoadContext.builder().referencedBy(referencedBy).build()
+        val timeTravelSpec = TimeTravelSpec.create(
+          relation.timeTravelTimestamp,
+          relation.timeTravelVersion,
+          conf.sessionLocalTimeZone)
+        try {
+          ViewUtil.loadTable(contextual, ident, context, timeTravelSpec) match 
{
+            case _: V1Table =>
+              toUnresolvedRelation(relation)
+            case table =>
+              val relationCatalog = if (timeTravelSpec.isEmpty) {
+                LoadContextTableCatalog(contextual, context)
+              } else {
+                contextual
+              }
+              SubqueryAlias(
+                catalog.name +: ident.asMultipartIdentifier,
+                DataSourceV2Relation.create(
+                  table,
+                  Some(relationCatalog),
+                  Some(ident),
+                  relation.options,
+                  timeTravelSpec))
+          }
+        } catch {
+          case _: NoSuchTableException =>
+            ViewUtil
+              .loadView(catalog, ident, context)
+              .map(createViewRelation(parts, catalog, ident, _, 
relation.viewChain))
+              .getOrElse(toUnresolvedRelation(relation))
+        }
+
+      case _ =>
+        toUnresolvedRelation(relation)
+    }
+  }
+
+  private def toUnresolvedRelation(relation: UnResolvedRelationFromView): 
LogicalPlan = {
+    val unresolved =
+      UnresolvedRelation(relation.tableMultipartIdentifier, relation.options, 
relation.isStreaming)
+    if (relation.timeTravelVersion.isEmpty && 
relation.timeTravelTimestamp.isEmpty) {
+      unresolved
+    } else {
+      RelationTimeTravel(unresolved, relation.timeTravelTimestamp, 
relation.timeTravelVersion)
+    }
+  }
+
+  private def createViewRelation(
+      nameParts: Seq[String],
+      catalog: CatalogPlugin,
+      ident: Identifier,
+      view: View,
+      existingChain: Seq[Seq[String]] = Seq.empty): LogicalPlan = {
+    // Session settings are read before switching to the view's captured SQL 
configs, which
+    // don't include them
+    val sessionConf = spark.sessionState.conf
+    val viewIdent = catalog.name +: ident.asMultipartIdentifier
+    val viewChain = if (ViewUtil.referencedByEnabled(sessionConf)) {
+      existingChain :+ viewIdent
+    } else {
+      Seq.empty
+    }
+    val compensate = viewSchemaMode(sessionConf) == 
SparkSQLProperties.VIEW_SCHEMA_MODE_COMPENSATION
 
-    // Apply any necessary rewrites to preserve correct resolution
-    val viewCatalogAndNamespace: Seq[String] = view.currentCatalog +: 
view.currentNamespace.toSeq
-    val rewritten = rewriteIdentifiers(parsed, viewCatalogAndNamespace);
+    // Like Spark's own views, the view body is parsed and analyzed with the 
SQL configs captured
+    // at creation, and nested views are expanded within the outer view's 
analysis
+    ViewUtil.withNestedView(viewIdent, sessionConf.maxNestedViewDepth) {
+      val viewConf = ViewNode.effectiveSQLConf(ViewUtil.sqlConfigs(view), 
isTempView = false)

Review Comment:
   This also applies with `spark.sql.iceberg.referenced-by.enabled` off. For 
views that store SQL configs (like the doubleQuotedIdentifiers test), using 
them on read looks right. But existing Iceberg views on 3.5/4.0/4.1 have no 
stored configs, and `effectiveSQLConf` starts from Spark's defaults rather than 
the session conf. So after upgrading, session settings would no longer apply 
inside these views.
   
   On 4.0/4.1 I'd also expect ANSI to be turned off for these views: with no 
stored `spark.sql.ansi.enabled` and no `createSparkVersion` passed in, 
`trySetAnsiValue` sets it to false 
(`spark.sql.assumeAnsiFalseIfNotPersisted.enabled` defaults to true). So 
something like `CAST('abc' AS INT)` in an existing view would return null 
instead of failing.
   
   Since referenced-by doesn't seem to need this, could we remove this behavior 
change from this PR as well, along with capturing configs in CREATE VIEW?



-- 
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