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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala:
##########
@@ -132,29 +135,58 @@ 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.
+   * Reads a generation expression for both auto-fill and validation. Convert 
the modeled expression
+   * once, falling back to SQL text when it is absent or cannot be converted, 
as defaults and CHECK
+   * constraints do. Conversion is deferred so presence checks do not read 
either form.
    */
-  def attachGenerationExpressions(relation: DataSourceV2Relation): 
Seq[AttributeReference] = {
-    if (!supportsGeneratedColumnsOnWrite(relation.table)) {
-      return relation.output
+  private[sql] class ExpressionReader(
+      relation: DataSourceV2Relation,
+      colName: String,
+      genExpr: GenerationExpression) {
+    private lazy val modeledExpression = Option(genExpr.getExpression)
+      .flatMap(V2ExpressionUtils.toCatalyst)
+
+    def toCatalyst(readSql: String => Expression = 
StoredExpressionText.parse): Expression = {
+      modeledExpression.orElse(Option(genExpr.getSql).map(readSql))
+        .getOrElse {
+          val operation = s"a value for the generated column 
${toSQLId(colName)}, because " +
+            s"Spark cannot convert its expression ${genExpr.getExpression}"
+          // A relation of a TableProvider has no catalog and no identifier.
+          throw ((relation.catalog, relation.identifier) match {
+            case (Some(catalog), Some(ident)) =>
+              QueryCompilationErrors.unsupportedTableOperationError(catalog, 
ident, operation)
+            case _ =>
+              
QueryCompilationErrors.unsupportedTableOperationError(relation.table, operation)
+          })
+        }
     }
-    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 sql: String = modeledExpression.map(_.sql).getOrElse(genExpr.getSql)
+
+    /** Only SQL text may fall back to analysis under the writing session's 
settings. */
+    def analyze[E <: Expression](
+        expr: E,
+        inSession: => E,
+        input: Seq[Attribute],
+        analyzer: LogicalPlan => LogicalPlan): E = {
+      if (modeledExpression.isEmpty) {
+        StoredExpressionText.analyze(expr, inSession, input, analyzer)
+      } else {
+        val conf = StoredExpressionText.conf(SQLConf.get, useCurrentConfigs = 
false)
+        SQLConf.withExistingConf(conf) {
+          val named = expr match {
+            case n: NamedExpression => n
+            case e => Alias(e, "value")()
+          }
+          val plan = analyzer(Project(Seq(named), LocalRelation(input)))
+          // Report unresolved references and type errors before the writer 
can re-analyze them.
+          SimpleAnalyzer.checkAnalysis(plan)

Review Comment:
   Fixed in 2befeffe91a. The strict analyzer still executes under fixed ANSI 
settings, but `checkAnalysis` now runs after leaving that conf, under the 
session's representation settings. Added auto-fill and explicit-value 
regressions for both first-class CHAR/VARCHAR configs and both types, including 
generated CHAR/VARCHAR values followed by `INSERT ... SELECT *` validation.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala:
##########
@@ -132,29 +135,58 @@ 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.
+   * Reads a generation expression for both auto-fill and validation. Convert 
the modeled expression
+   * once, falling back to SQL text when it is absent or cannot be converted, 
as defaults and CHECK
+   * constraints do. Conversion is deferred so presence checks do not read 
either form.
    */
-  def attachGenerationExpressions(relation: DataSourceV2Relation): 
Seq[AttributeReference] = {
-    if (!supportsGeneratedColumnsOnWrite(relation.table)) {
-      return relation.output
+  private[sql] class ExpressionReader(
+      relation: DataSourceV2Relation,
+      colName: String,
+      genExpr: GenerationExpression) {
+    private lazy val modeledExpression = Option(genExpr.getExpression)

Review Comment:
   Fixed in 2befeffe91a by constructing the cached modeled expression under 
`StoredExpressionText.fixedConf`, as well as analyzing it there. This pins 
FLOOR/CEIL's construction-time ANSI behavior for generated columns without 
changing those functions' shared converter behavior for defaults or CHECK 
constraints. Tests cover both functions, positive/negative overflow and 
infinity, auto-fill and explicit validation, across all combinations of writer 
ANSI and legacy settings; valid rows also survive `INSERT ... SELECT *`.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala:
##########
@@ -132,29 +135,58 @@ 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.
+   * Reads a generation expression for both auto-fill and validation. Convert 
the modeled expression
+   * once, falling back to SQL text when it is absent or cannot be converted, 
as defaults and CHECK
+   * constraints do. Conversion is deferred so presence checks do not read 
either form.
    */
-  def attachGenerationExpressions(relation: DataSourceV2Relation): 
Seq[AttributeReference] = {
-    if (!supportsGeneratedColumnsOnWrite(relation.table)) {
-      return relation.output
+  private[sql] class ExpressionReader(
+      relation: DataSourceV2Relation,
+      colName: String,
+      genExpr: GenerationExpression) {
+    private lazy val modeledExpression = Option(genExpr.getExpression)
+      .flatMap(V2ExpressionUtils.toCatalyst)

Review Comment:
   Fixed in 2befeffe91a. Modeled literal conversion now uses `Literal.create` 
to normalize public string, decimal and date values, matching the other 
converter overload. The correctness review also found that a value incompatible 
with its declared type could still throw, so only literal construction is 
wrapped in `Try(...).toOption`: an unconvertible literal permits SQL fallback, 
while later analysis/evaluation errors remain strict. Added converter tests for 
external/internal representations and incompatible values, plus write tests 
proving model precedence and SQL fallback for auto-fill and explicit 
validation. Without SQL, an invalid literal reports the contextual 
unsupported-generated-column error.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/WriteOutputResolution.scala:
##########
@@ -46,23 +46,31 @@ 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) =
+    // Read directly from the V2 columns so modeled expressions do not pass 
through SQL text
+    // or schema metadata. Reuse the readers when SQL text needs the session 
fallback pass.
+    val generationExpressions: Map[String, GeneratedColumn.ExpressionReader] = 
v2Write.table match {
+      case r: DataSourceV2Relation if 
GeneratedColumn.supportsGeneratedColumnsOnWrite(r.table) =>
+        r.table.columns().flatMap { col =>
+          GeneratedColumn.columnGenerationExpression(col).map { expr =>

Review Comment:
   Fixed in 2befeffe91a. `columnGenerationExpression` now fills missing SQL 
from the legacy getter when the modern getter supplies only a model. It 
preserves the modern getter's SQL when present and keeps a convertible model 
first. Tests cover separate legacy SQL with both convertible and unsupported 
models, for auto-fill and explicit validation. The in-memory table also retains 
the combined expression across repeated writes.



##########
docs/sql-migration-guide.md:
##########
@@ -89,7 +89,8 @@ license: |
 - Since Spark 4.4, the Spark Thrift Server logs a warning at startup when 
`hive.server2.enable.doAs` is `true` and `hive.server2.authentication` verifies 
user identities (any recognized type other than `NONE`/`NOSASL`), because 
executor-side data access still runs as the server's own service identity 
rather than the connecting user (SPARK-5159). Set 
`spark.sql.hive.thriftServer.allowIneffectiveDoAs` to `true` to acknowledge the 
limitation and silence the warning. Spark 5.0 is expected to refuse to start on 
this configuration unless that option is set.
 - Since Spark 4.4, `UPDATE` and `MERGE` on a Data Source V2 table fail with 
`DATATYPE_MISMATCH.INVALID_ROW_LEVEL_OPERATION_ASSIGNMENTS` when they assign to 
a metadata column of the table. This includes `UPDATE SET *` and `INSERT *` in 
`MERGE WITH SCHEMA EVOLUTION` when the source has a column with the name of a 
metadata column of the target table. Previously, these assignments passed 
analysis and were usually ignored. To restore the previous behavior, set 
`spark.sql.legacy.ignoreMetadataColumnAssignments` to `true`.
 - Since Spark 4.4, `CREATE TABLE`, `REPLACE TABLE`, and `ALTER TABLE ... ADD 
CONSTRAINT` on a Data Source V2 table fail with 
`USER_DEFINED_FUNCTION_IN_CHECK_CONSTRAINT` when the condition of a CHECK 
constraint calls a user-defined scalar function, including a Data Source V2 
function. `ALTER TABLE ... ADD CONSTRAINT` keeps failing with 
`UNSUPPORTED_SQL_UDF_USAGE` on a SQL function. Previously, a write could 
resolve the function name in its own session, so that it enforced another rule 
or failed (SPARK-60777). To run these statements, change the condition to call 
only built-in functions. Existing constraints that call a user-defined function 
are not rejected.
-- Since Spark 4.4, a write to a Data Source V2 table parses and analyzes the 
stored text of a generation expression with ANSI mode on and the default values 
of the SQL configs that change how a text reads, such as 
`spark.sql.parser.escapedStringLiterals`, regardless of the session of the 
write. Only the following still follow that session: the session time zone, 
case sensitivity, `spark.sql.timestampType`, 
`spark.sql.decimalOperations.allowPrecisionLoss`, the configs that a view also 
takes from the session that reads it, the functions found through `SET PATH`, 
and the configs that an expression reads during evaluation, such as 
`spark.sql.legacy.timeParserPolicy`. Any other config that the parsing or the 
analysis reads takes its default value, also one that a function reads while it 
is built, such as `spark.sql.legacy.negativeIndexInArrayInsert`. A text that 
does not resolve under these settings, such as `flag = 1` on a `BOOLEAN` 
column, is parsed with the ANSI mode of that session a
 nd analyzed under that session, and a text that does not parse under them is 
parsed under that session. Previously, the session of the write decided how the 
text read, so a write could silently store a wrong value (SPARK-60757). As a 
result, with `spark.sql.ansi.enabled=false`, also for a table created with that 
setting, a write can fail with an error such as `CAST_INVALID_INPUT` where 
Spark 4.3 stored `NULL`, and an implicit cast can change the stored value. The 
validation of a provided value compares it with the value that the write would 
store, so a value that only casts to it now fails with 
`CHECK_CONSTRAINT_VIOLATION`, also with ANSI mode on. For example, for `b 
STRING GENERATED ALWAYS AS (coalesce(s, 1))` with `s = '007'`, which stores 
`7`, a provided `07` fails. A table created with a non-default value of a 
config such as `spark.sql.parser.escapedStringLiterals` also gets the default 
reading of its text on every write, without an error. A table CHECK constraint 
is still read 
 under the session that writes, so a constraint that repeats the text of a 
generation expression can fail a write whose session sets such a config. A row 
that Spark 4.3 stored differently can fail with such an error or with 
`CHECK_CONSTRAINT_VIOLATION` when a later write provides it again, such as an 
`INSERT ... SELECT` from the same table. A `DELETE` does not check the 
generated columns of the rows that it carries. To fix such a table, create a 
new table with a text that reads as intended under these settings, and copy the 
other columns into it with `INSERT ... SELECT`. To read the text under the 
session of the write, as Spark 4.3 does, set 
`spark.sql.legacy.useCurrentConfigsForGeneratedColumn` to `true`.
+- Since Spark 4.4, a write to a Data Source V2 table with the 
`GENERATE_COLUMN_VALUES_ON_WRITE` capability uses a modeled connector 
generation expression when Spark can convert it, for both auto-filling missing 
generated values and validating provided values. Only when the modeled 
expression is absent or cannot be converted does Spark read the SQL text. A 
converted modeled expression is analyzed with ANSI mode on and keeps the 
explicit and implicit casts stored by the connector. For example, for `b STRING 
GENERATED ALWAYS AS (coalesce(s, 1))` with `s = '007'`, a convertible modeled 
expression stored by `CREATE TABLE` with ANSI mode off generates `'007'`; one 
stored with ANSI mode on generates `'7'`. Analysis or evaluation errors in a 
converted modeled expression fail the write without falling back to SQL text or 
the writing session's type coercion. Previously, auto-fill used only SQL text, 
and validation preferred SQL text when both forms were available (SPARK-61495).

Review Comment:
   Corrected in 2befeffe91a after checking the released Spark 4.3.0 
implementation. The migration guide now says that auto-fill previously used 
only SQL, while validation already preferred modeled expressions but used the 
writer's analysis settings and compared before the cast to the column type. 
Removed the SQL-first wording from the legacy-flag sentence and corrected the 
PR description too.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala:
##########
@@ -132,29 +135,58 @@ 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.
+   * Reads a generation expression for both auto-fill and validation. Convert 
the modeled expression
+   * once, falling back to SQL text when it is absent or cannot be converted, 
as defaults and CHECK
+   * constraints do. Conversion is deferred so presence checks do not read 
either form.
    */
-  def attachGenerationExpressions(relation: DataSourceV2Relation): 
Seq[AttributeReference] = {
-    if (!supportsGeneratedColumnsOnWrite(relation.table)) {
-      return relation.output
+  private[sql] class ExpressionReader(
+      relation: DataSourceV2Relation,
+      colName: String,
+      genExpr: GenerationExpression) {
+    private lazy val modeledExpression = Option(genExpr.getExpression)
+      .flatMap(V2ExpressionUtils.toCatalyst)
+
+    def toCatalyst(readSql: String => Expression = 
StoredExpressionText.parse): Expression = {
+      modeledExpression.orElse(Option(genExpr.getSql).map(readSql))
+        .getOrElse {
+          val operation = s"a value for the generated column 
${toSQLId(colName)}, because " +
+            s"Spark cannot convert its expression ${genExpr.getExpression}"
+          // A relation of a TableProvider has no catalog and no identifier.
+          throw ((relation.catalog, relation.identifier) match {
+            case (Some(catalog), Some(ident)) =>
+              QueryCompilationErrors.unsupportedTableOperationError(catalog, 
ident, operation)
+            case _ =>
+              
QueryCompilationErrors.unsupportedTableOperationError(relation.table, operation)
+          })
+        }
     }
-    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 sql: String = modeledExpression.map(_.sql).getOrElse(genExpr.getSql)
+
+    /** Only SQL text may fall back to analysis under the writing session's 
settings. */
+    def analyze[E <: Expression](
+        expr: E,
+        inSession: => E,
+        input: Seq[Attribute],
+        analyzer: LogicalPlan => LogicalPlan): E = {
+      if (modeledExpression.isEmpty) {
+        StoredExpressionText.analyze(expr, inSession, input, analyzer)
+      } else {
+        val conf = StoredExpressionText.conf(SQLConf.get, useCurrentConfigs = 
false)
+        SQLConf.withExistingConf(conf) {
+          val named = expr match {

Review Comment:
   Refactored in 2befeffe91a. `StoredExpressionText` now owns `analyzeStrict` 
alongside the SQL-text `analyze`, with shared `analyzePlan` and 
`expressionFromPlan` helpers for wrapping, analysis and extraction. 
`ExpressionReader.analyze` only dispatches between the two paths. The strict 
variant also contains the `checkAnalysis` placement fix from [5].



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