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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala:
##########
@@ -132,29 +144,47 @@ 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 
{ expression =>
+      SQLConf.withExistingConf(StoredExpressionText.fixedConf(SQLConf.get)) {
+        V2ExpressionUtils.toCatalyst(expression)
+      }
     }
-    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(readSql: String => Expression = 
StoredExpressionText.parse): Expression = {
+      modeledExpression.orElse(Option(genExpr.getSql).map(readSql))

Review Comment:
   **[14] A model that `CREATE TABLE` built with ANSI mode off can carry 
constants folded under non-ANSI semantics, and a write now stores them without 
an error.**
   
   `GeneratedColumnExpression.toV2` builds the model with 
`V2ExpressionBuilder`, which replaces every `contextIndependentFoldable` 
subtree with its value (`V2ExpressionBuilder.scala:110-121`, under 
`spark.sql.optimizer.datasourceV2ExprFolding`, which is true by default). 
`CREATE TABLE` analyzes the expression in its own session, so with ANSI mode 
off an invalid cast is folded to `NULL` and an integer overflow to the wrapped 
value. Since this line now prefers the model, the strict analysis with ANSI 
mode on never sees the original expression. For example:
   
   ```sql
   SET spark.sql.ansi.enabled=false;
   CREATE TABLE testcat.t (a INT, b INT GENERATED ALWAYS AS (coalesce(a, 
CAST('x' AS INT))))
     USING foo;
   -- The stored model is COALESCE(a, NULL).
   SET spark.sql.ansi.enabled=true;
   INSERT INTO testcat.t(a) VALUES (NULL);  -- stores b = NULL
   ```
   
   At the base, auto-fill read the SQL text with ANSI mode on, so this `INSERT` 
failed with `CAST_INVALID_INPUT`. `coalesce(a, 2147483647 + 1)` stores 
`-2147483648` in the same way. The new entry in the migration guide covers the 
implicit casts that `CREATE TABLE` stores, as in the `'007'` example, and the 
`GenerationExpression` Javadoc says that a converted expression is analyzed 
with ANSI mode on. Neither says that a constant can keep the result of a 
non-ANSI evaluation, which is the kind of silent value that SPARK-60757 was 
meant to prevent. `spark.sql.legacy.useCurrentConfigsForGeneratedColumn` does 
not change it either.
   
   Could `toV2` build the model without folding, or under the settings that a 
write reads it with? If that is out of scope here, could the docs say that the 
constants of a model keep the semantics of the session that ran `CREATE TABLE`?



##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/GenerationExpression.java:
##########
@@ -26,10 +26,11 @@
  * Connectors can define generated columns using either a SQL string (Spark 
SQL dialect) or a more
  * portable connector {@link Expression expression}, whose semantics follow 
the ANSI SQL standard.
  * <p>
- * Spark computes a generated value on a write only from the SQL string, so a 
column without one is
- * not auto-filled. To check a provided value, Spark parses the SQL string if 
one is provided, also
- * when an expression is provided. Otherwise, Spark converts the given 
expression to its internal
- * representation.
+ * To compute a missing generated value or check a provided value, Spark first 
attempts to convert
+ * the connector expression to its internal representation. If the expression 
is absent or cannot
+ * be converted, Spark falls back to parsing the SQL string, if provided.

Review Comment:
   **[17] The public docs do not say that `Column.generationExpression()` now 
supplies the SQL fallback.**
   
   In the latest commit, `GeneratedColumn.columnGenerationExpression` takes the 
SQL text from the legacy getter `Column.generationExpression()` when 
`columnGenerationExpression()` returns only a model. So a connector that 
overrides both gets the SQL fallback described here. Only the scaladoc of that 
internal helper says so. The Javadoc of `Column.generationExpression()` still 
says that it "returns only the SQL string form" and points to this class, and 
this paragraph says only "the SQL string, if provided", which reads as 
`getSql()` of this object.
   
   Could this paragraph, or the `Column.generationExpression()` Javadoc, say 
that Spark also takes the SQL string from `Column.generationExpression()` when 
this object has none?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/StoredExpressionText.scala:
##########
@@ -97,24 +103,53 @@ object StoredExpressionText {
       inSession: => E,
       input: Seq[Attribute],
       analyzer: LogicalPlan => LogicalPlan): E = {
+    val analyzed = try {
+      expressionFromPlan(expr, analyzePlan(expr, input, analyzer, 
conf(SQLConf.get)))
+    } catch {
+      case _: AnalysisException => None
+    }
+    analyzed.getOrElse(inSession)
+  }
+
+  /**
+   * Analyzes a modeled expression under fixed ANSI settings and reports 
errors without fallback.
+   */
+  def analyzeStrict[E <: Expression](
+      expr: E,
+      input: Seq[Attribute],
+      analyzer: LogicalPlan => LogicalPlan): E = {
+    val plan = analyzePlan(expr, input, analyzer, fixedConf(SQLConf.get))
+    // Check under the session's representation settings, including 
first-class CHAR/VARCHAR.
+    SimpleAnalyzer.checkAnalysis(plan)

Review Comment:
   **[16] An error from the strict analysis names neither the table nor the 
generated column.**
   
   `checkAnalysis` here reports an error against a synthetic plan, a `Project` 
of the expression over a `LocalRelation`, with an alias that is `value` or the 
column name. The message has that plan attached, but no table name and no hint 
that the expression is the stored generation expression of a column. For 
example, in the new test `modeled generation expression analysis failure does 
not fall back to SQL`, the write fails with `UNRESOLVED_COLUMN.WITH_SUGGESTION` 
for `missing`, which reads as if the `INSERT` itself referred to a missing 
column. Since a convertible model no longer falls back, such an error always 
comes from the stored metadata, and the user cannot fix it by changing the 
query.
   
   Could the strict path wrap these errors with the column and the table, as 
`toCatalyst` already does with `unsupportedTableOperationError` for an 
expression that cannot be converted?



##########
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. 
Validation already preferred modeled expressions, but analyzed them under the 
writing session 
 and compared against the expression before its cast to the column type 
(SPARK-61495).

Review Comment:
   **[15] This entry has no config to restore the previous behavior, and the 
legacy flag no longer applies to a convertible model.**
   
   This entry changes the values that a write stores in existing tables, but 
unlike the SPARK-60757 entry below it, it does not say how to get the previous 
behavior back. The next entry also says that 
`spark.sql.legacy.useCurrentConfigsForGeneratedColumn` "does not change 
auto-fill or validation of a convertible modeled expression". `CREATE TABLE` 
stores a model next to the SQL text whenever it can build one, so for most 
tables that Spark creates there is no switch at all.
   
   For example, take a table that `CREATE TABLE` created with ANSI mode on, 
with `b STRING GENERATED ALWAYS AS (coalesce(s, 1))`. With `s = '007'` and ANSI 
mode off, a Spark 4.3 write auto-filled `'007'` and accepted a provided 
`'007'`. With this PR, it stores `'7'`, and a provided `'007'` fails with 
`CHECK_CONSTRAINT_VIOLATION`. Setting the legacy flag does not bring either 
back.
   
   This is a different point from the [wording 
thread](https://github.com/apache/spark/pull/60368#discussion_r4546043995), 
which scoping the flag in this entry resolved. Could this entry say how to 
restore the previous behavior, for example with a legacy config that makes a 
write read the SQL text first, or with the existing flag also covering this 
case? If no such switch is intended, could the entry say so?



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/GeneratedColumnWriteSuite.scala:
##########
@@ -347,6 +364,402 @@ class GeneratedColumnWriteSuite extends QueryTest with 
DatasourceV2SQLBase {
     }
   }
 
+  gridTest("modeled generation expression auto-fill")(

Review Comment:
   **[18] Nit: 11 of the 17 tests that this PR adds or renames in this suite 
have no `SPARK-61495:` prefix.**
   
   Six of them use it, such as `SPARK-61495: modeled FLOOR and CEIL retain ANSI 
overflow behavior`. The other 11 are this test, the eight tests from `modeled 
generation expression keeps ANSI semantics` to `modeled generation expression 
respects the write capability`, `generation expression presence checks do not 
convert expressions`, and `modeled generation expression keeps the implicit 
casts of CREATE TABLE`, which replaces a `SPARK-60757:` test. The new tests in 
`V2ExpressionUtilsSuite` and `V2ResolveOutputRelationSuite` have no prefix 
either. Could they all use `SPARK-61495:`, so that the tests of this change can 
be found by the JIRA ID?



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