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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala:
##########
@@ -57,13 +56,45 @@ private[sql] class TableConstraintResolution(
       condition => v2Write.withNewQuery(Filter(condition, v2Write.query)))
   }
 
-  private def buildCatalystExpression(c: Check): Expression = {
-    Option(c.predicate())
-      .flatMap(V2ExpressionUtils.toCatalyst)
-      .getOrElse(StoredExpressionFunctions.qualifyBuiltinFunctions(
-        
catalogManager.v1SessionCatalog.parser.parseExpression(c.predicateSql())))
+  private def buildCheckInvariant(c: Check, query: LogicalPlan): Expression = {
+    Option(c.predicate()).flatMap(V2ExpressionUtils.toCatalyst) match {
+      case Some(expr) => toCheckInvariant(c, expr)
+      case None if 
SQLConf.get.getConf(SQLConf.USE_CURRENT_SQL_CONFIGS_FOR_CHECK_CONSTRAINT) =>
+        toCheckInvariant(c, parseCondition(c))
+      case None => readCheckInvariant(c, query)

Review Comment:
   Thank you. As you noted, the base branch already read such a text with the 
default value for every writer that does not set the config, so this PR makes 
every writer read it the same way. Comparing the column references would catch 
only a part of such constraints, and it would add a new write failure for 
constraints that a connector builds, so I documented it instead. The 
SPARK-61893 migration entry now says that such a constraint can accept rows 
that it rejected before, with an example, and how to add it again so that it 
reads the same under the default values.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckAnalysis.scala:
##########
@@ -1326,6 +1338,21 @@ trait CheckAnalysis extends LookupCatalog with 
QueryErrorsBase with PlanToString
     check(plan)
   }
 
+  /**
+   * Fails a DDL with a CHECK condition that means something else under the 
settings a later write
+   * reads it with. This covers a condition with a predicate too, because a 
connector may store only
+   * the text.
+   */
+  private def failIfSessionDependent(condition: String, node: TreeNode[_]): 
Unit = {
+    if (!conf.getConf(SQLConf.USE_CURRENT_SQL_CONFIGS_FOR_CHECK_CONSTRAINT) &&
+        
!StoredExpressionText.readsAsInSession(catalogManager.v1SessionCatalog.parser, 
condition,

Review Comment:
   Good catch. Fixed. The DDL check no longer compares the values of datetime 
literals. The settings that a datetime literal depends on, such as the session 
time zone and `spark.sql.timestampType`, are those of the session in both 
parses, so only the clock can differ. The comparison for generation expressions 
and for the predicate decision of SPARK-60032 is unchanged. I added `TIMESTAMP 
'now'` to the acceptance test.
   



##########
docs/sql-migration-guide.md:
##########
@@ -97,6 +97,7 @@ license: |
 - Since Spark 4.4, `CREATE TABLE` and `REPLACE TABLE` fail with 
`UNSUPPORTED_EXPRESSION_GENERATED_COLUMN` when the data type of a generation 
expression names its struct fields differently from the column type, in name, 
including letter case, or in order, for example `named_struct('y', a, 'x', b)`, 
`named_struct('X', b, 'Y', a)`, or `struct(a, b)` for a `STRUCT<x: INT, y: 
INT>` column. Previously, such an expression was accepted, although Spark lines 
up the struct fields by name, with the case sensitivity of the writing session, 
when it computes the value of a generated column of a Data Source V2 table, and 
by position when it checks a provided value (SPARK-60857). To line up the 
fields by position, cast the expression to the column type, for example 
`CAST(struct(a, b) AS STRUCT<x: INT, y: INT>)`. Existing tables with such an 
expression are not rejected, and this change does not affect writes to them.
 - Since Spark 4.4, `ALTER TABLE ... ADD CONSTRAINT` with a CHECK constraint 
fails with `EXPECT_TABLE_NOT_VIEW.NO_ALTERNATIVE` when the target is a view, as 
it does with the other constraint types. Previously, when the view only 
projected or filtered a Data Source V2 table, the statement added the 
constraint to that table after validating only the rows of the view 
(SPARK-60822). To add the constraint, run the statement on the table.
 - Since Spark 4.4, a write to a Data Source V2 table that parses the SQL text 
of a CHECK constraint binds an unqualified built-in function name to 
`system.builtin`, regardless of the SQL path and 
`spark.sql.functionResolution.sessionOrder` (SPARK-60777). Previously, an 
existing constraint could call another function with the same name.
+- 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`, 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 co
 ndition cannot evaluate under ANSI mode, and an existing constraint that was 
created with such a config now reads with its default value. `CREATE TABLE`, 
`REPLACE TABLE`, and `ALTER TABLE ... ADD CONSTRAINT` fail with 
`SESSION_DEPENDENT_CHECK_CONSTRAINT` on a condition that means something else 
under those default values, and a condition that cannot 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`.

Review Comment:
   Thank you. I updated the SPARK-60757 and SPARK-60032 entries and the 
`CheckConstraint.withPredicateDecision` Scaladoc.
   



##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/constraints/Check.java:
##########
@@ -68,6 +68,14 @@ private Check(
    * This is the canonical representation of the condition and is always 
present (never
    * {@code null}). The optional {@link #predicate()} provides a structured 
form, except in the
    * cases that method lists.
+   * <p>
+   * When a write cannot use {@link #predicate()}, Spark reads the condition 
from this text. It
+   * 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 {@code 
spark.sql.parser.escapedStringLiterals}, regardless of
+   * the session of the write. Only the session time zone, case sensitivity, 
timestamp type and

Review Comment:
   Thank you. I added the functions found through `SET PATH` and the configs 
that an expression reads during evaluation.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala:
##########
@@ -57,13 +56,45 @@ private[sql] class TableConstraintResolution(
       condition => v2Write.withNewQuery(Filter(condition, v2Write.query)))
   }
 
-  private def buildCatalystExpression(c: Check): Expression = {
-    Option(c.predicate())
-      .flatMap(V2ExpressionUtils.toCatalyst)
-      .getOrElse(StoredExpressionFunctions.qualifyBuiltinFunctions(
-        
catalogManager.v1SessionCatalog.parser.parseExpression(c.predicateSql())))
+  private def buildCheckInvariant(c: Check, query: LogicalPlan): Expression = {
+    Option(c.predicate()).flatMap(V2ExpressionUtils.toCatalyst) match {
+      case Some(expr) => toCheckInvariant(c, expr)
+      case None if 
SQLConf.get.getConf(SQLConf.USE_CURRENT_SQL_CONFIGS_FOR_CHECK_CONSTRAINT) =>
+        toCheckInvariant(c, parseCondition(c))
+      case None => readCheckInvariant(c, query)
+    }
+  }
+
+  private def toCheckInvariant(c: Check, unresolvedExpr: Expression): 
CheckInvariant = {
+    val columnExtractors = mutable.Map[String, Expression]()
+    buildColumnExtractors(unresolvedExpr, columnExtractors)
+    CheckInvariant(unresolvedExpr, columnExtractors.toSeq, c.name, 
c.predicateSql)
+  }
+
+  /**
+   * Reads a CHECK condition from its text, independently of the settings of 
the writer. Only the
+   * condition is analyzed under the fixed settings, and the query of the 
write is not analyzed
+   * again. The result is resolved against the same attributes as the query, 
so it can go to the
+   * [[Filter]] above the query as it is.
+   */
+  private def readCheckInvariant(c: Check, query: LogicalPlan): Expression = {
+    try {
+      val analyzed = 
SQLConf.withExistingConf(StoredExpressionText.fixedConf(SQLConf.get)) {
+        analyze(Filter(toCheckInvariant(c, parseCondition(c)), 
LocalRelation(query.output)))
+      }
+      // Check under the session's representation settings, as `analyzeStrict` 
does.
+      SimpleAnalyzer.checkAnalysis(analyzed)

Review Comment:
   Thank you. I added a test that writes under both configs to `CHAR` and 
`VARCHAR` columns with a condition read from its text. It fails if 
`checkAnalysis` runs under the fixed settings.
   



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/CheckConstraintSuite.scala:
##########
@@ -609,7 +613,7 @@ class CheckConstraintSuite extends QueryTest with 
CommandSuiteBase with DDLComma
     // A write with `spark.sql.variable.substitute` replaces the placeholder.
     withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
       sql(s"CREATE TABLE $t (id INT, path STRING, ts TIMESTAMP) $defaultUsing")
-      withSQLConf(SQLConf.VARIABLE_SUBSTITUTE_ENABLED.key -> "false") {
+      withSQLConf(SQLConf.VARIABLE_SUBSTITUTE_ENABLED.key -> "false", legacy) {

Review Comment:
   Thank you. I added a `${...}` case with 
`spark.sql.variable.substitute=false` to the rejection test. It fails if the 
check compares the parses of `CatalystSqlParser`.
   



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