LuciferYang commented on code in PR #60549:
URL: https://github.com/apache/spark/pull/60549#discussion_r4639137139


##########
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:
   Done as `SpecialDatetimeValues.withEpochValues`, which `build()` calls: 
`CAST('epoch' AS DATE) - 1` folds, and `DEFAULT CAST('epoch' AS DATE) + 1` gets 
the literal 1970-01-02. Two differences from the suggestion:
   
   - It works top-down and does not look into another cast of a constant string 
to a datetime type, since the rule reads that string first. With `transformUp`, 
`CHECK (d <= CAST(CASE WHEN CAST('epoch' AS DATE) IS NULL THEN 'today' ELSE 
'2000-01-01' END AS DATE))` stored `d <= DATE'2000-01-01'`, while ALTER TABLE 
with ANSI mode off reads the outer cast as 'today'.
   - It keeps an expression that `ConstantFolding` failed to fold. A filter 
keeps such a cast when its string becomes constant only in the optimizer, as in 
`CASE WHEN id > 0 THEN CAST(s AS DATE) ... END` over `'epoch' AS s`. With the 
previous commit it was pushed as 1970-01-01, while Spark fails under ANSI mode.
   
   The tests check both.
   



##########
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:
   `ADD COLUMNS` is in the guide and the description now, and the test checks 
the default value of the `AddColumn` change for `ADD COLUMN h DATE DEFAULT 
CAST('today' AS DATE)`. I left `REPLACE COLUMNS` out: its parser rejects a 
DEFAULT value with `UNSUPPORTED_DEFAULT_VALUE.WITHOUT_SUGGESTION` 
(`AstBuilder.visitHiveReplaceColumns`, tested in 
`AlterTableReplaceColumnsSuite`), so it never reaches `getV2Default`.
   



##########
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:
   Done with your wording: "a generated column keeps its stored generation 
expression until the table is created again."
   



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