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


##########
docs/sql-migration-guide.md:
##########
@@ -101,6 +101,7 @@ license: |
 - Since Spark 4.4, a write to a Data Source V2 table that checks a CHECK 
constraint through its SQL text parses and analyzes the text with ANSI mode on 
and the default values of the SQL configs that change how a text reads, such as 
`spark.sql.parser.escapedStringLiterals` and 
`spark.sql.ansi.doubleQuotedIdentifiers`, regardless of the session of the 
write. As for a generation expression, only the session time zone, case 
sensitivity, `spark.sql.timestampType`, 
`spark.sql.decimalOperations.allowPrecisionLoss`, `spark.sql.timeType.enabled`, 
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 still follow that session. Previously, the session of the 
write decided how the text read, so a write could store rows that violate the 
constraint (SPARK-61893). As a result, with `spark.sql.ansi.enabled=false`, a 
write can fail with an error such as `CAST_INVALID_INPUT` or `ARITHMETIC_
 OVERFLOW` on a row that the condition cannot evaluate under ANSI mode. An 
existing constraint that was created with a non-default value of such a config 
now reads with the default value, without an error, so it can accept rows that 
it rejected before. For example, `upper("s") <> 'X'` created with 
`spark.sql.ansi.doubleQuotedIdentifiers=true` now reads `"s"` as a string and 
accepts every row. To keep such a constraint, drop it and add it again with a 
condition that reads the same under the default values, such as `upper(s) <> 
'X'`. `CREATE TABLE`, `REPLACE TABLE`, and `ALTER TABLE ... ADD CONSTRAINT` 
fail with `SESSION_DEPENDENT_CHECK_CONSTRAINT` on a condition that the parser 
reads differently under those default values. This comparison takes ANSI mode 
from the session, so with `spark.sql.ansi.enabled=false` these statements can 
still add a condition that a write reading its text analyzes differently or 
cannot resolve, such as `flag = 1` on a `BOOLEAN` column. A condition that canno
 t be parsed or resolved on a write fails with `UNRESOLVABLE_CHECK_CONSTRAINT`, 
which names the constraint. To restore the previous behavior, set 
`spark.sql.legacy.useCurrentConfigsForCheckConstraint` to `true`.
 - Since Spark 4.4, `CREATE TABLE`, `REPLACE TABLE`, and `ALTER TABLE ... ADD 
CONSTRAINT` on a Data Source V2 table fail with `SUBQUERY_IN_CHECK_CONSTRAINT` 
when the condition of a CHECK constraint contains a subquery. `ALTER TABLE ... 
ADD CONSTRAINT` keeps failing with 
`UNSUPPORTED_SUBQUERY_EXPRESSION_CATEGORY.HIGHER_ORDER_FUNCTION` on a subquery 
in a lambda function. Previously, most of these statements failed with 
`INTERNAL_ERROR`, but a subquery that needed no resolution, such as `id > 
(SELECT 0 AS a)`, was accepted and every write evaluated it again 
(SPARK-60781). Existing constraints that contain a subquery are not rejected.
 - Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT` 
adds to a Data Source V2 table, and whose condition reads the current time, 
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db = 
current_database()`, is checked against their values at the time of each write. 
Previously, it was checked against their values at the time of the `ALTER 
TABLE`, unless a write could not read back a predicate for its condition, such 
as one with a lambda function or one that passes a column to `datediff`, `year` 
or `upper` (SPARK-60032). Such a constraint is stored without a predicate, so 
each write parses and analyzes its SQL text, as it does for a constraint 
without a predicate that `CREATE TABLE` adds (SPARK-61893). With 
`spark.sql.legacy.useCurrentConfigsForCheckConstraint`, a write does so under 
its own session, and a setting of the write such as 
`spark.sql.ansi.enforceReservedKeywords`, which reserves `TIME`, or 
`spark.sql.ansi.doubleQuotedIdentifiers
 ` can then make it fail to parse the text or read it differently. A row-level 
operation that copies unchanged rows, such as a `DELETE` or `UPDATE` on a 
copy-on-write table, fails with `CHECK_CONSTRAINT_VIOLATION` on a copied row 
that no longer satisfies the condition. For example, `ts >= current_timestamp() 
- INTERVAL 30 DAYS` now fails such a `DELETE` once a copied row is older than 
30 days. A condition that Spark detects a write could resolve differently is 
stored as before, so a write accepts and rejects the same rows for it as 
before. Examples are conditions that also read a variable, a `CHAR` column, a 
name with more than one part such as a column qualified by the table name, or a 
constant that depends on the session time zone, such as `'2024-01-01 00:00:00'` 
cast to a timestamp. So are conditions with a name such as `current_date` or 
`user` without parentheses, which a write can read as a column name. A 
condition whose text the parser settings of the `ALTER TABLE`, such as `sp
 ark.sql.ansi.doubleQuotedIdentifiers` or 
`spark.sql.parser.escapedStringLiterals`, read differently from their default 
values fails with `SESSION_DEPENDENT_CHECK_CONSTRAINT` (SPARK-61893), and is 
stored as before only with 
`spark.sql.legacy.useCurrentConfigsForCheckConstraint`. ANSI mode, 
`spark.sql.timestampType` and the session time zone are taken from the session 
for this comparison, as for a generation expression. A condition that reads the 
current date or time only through a typed literal such as `DATE 'today'` is 
also stored as before. An existing constraint keeps its stored predicate until 
it is dropped and added again. `Check.predicate()` is null for a constraint 
stored without a predicate, so a connector that validates or enforces it itself 
has to evaluate `Check.predicateSql()`. To restore the previous behavior, set 
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding 
the constraint. A constraint added without it is not changed.
+- Since Spark 4.4, a CHECK constraint, a DEFAULT value or a generation 
expression of a Data Source V2 table on a cast of a special datetime value, 
such as `d <= CAST('today' AS DATE)` or `d <= 'today'` for a `DATE` column `d`, 
is checked or computed at each write. Previously, for a cast to `DATE` or 
`TIMESTAMP_NTZ`, `CREATE TABLE`, `REPLACE TABLE` and `ALTER TABLE ... ALTER 
COLUMN ... SET DEFAULT` failed with `CAST_INVALID_INPUT` when 
`spark.sql.ansi.enabled` was `true`. When it was `false`, they stored the 
predicate `d <= NULL`, which accepts every row, or a `NULL` default value or 
generation expression, so a write stored `NULL` (SPARK-60451). A table created 
this way keeps what it stored until the constraint is dropped and added again 
or the default value is set again, and a generated column keeps its stored 
generation expression. Rows that are already stored keep their values, and data 
derived from them may need to be recomputed. For a special value other than 
`'epoch'`, `Check.p
 redicate()` and the expressions of `ColumnDefaultValue` and 
`GenerationExpression` are null, so a connector that validates or enforces them 
itself has to evaluate their SQL text.

Review Comment:
   **[8] `ADD COLUMNS` and `REPLACE COLUMNS` are fixed too, but the guide does 
not list them.**
   
   The guide lists `CREATE TABLE`, `REPLACE TABLE` and `ALTER TABLE ... ALTER 
COLUMN ... SET DEFAULT`. `AddColumns` and `ReplaceColumns` build the V2 default 
value through the same `DefaultValueExpression.toV2` 
(`QualifiedColType.getV2Default`, `v2AlterTableCommands.scala:133` and 
`v2AlterTableCommands.scala:171`). So before this PR, `ALTER TABLE t ADD COLUMN 
c DATE DEFAULT CAST('today' AS DATE)` also failed with `CAST_INVALID_INPUT` 
under ANSI mode. With ANSI mode off, it stored a `NULL` current default value, 
so a later write that omits `c` wrote `NULL`.
   
   Could the guide and the PR description list them too, so that the users of 
such a table know that it is affected and that setting the default value again 
fixes it? A test in `DataSourceV2DataFrameSuite` would also keep this path 
fixed, for example by checking the default value of the `AddColumn` change of 
the executed `AlterTableExec`, as the new test does for `ALTER COLUMN`.



##########
docs/sql-migration-guide.md:
##########
@@ -101,6 +101,7 @@ license: |
 - Since Spark 4.4, a write to a Data Source V2 table that checks a CHECK 
constraint through its SQL text parses and analyzes the text with ANSI mode on 
and the default values of the SQL configs that change how a text reads, such as 
`spark.sql.parser.escapedStringLiterals` and 
`spark.sql.ansi.doubleQuotedIdentifiers`, regardless of the session of the 
write. As for a generation expression, only the session time zone, case 
sensitivity, `spark.sql.timestampType`, 
`spark.sql.decimalOperations.allowPrecisionLoss`, `spark.sql.timeType.enabled`, 
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 still follow that session. Previously, the session of the 
write decided how the text read, so a write could store rows that violate the 
constraint (SPARK-61893). As a result, with `spark.sql.ansi.enabled=false`, a 
write can fail with an error such as `CAST_INVALID_INPUT` or `ARITHMETIC_
 OVERFLOW` on a row that the condition cannot evaluate under ANSI mode. An 
existing constraint that was created with a non-default value of such a config 
now reads with the default value, without an error, so it can accept rows that 
it rejected before. For example, `upper("s") <> 'X'` created with 
`spark.sql.ansi.doubleQuotedIdentifiers=true` now reads `"s"` as a string and 
accepts every row. To keep such a constraint, drop it and add it again with a 
condition that reads the same under the default values, such as `upper(s) <> 
'X'`. `CREATE TABLE`, `REPLACE TABLE`, and `ALTER TABLE ... ADD CONSTRAINT` 
fail with `SESSION_DEPENDENT_CHECK_CONSTRAINT` on a condition that the parser 
reads differently under those default values. This comparison takes ANSI mode 
from the session, so with `spark.sql.ansi.enabled=false` these statements can 
still add a condition that a write reading its text analyzes differently or 
cannot resolve, such as `flag = 1` on a `BOOLEAN` column. A condition that canno
 t be parsed or resolved on a write fails with `UNRESOLVABLE_CHECK_CONSTRAINT`, 
which names the constraint. To restore the previous behavior, set 
`spark.sql.legacy.useCurrentConfigsForCheckConstraint` to `true`.
 - Since Spark 4.4, `CREATE TABLE`, `REPLACE TABLE`, and `ALTER TABLE ... ADD 
CONSTRAINT` on a Data Source V2 table fail with `SUBQUERY_IN_CHECK_CONSTRAINT` 
when the condition of a CHECK constraint contains a subquery. `ALTER TABLE ... 
ADD CONSTRAINT` keeps failing with 
`UNSUPPORTED_SUBQUERY_EXPRESSION_CATEGORY.HIGHER_ORDER_FUNCTION` on a subquery 
in a lambda function. Previously, most of these statements failed with 
`INTERNAL_ERROR`, but a subquery that needed no resolution, such as `id > 
(SELECT 0 AS a)`, was accepted and every write evaluated it again 
(SPARK-60781). Existing constraints that contain a subquery are not rejected.
 - Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT` 
adds to a Data Source V2 table, and whose condition reads the current time, 
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db = 
current_database()`, is checked against their values at the time of each write. 
Previously, it was checked against their values at the time of the `ALTER 
TABLE`, unless a write could not read back a predicate for its condition, such 
as one with a lambda function or one that passes a column to `datediff`, `year` 
or `upper` (SPARK-60032). Such a constraint is stored without a predicate, so 
each write parses and analyzes its SQL text, as it does for a constraint 
without a predicate that `CREATE TABLE` adds (SPARK-61893). With 
`spark.sql.legacy.useCurrentConfigsForCheckConstraint`, a write does so under 
its own session, and a setting of the write such as 
`spark.sql.ansi.enforceReservedKeywords`, which reserves `TIME`, or 
`spark.sql.ansi.doubleQuotedIdentifiers
 ` can then make it fail to parse the text or read it differently. A row-level 
operation that copies unchanged rows, such as a `DELETE` or `UPDATE` on a 
copy-on-write table, fails with `CHECK_CONSTRAINT_VIOLATION` on a copied row 
that no longer satisfies the condition. For example, `ts >= current_timestamp() 
- INTERVAL 30 DAYS` now fails such a `DELETE` once a copied row is older than 
30 days. A condition that Spark detects a write could resolve differently is 
stored as before, so a write accepts and rejects the same rows for it as 
before. Examples are conditions that also read a variable, a `CHAR` column, a 
name with more than one part such as a column qualified by the table name, or a 
constant that depends on the session time zone, such as `'2024-01-01 00:00:00'` 
cast to a timestamp. So are conditions with a name such as `current_date` or 
`user` without parentheses, which a write can read as a column name. A 
condition whose text the parser settings of the `ALTER TABLE`, such as `sp
 ark.sql.ansi.doubleQuotedIdentifiers` or 
`spark.sql.parser.escapedStringLiterals`, read differently from their default 
values fails with `SESSION_DEPENDENT_CHECK_CONSTRAINT` (SPARK-61893), and is 
stored as before only with 
`spark.sql.legacy.useCurrentConfigsForCheckConstraint`. ANSI mode, 
`spark.sql.timestampType` and the session time zone are taken from the session 
for this comparison, as for a generation expression. A condition that reads the 
current date or time only through a typed literal such as `DATE 'today'` is 
also stored as before. An existing constraint keeps its stored predicate until 
it is dropped and added again. `Check.predicate()` is null for a constraint 
stored without a predicate, so a connector that validates or enforces it itself 
has to evaluate `Check.predicateSql()`. To restore the previous behavior, set 
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding 
the constraint. A constraint added without it is not changed.
+- Since Spark 4.4, a CHECK constraint, a DEFAULT value or a generation 
expression of a Data Source V2 table on a cast of a special datetime value, 
such as `d <= CAST('today' AS DATE)` or `d <= 'today'` for a `DATE` column `d`, 
is checked or computed at each write. Previously, for a cast to `DATE` or 
`TIMESTAMP_NTZ`, `CREATE TABLE`, `REPLACE TABLE` and `ALTER TABLE ... ALTER 
COLUMN ... SET DEFAULT` failed with `CAST_INVALID_INPUT` when 
`spark.sql.ansi.enabled` was `true`. When it was `false`, they stored the 
predicate `d <= NULL`, which accepts every row, or a `NULL` default value or 
generation expression, so a write stored `NULL` (SPARK-60451). A table created 
this way keeps what it stored until the constraint is dropped and added again 
or the default value is set again, and a generated column keeps its stored 
generation expression. Rows that are already stored keep their values, and data 
derived from them may need to be recomputed. For a special value other than 
`'epoch'`, `Check.p
 redicate()` and the expressions of `ColumnDefaultValue` and 
`GenerationExpression` are null, so a connector that validates or enforces them 
itself has to evaluate their SQL text.

Review Comment:
   **[9] nit: could the guide say how to fix an existing generated column?**
   
   For a CHECK constraint and a DEFAULT value, the guide says what fixes an 
existing table. For a generated column, it only says that the column keeps its 
stored generation expression. A table created by Spark 4.1 to 4.3 with ANSI 
mode off stores `LiteralValue(null)` for `GENERATED ALWAYS AS (CAST('today' AS 
DATE))`, and writes read that expression, so they keep writing `NULL`. `ALTER 
TABLE` cannot change a generation expression, and `ADD COLUMN` does not take 
one, so the only fix is to create the table again and copy its rows. Maybe 
something like "..., and a generated column keeps its stored generation 
expression until the table is created again."



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/V2ExpressionBuilder.scala:
##########
@@ -172,6 +172,11 @@ class V2ExpressionBuilder(e: Expression, isPredicate: 
Boolean = false) extends L
       } else {
         None
       }
+    // Only `SpecialDatetimeValues` gives such a cast its value. 'epoch' 
becomes its fixed value,
+    // and the others have no V2 form, like `current_date()`.
+    case c: Cast if c.specialDatetimeValue.isDefined =>

Review Comment:
   **[7] An expression that contains a cast of 'epoch' still does not fold.**
   
   Thank you for giving a cast of 'epoch' its value 
([1](https://github.com/apache/spark/pull/60549#discussion_r4623987828)). This 
case handles the cast itself, but an expression that contains one still gets no 
folded V2 form. `Cast.contextIndependentFoldable` is false for 'epoch' too, so 
its parents, such as `DateSub` and `DateAdd`, are not context independent 
either, and the folding case at L110 never sees them. For example:
   
   - `CREATE TABLE t (d DATE, CONSTRAINT c CHECK (d >= CAST('epoch' AS DATE) - 
1))` stores no predicate, because the builder does not translate `DateSub`. 
`ALTER TABLE ... ADD CONSTRAINT` with the same condition stores `d >= 
DATE'1969-12-31'`, since 'epoch' does not read the current date.
   - `DEFAULT CAST('epoch' AS DATE) - 1` has no V2 expression, and `DEFAULT 
CAST('epoch' AS DATE) + 1` becomes a `DATE_ADD` call on `LiteralValue(0, 
DateType)` instead of a date literal.
   
   The results are still right, because a write reads the SQL text when there 
is no V2 form. But the same predicate for CREATE and ALTER TABLE, and "For 
'epoch' they hold its value" in the PR description, hold only for a cast that 
is not inside another expression. Could `build()` replace each cast of 'epoch' 
with its value once, before the translation? For example:
   
   ```scala
     def build(): Option[V2Expression] = generateExpression(withEpochValues(e), 
isPredicate)
   
     // Gives each cast of 'epoch' its value, so that the folding case also 
folds the expressions
     // around it.
     private def withEpochValues(expr: Expression): Expression =
       expr.transformUpWithPruning(_.containsPattern(CAST)) {
         case c: Cast =>
           c.specialDatetimeValue.flatMap(SpecialDatetimeValues.epochValue(_, 
c.dataType))
             .getOrElse(c)
       }
   ```
   
   Then the folding case folds `CAST('epoch' AS DATE) - 1` as it folds 
`DATE'1970-01-01' - 1`, and this case only has to return `None` for the other 
special values. The optimized plans whose filters the builder also translates 
no longer have such a cast, so they are not affected.



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