szehon-ho commented on code in PR #60368:
URL: https://github.com/apache/spark/pull/60368#discussion_r4555442593


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala:
##########
@@ -122,31 +123,28 @@ object GeneratedColumn {
   }
 
   /**
-   * Returns `relation`'s output with every generated column's generation 
expression recorded in
-   * the attribute's metadata, which is where [[TableOutputResolver]] looks 
when it auto-fills the
-   * generated columns a write does not provide a value for.
-   *
-   * Generation expressions are internal metadata: they should neither surface 
in a DataFrame's
-   * schema nor propagate into tables created from it. A table's V2 columns 
are the persisted form
-   * and the source of truth, so the write path copies the expression into 
plan attribute metadata
-   * only for as long as resolving the write takes.
-   *
-   * The output is returned unchanged if the table does not ask Spark to 
handle generated columns.
+   * Converts a generation expression for both auto-fill and validation. Try 
the modeled expression
+   * first, falling back to SQL text when it is absent or cannot be converted, 
as defaults and CHECK
+   * constraints do.
    */
-  def attachGenerationExpressions(relation: DataSourceV2Relation): 
Seq[AttributeReference] = {
-    if (!supportsGeneratedColumnsOnWrite(relation.table)) {
-      return relation.output
-    }
-    val genExprs = relation.table.columns()
-      .flatMap(col => Option(col.generationExpression()).map(col.name -> _))
-      .toMap
-    relation.output.map { attr =>
-      genExprs.get(attr.name) match {
-        case Some(genExpr) =>
-          withMetadataEntry(attr, GENERATION_EXPRESSION_METADATA_KEY, genExpr)
-        case None => attr
+  def toCatalyst(
+      relation: DataSourceV2Relation,
+      colName: String,
+      genExpr: GenerationExpression,
+      readSql: String => Expression = StoredExpressionText.parse): Expression 
= {
+    Option(genExpr.getExpression)

Review Comment:
   Updated in 607399ca8e6. The migration guide now documents modeled-first 
precedence and retained implicit casts, distinguishes the `'007'` and `'7'` 
cases, and scopes the legacy flag to SQL-text reading. The PR description has 
the same clarification.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/WriteOutputResolution.scala:
##########
@@ -46,23 +47,34 @@ private[sql] object WriteOutputResolution {
     val defaultValueFillMode =
       if (conf.coerceInsertNestedTypes && v2Write.schemaEvolutionEnabled) 
RECURSE
       else FILL
-    // Generation expressions live on the table's columns, so attach them to 
the expected
-    // output for TableOutputResolver, which auto-fills the generated columns 
the query is
-    // missing.
-    val expected = v2Write.table match {
-      case r: DataSourceV2Relation => 
GeneratedColumn.attachGenerationExpressions(r)
-      case _ => v2Write.table.output
-    }
     val schemaAlignmentConfig = v2Write.table match {
       case ExtractV2Table(table: SupportsConfigurableSchemaAlignment) =>
         table.schemaAlignmentConfig()
       case _ => SchemaAlignmentConfig.DEFAULT
     }
-    def resolveOutput(readGenerationExpr: String => Expression) =
+    def resolveOutput(readSql: String => Expression) = {
+      // Read directly from the V2 columns so modeled expressions do not pass 
through SQL text
+      // or schema metadata. Only tables with the write capability ask Spark 
to generate values.
+      val readGenerationExpr: Attribute => Option[() => Expression] = 
v2Write.table match {
+        case r: DataSourceV2Relation if 
GeneratedColumn.supportsGeneratedColumnsOnWrite(r.table) =>
+          val expressions = r.table.columns().flatMap { col =>

Review Comment:
   Moved the capability check and column-reader map outside `resolveOutput` in 
607399ca8e6. The stored-settings and SQL session-fallback passes now reuse that 
map and the cached modeled conversions.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala:
##########
@@ -122,31 +123,28 @@ object GeneratedColumn {
   }
 
   /**
-   * Returns `relation`'s output with every generated column's generation 
expression recorded in
-   * the attribute's metadata, which is where [[TableOutputResolver]] looks 
when it auto-fills the
-   * generated columns a write does not provide a value for.
-   *
-   * Generation expressions are internal metadata: they should neither surface 
in a DataFrame's
-   * schema nor propagate into tables created from it. A table's V2 columns 
are the persisted form
-   * and the source of truth, so the write path copies the expression into 
plan attribute metadata
-   * only for as long as resolving the write takes.
-   *
-   * The output is returned unchanged if the table does not ask Spark to 
handle generated columns.
+   * Converts a generation expression for both auto-fill and validation. Try 
the modeled expression
+   * first, falling back to SQL text when it is absent or cannot be converted, 
as defaults and CHECK
+   * constraints do.
    */
-  def attachGenerationExpressions(relation: DataSourceV2Relation): 
Seq[AttributeReference] = {
-    if (!supportsGeneratedColumnsOnWrite(relation.table)) {
-      return relation.output
-    }
-    val genExprs = relation.table.columns()
-      .flatMap(col => Option(col.generationExpression()).map(col.name -> _))
-      .toMap
-    relation.output.map { attr =>
-      genExprs.get(attr.name) match {
-        case Some(genExpr) =>
-          withMetadataEntry(attr, GENERATION_EXPRESSION_METADATA_KEY, genExpr)
-        case None => attr
+  def toCatalyst(
+      relation: DataSourceV2Relation,
+      colName: String,
+      genExpr: GenerationExpression,
+      readSql: String => Expression = StoredExpressionText.parse): Expression 
= {
+    Option(genExpr.getExpression)
+      .flatMap(V2ExpressionUtils.toCatalyst)
+      .orElse(Option(genExpr.getSql).map(readSql))

Review Comment:
   Updated both tests in 607399ca8e6 to create SQL-only generated columns 
through the catalog API. They now exercise reserved-keyword parsing and the 
IDENTIFIER session-analysis fallback, with assertions on the stored values. The 
IDENTIFIER case covers both auto-fill and validation of a supplied value.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala:
##########
@@ -97,7 +95,7 @@ private[sql] class TableConstraintResolution(
       Option(col.columnGenerationExpression())
         .filter(_ => !autoFilledGenCols.exists(n => resolver(n, col.name)))
         .map { genExpr =>
-          val catalystExpr = buildGenerationCatalystExpression(r, col.name, 
genExpr)
+          val catalystExpr = GeneratedColumn.toCatalyst(r, col.name, genExpr)
           val colRef = UnresolvedAttribute.quoted(col.name)
           val columnExtractors = Seq(col.name -> colRef)
           val genExprSql = Option(genExpr.getSql()).getOrElse(catalystExpr.sql)

Review Comment:
   Fixed in 607399ca8e6. The diagnostic now uses the converted model's `.sql` 
when that model is selected, and the original SQL text only when the SQL path 
is used. Added exact violation-message assertions for differing model/SQL forms 
and empty or invalid unused SQL.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala:
##########
@@ -122,31 +123,28 @@ object GeneratedColumn {
   }
 
   /**
-   * Returns `relation`'s output with every generated column's generation 
expression recorded in
-   * the attribute's metadata, which is where [[TableOutputResolver]] looks 
when it auto-fills the
-   * generated columns a write does not provide a value for.
-   *
-   * Generation expressions are internal metadata: they should neither surface 
in a DataFrame's
-   * schema nor propagate into tables created from it. A table's V2 columns 
are the persisted form
-   * and the source of truth, so the write path copies the expression into 
plan attribute metadata
-   * only for as long as resolving the write takes.
-   *
-   * The output is returned unchanged if the table does not ask Spark to 
handle generated columns.
+   * Converts a generation expression for both auto-fill and validation. Try 
the modeled expression
+   * first, falling back to SQL text when it is absent or cannot be converted, 
as defaults and CHECK
+   * constraints do.
    */
-  def attachGenerationExpressions(relation: DataSourceV2Relation): 
Seq[AttributeReference] = {
-    if (!supportsGeneratedColumnsOnWrite(relation.table)) {
-      return relation.output
-    }
-    val genExprs = relation.table.columns()
-      .flatMap(col => Option(col.generationExpression()).map(col.name -> _))
-      .toMap
-    relation.output.map { attr =>
-      genExprs.get(attr.name) match {
-        case Some(genExpr) =>
-          withMetadataEntry(attr, GENERATION_EXPRESSION_METADATA_KEY, genExpr)
-        case None => attr
+  def toCatalyst(
+      relation: DataSourceV2Relation,
+      colName: String,
+      genExpr: GenerationExpression,
+      readSql: String => Expression = StoredExpressionText.parse): Expression 
= {
+    Option(genExpr.getExpression)
+      .flatMap(V2ExpressionUtils.toCatalyst)

Review Comment:
   Added argument-count checks in `V2ExpressionUtils` in 607399ca8e6 for 
WIDTH_BUCKET, IN, BOOLEAN_EXPRESSION, CASE_WHEN, COALESCE, GREATEST, and LEAST. 
Malformed counts now return `None`, allowing SQL fallback; valid expressions 
retain their behavior. Added converter boundary tests and write regressions for 
the three reported cases, covering both auto-fill and explicit-value validation.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/WriteOutputResolution.scala:
##########
@@ -46,23 +47,34 @@ private[sql] object WriteOutputResolution {
     val defaultValueFillMode =
       if (conf.coerceInsertNestedTypes && v2Write.schemaEvolutionEnabled) 
RECURSE
       else FILL
-    // Generation expressions live on the table's columns, so attach them to 
the expected
-    // output for TableOutputResolver, which auto-fills the generated columns 
the query is
-    // missing.
-    val expected = v2Write.table match {
-      case r: DataSourceV2Relation => 
GeneratedColumn.attachGenerationExpressions(r)
-      case _ => v2Write.table.output
-    }
     val schemaAlignmentConfig = v2Write.table match {
       case ExtractV2Table(table: SupportsConfigurableSchemaAlignment) =>
         table.schemaAlignmentConfig()
       case _ => SchemaAlignmentConfig.DEFAULT
     }
-    def resolveOutput(readGenerationExpr: String => Expression) =
+    def resolveOutput(readSql: String => Expression) = {
+      // Read directly from the V2 columns so modeled expressions do not pass 
through SQL text
+      // or schema metadata. Only tables with the write capability ask Spark 
to generate values.
+      val readGenerationExpr: Attribute => Option[() => Expression] = 
v2Write.table match {
+        case r: DataSourceV2Relation if 
GeneratedColumn.supportsGeneratedColumnsOnWrite(r.table) =>
+          val expressions = r.table.columns().flatMap { col =>
+            // Read SQL text, a modeled expression, or both.
+            val generationExpr = 
Option(col.columnGenerationExpression()).orElse {
+              // Support connectors implementing only the legacy SQL getter.
+              Option(col.generationExpression()).map(sql => new 
GenerationExpression(sql))
+            }
+            generationExpr.map(col.name -> _)
+          }.toMap
+          attr => expressions.get(attr.name).map { expr =>
+            () => GeneratedColumn.toCatalyst(r, attr.name, expr, readSql)

Review Comment:
   Fixed in 607399ca8e6. Converted models are analyzed and checked under the 
fixed ANSI settings, without falling back to the writer's settings or SQL text 
on analysis errors. Only the SQL-text path retains session fallback. Added 
`flag = 1` regressions for auto-fill and explicit-value validation under all 
four combinations of writer ANSI and legacy settings; all fail ANSI type 
checking.



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