dongjoon-hyun commented on code in PR #60368:
URL: https://github.com/apache/spark/pull/60368#discussion_r4558589922


##########
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:
   **[5] With first-class CHAR/VARCHAR, this `checkAnalysis` fails the write 
with an INTERNAL_ERROR.** It runs inside `SQLConf.withExistingConf(conf)` 
(L176). The fixed conf from `StoredExpressionText.conf` starts from `new 
SQLConf` and keeps only what `retainResolutionConfigsForAnalysis` copies, so 
`spark.sql.preserveCharVarcharTypeInfo` and 
`spark.sql.charVarchar.standardSemantics.enabled` are both false in it. When 
the writer's session sets either one, `input` keeps the CHAR/VARCHAR types, and 
the `LeafNode` check in `CheckAnalysis.scala:454-460` throws `Logical plan 
should not have output of char/varchar type ...` for `LocalRelation(input)`. 
For example:
   
   ```sql
   SET spark.sql.preserveCharVarcharTypeInfo=true;
   CREATE TABLE testcat.t (a INT, s CHAR(5), b INT GENERATED ALWAYS AS (a + 1)) 
USING foo;
   INSERT INTO testcat.t(a, s) VALUES (1, 'x');  -- auto-fill
   INSERT INTO testcat.t VALUES (1, 'x', 2);     -- validation of a provided 
value
   ```
   
   Both INSERTs fail, although `b` does not read `s`. In round 1 (c2ffe55) and 
at the base, they succeed, because `StoredExpressionText.analyze` only runs 
`execute` and does not call `checkAnalysis`. No test combines generated columns 
with these configs, so CI does not catch it.
   
   Could `checkAnalysis` run outside the fixed conf, as `ResolveSQLFunctions` 
does (`Analyzer.scala:2871`)? A test with one of these configs and a CHAR 
column would cover it.



##########
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:
   **[6] A modeled `FLOOR` or `CEIL` still follows the writer's ANSI mode.** 
`modeledExpression` is first evaluated outside the fixed conf, under the 
writer's session: in `TableOutputResolver` for auto-fill and in 
`TableConstraintResolution` for validation. `V2ExpressionUtils` converts 
`FLOOR` and `CEIL` to `Floor(_)` and `Ceil(_)` 
(`V2ExpressionUtils.scala:403-404`), whose `failOnError` defaults to 
`SQLConf.get.ansiEnabled`. Its neighbors pin it instead: `Abs(_, failOnError = 
true)`, `UnaryMinus(_, failOnError = true)` and `Round(_, _, ansiEnabled = 
true)`. The later analysis under the fixed conf does not change it.
   
   For example, `CREATE TABLE testcat.t (d DOUBLE, b BIGINT GENERATED ALWAYS AS 
(floor(d))) USING foo` stores the model `FLOOR(d)` 
(`V2ExpressionBuilder.scala:197`). Then:
   
   - With `spark.sql.ansi.enabled=false`, `INSERT INTO testcat.t(d) VALUES 
(1e19)` stores `b = 9223372036854775807`, because `Floor` clamps with 
`.toLong`. At the base, auto-fill built `floor` from the SQL text under the 
fixed conf, so the same write failed with ARITHMETIC_OVERFLOW.
   - A later ANSI write that carries that row, such as `INSERT INTO testcat.t 
SELECT * FROM testcat.t`, fails with ARITHMETIC_OVERFLOW on a row that Spark 
auto-filled.
   
   Infinity behaves the same way. This is the case [3] was about: the stored 
value depends on the writer's session. It also contradicts the new Javadoc and 
migration guide, which say that a converted expression is analyzed with ANSI 
mode on.
   
   Could the converter pin `failOnError = true` for both, as it does for `ABS`, 
or could `modeledExpression` be converted under the fixed conf? The converter 
is shared with CHECK constraints and defaults, so the first option changes 
those too.



##########
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:
   **[8] Auto-fill now uses the legacy SQL getter only when the new getter 
returns null.** This line reads the column through 
`GeneratedColumn.columnGenerationExpression(col)` 
(`GeneratedColumn.scala:120-123`, from #60393), which takes 
`columnGenerationExpression()` whenever it is non-null. A connector `Column` 
can override `generationExpression()` to return SQL text and 
`columnGenerationExpression()` to return a modeled-only `GenerationExpression`. 
If that model does not convert, say `UPPER(a)` or a `UserDefinedScalarFunc`, 
`INSERT INTO t(a) VALUES ('x')` now fails with 
UNSUPPORTED_FEATURE.TABLE_OPERATION. In 4.3.0 and at the base, auto-fill read 
`col.generationExpression()` in `attachGenerationExpressions` and stored `'X'`.
   
   This is a low-priority edge case. A provided value for such a column already 
failed validation, and a column built with `Column.create` or the builder keeps 
both getters consistent. Still, the PR description says it preserves support 
for connectors that override the legacy getter.
   
   Could the helper fill in the SQL text from the legacy getter when the new 
getter has no SQL, for example `new 
GenerationExpression(col.generationExpression(), g.getExpression)`? Validation 
uses the same helper, so it would be covered 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:
   **[10] The modeled branch repeats `StoredExpressionText.analyze`.** It wraps 
the expression in `Alias(e, "value")()`, analyzes `Project(Seq(named), 
LocalRelation(input))`, and unwraps the alias, as 
`StoredExpressionText.analyze` does (`StoredExpressionText.scala:103-120`). 
Only the conf, the error handling and the way the result is taken differ: here 
`plan.asInstanceOf[Project].projectList.head` (L184), there `case 
Project(Seq(a), _: LocalRelation) if a.resolved`. A later change to one copy 
would make SQL-text and modeled columns come back in different shapes.
   
   Could `StoredExpressionText` have a strict variant next to `analyze` (fixed 
conf, no fallback, errors reported), so that this method only dispatches? That 
would also be a natural place for the `checkAnalysis` change in [5].



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/GeneratedColumnWriteSuite.scala:
##########
@@ -347,6 +348,283 @@ class GeneratedColumnWriteSuite extends QueryTest with 
DatasourceV2SQLBase {
     }
   }
 
+  gridTest("modeled generation expression auto-fill")(
+      Seq("insert", "insert overwrite", "append", "overwrite", "overwrite 
partitions")) { mode =>
+    val tblName = "my_tab"
+    val genExpr = new GeneralScalarExpression("+", Array[V2Expression](
+      FieldReference(Seq("a.b")), FieldReference(Seq("s", "f"))))
+    val generation = new GenerationExpression(new V2Cast(genExpr, IntegerType, 
LongType))
+    withTable(s"testcat.$tblName") {
+      catalog("testcat").asInstanceOf[InMemoryCatalog].createTable(

Review Comment:
   **[11] Nit: the PR adds 13 copies of the catalog `createTable` call.** The 
suite now has 16 copies of 
`catalog("testcat").asInstanceOf[InMemoryCatalog].createTable(Identifier.of(Array(),
 tblName), Array(...), Array.empty[Transform], Collections.emptyMap[String, 
String])`, where the base had 3. Only the column list differs, and this 
four-argument overload is deprecated since 4.1.0 (`TableCatalog.java:358`). 
Could a small helper such as `createCatalogTable(columns: Column*)`, with 
optional properties for the `noWriteCapProp` case, replace them? 
`RowLevelOperationSuiteBase.createTable` builds a `TableInfo` the same way.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/StoredExpressionText.scala:
##########
@@ -38,9 +38,12 @@ object StoredExpressionText {
    * also one that a function reads while it is built, such as
    * `spark.sql.legacy.negativeIndexInArrayInsert`. With
    * `spark.sql.legacy.useCurrentConfigsForGeneratedColumn`, these are the 
settings of the session.
+   * Set `useCurrentConfigs` to false for modeled expressions, which always 
use the fixed settings.
    */
-  def conf(session: SQLConf): SQLConf = {
-    if (session.useCurrentSQLConfigsForGeneratedColumn) {
+  def conf(session: SQLConf): SQLConf = conf(session, useCurrentConfigs = true)
+
+  private[sql] def conf(session: SQLConf, useCurrentConfigs: Boolean): SQLConf 
= {

Review Comment:
   **[12] Nit: this Boolean overload has one caller.** 
`GeneratedColumn.scala:175` is the only caller, with `useCurrentConfigs = 
false`, and the note about it (L41) sits on the public `conf(session)`, which 
does not take the parameter. Could the else branch become `private[sql] def 
fixedConf(session: SQLConf): SQLConf`, with `conf(session)` returning 
`session.clone()` under the legacy flag and `fixedConf(session)` otherwise? The 
caller would then read `StoredExpressionText.fixedConf(SQLConf.get)`.



##########
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:
   **[7] A modeled literal that is not in Spark's internal representation 
throws instead of falling back to the SQL text.** The arity checks from [2] 
return `None`, but `toCatalyst` still throws for such a literal. `case l: 
V2Literal[_] => Some(Literal(l.value, l.dataType))` 
(`V2ExpressionUtils.scala:314`) fails in `Literal.validateLiteralValue` with 
`IllegalArgumentException: requirement failed: Literal must have a 
corresponding value to string, but class String found.` The public factory 
`Expressions.literal("Y")` builds such a literal, because it keeps the 
`java.lang.String` value. A `java.math.BigDecimal` or `LocalDate` value does 
the same.
   
   For example, take `b BOOLEAN` with `new GenerationExpression("a = 'Y'", new 
Predicate("=", Array(Expressions.column("a"), Expressions.literal("Y"))))`. 
Both `INSERT INTO t(a) VALUES ('Y')` and `INSERT INTO t VALUES ('Y', true)` 
fail during analysis with that exception, which has no error class and names no 
table or column. At the base, both read the SQL text first and succeeded.
   
   Strictly, the `Literal` Javadoc asks for internal values. But the new 
`GenerationExpression` Javadoc says that Spark falls back to the SQL string 
when the expression cannot be converted. `toCatalystOpt` in the same file 
already converts with `Literal.create` (`V2ExpressionUtils.scala:133-134`). 
Could `toCatalyst` do the same, or could `ExpressionReader` treat a conversion 
failure as `None`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/V2ExpressionUtils.scala:
##########
@@ -407,9 +408,13 @@ object V2ExpressionUtils extends SQLConfHelper with 
Logging {
       case "RADIANS" => convertUnaryExpr(expr, ToRadians)
       case "SIGN" => convertUnaryExpr(expr, Signum)
       case "WIDTH_BUCKET" =>

Review Comment:
   **[13] Nit: `WIDTH_BUCKET` checks its arity differently from its siblings.** 
The other new checks are case guards, such as `case "IN" if 
expr.children.nonEmpty =>` and `case "GREATEST" if expr.children.length >= 2 
=>`. This one is an `if`/`else` that returns `None`, which `case _ => None` 
already does. Could it be `case "WIDTH_BUCKET" if expr.children.length == 4 =>`?



##########
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:
   **[9] Spark 4.3.0 validated with the modeled expression first.** This entry 
says "Previously, auto-fill used only SQL text, and validation preferred SQL 
text when both forms were available", and the next entry says that the legacy 
flag "does not restore SQL-first precedence". In 4.3.0, 
[`ResolveTableConstraints`](https://github.com/apache/spark/blob/98bc0212c94705434471627068f41e374ccab143/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveTableConstraints.scala#L119-L127)
 tried the V2 expression first and fell back to the SQL string, and the 
`GenerationExpression` Javadoc said "Spark first attempts to convert the given 
expression". SQL-first validation exists only since 
[SPARK-60757](https://github.com/apache/spark/commit/6e287bf9bf3bb6c6e464c53350db507b210dfd1e),
 which is not in 4.3.0 or `branch-4.3`.
   
   So a 4.3 user would read this as a precedence change that did not happen. 
What changes from 4.3 is that auto-fill now uses the modeled expression, and 
that a modeled expression is analyzed under the fixed ANSI settings instead of 
the writer's session and is compared after the cast to the column type. Could 
this entry say "Previously, auto-fill used only the SQL text" and describe 
validation that way, and could the next entry drop the SQL-first wording?



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