spark-test commented on code in PR #60637:
URL: https://github.com/apache/spark/pull/60637#discussion_r4607537715
##########
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:
**Blocking (P1):** When the stored predicate cannot be converted back, this
branch now reads `predicateSql` under the fixed settings and never compares the
result with that predicate. For a constraint stored before this change under a
non-default parser config, the two can disagree.
Example, from reading the code: on the base branch, a session with
`spark.sql.ansi.doubleQuotedIdentifiers=true` runs `CREATE TABLE t (id INT, s
STRING, CONSTRAINT c CHECK (upper("s") <> 'X'))`. The stored predicate applies
`UPPER` to column `s`, which `V2ExpressionUtils.toCatalyst` cannot convert
back, and `INSERT INTO t VALUES (1, 'x')` in that session fails with
`CHECK_CONSTRAINT_VIOLATION`. With this change, every write in any session
reads `"s"` as the string `'s'`, checks `upper('s') <> 'X'`, which is always
true, and stores the row without an error.
That turns an explicit failure into silently stored rows that violate the
constraint, the problem this PR fixes for other writers. Generation expressions
also give existing tables the default reading, as their migration entry states,
but a CHECK constraint exists only to reject rows, and here the stored
predicate records which names the DDL read as columns, so the write has what it
needs to notice at least this case.
**Recommended change:** When a constraint has a stored predicate that
toCatalyst cannot convert back, compare the top-level columns that the
predicate references with the columns that the fixed reading of predicateSql
references, and fail the write with a new error condition that names the
constraint, its condition and the missing columns when the predicate references
a column that the reading does not. In the SPARK-61893 migration entry,
document the new error, and state that an existing constraint created with a
non-default value of a config that changes how its text reads can, when a write
reads its text, accept rows that it rejected before, and that such a constraint
should be dropped and added again with a condition that reads the same under
the default values. Add a comment at the comparison that names the mismatches
it cannot detect, and add write tests for such a constraint.
**Why this works:** The stored predicate was built from the DDL's own
analysis, so its column references record which names the DDL read as columns.
A text that the default configs read in a way that turns such a column into a
literal, such as a double-quoted name read as a string, loses that reference,
and detecting the loss turns a silent misreading into an explicit failure; a
reading that keeps or adds references passes, so predicates that the optimizer
simplified at ALTER TABLE raise no false alarm.
**Compatibility:** Constraints that this PR reads correctly, including every
constraint whose predicate converts back and every constraint without a
predicate, are enforced exactly as with this PR.
**Risks:** A connector that stores a predicate whose columns do not match
its text, an inconsistent constraint, now fails every write to that table;
setting spark.sql.legacy.useCurrentConfigsForCheckConstraint restores the base
branch's reading. Each write with such a constraint also walks the predicate's
references once, a negligible planning cost. A mismatch that leaves the
referenced columns unchanged is still enforced as the default reading without
an error; only the migration entry and the comment at the comparison warn about
it.
**Constraints:** Compare column names with the writer's resolver, since case
sensitivity follows the writer's session. Skip the comparison under
spark.sql.legacy.useCurrentConfigsForCheckConstraint, so that the legacy path
stays identical to the base branch. Leave constraints without a predicate, and
constraints whose predicate converts back, exactly as this PR reads them.
**Exclusions:**
- A mismatch that leaves the referenced columns unchanged, such as a
backslash in a string created under
spark.sql.parser.escapedStringLiterals=true, and a constraint stored without a
predicate are not detected, because comparing literal values would reject valid
writes whose values follow the writer on purpose, such as a timestamp literal
read in the time zone of the writer; the migration entry and the comment at the
comparison name them instead.
**Verification:**
- **Regression:** A write to a table whose CHECK constraint has predicateSql
upper("s") <> 'X' and a stored predicate that applies UPPER to column s, added
through the catalog API or by a session with
spark.sql.ansi.doubleQuotedIdentifiers=true and
spark.sql.legacy.useCurrentConfigsForCheckConstraint set to true, fails with
the new error naming the constraint, and the table stays empty.
- **Behavior:** Writes to text-read constraints whose stored predicate
references only columns that the text also references, including ALTER TABLE
constraints whose predicate the optimizer simplified, keep accepting valid rows
and rejecting violating ones.
- **Compatibility:** With
spark.sql.legacy.useCurrentConfigsForCheckConstraint set to true, a write to
such a constraint behaves as on the base branch.
- **Inspection:** The SPARK-61893 migration entry says that an existing
constraint created with a non-default value of a config that changes how its
text reads can accept rows that it rejected before, names the new error, and
says how to add such a constraint again so that it reads the same under the
default values.
##########
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)) {
Review Comment:
**Non-blocking (P2):** `fixedConf` starts from a new `SQLConf` and keeps
only the retained resolution configs and a few named settings, so
`spark.sql.timeType.enabled`, which is internal, has no binding and defaults to
`Utils.isTesting`, is off in this nested analysis outside tests. From reading
the code, in a session that enables the TIME type, a table with `CONSTRAINT c
CHECK (hour(start_t) BETWEEN 6 AND 22)` on a `TIME` column then fails every
write: `hour()` builds `HoursOfTime`, whose `checkInputDataTypes` throws
`UNSUPPORTED_TIME_TYPE`, which surfaces as `UNRESOLVABLE_CHECK_CONSTRAINT`. On
the base branch the condition resolves in the writer's session and is enforced.
The setting decides whether the type exists, not how the text reads, so
resetting it protects nothing. The tests do not see this because the flag
defaults to true under `Utils.isTesting`.
**Recommended change:** Make StoredExpressionText.fixedConf keep the
session's value of spark.sql.timeType.enabled next to the time zone, case
sensitivity, timestamp type and decimal precision loss, and name it among the
settings that follow the session in the StoredExpressionText.conf Scaladoc, the
Check.predicateSql() Javadoc, and both the generation-expression entry and the
SPARK-61893 entry of the Spark 4.4 migration guide, since generation
expressions are read under the same settings.
**Why this works:** The setting decides whether the TIME type exists, not
how a text reads, so keeping the session's value lets a condition that the
writer's session resolves resolve under the fixed settings too, while every
config that changes the reading still takes its default value.
**Risks:** A generation expression with a TIME expression that the fixed
settings could not resolve fell back to the session of the writer; it is now
read under the fixed settings, so in a session with ANSI mode off or another
non-default analysis config its value can change to the reading that every
other generation expression already gets, and
spark.sql.legacy.useCurrentConfigsForGeneratedColumn still reads it under the
session. A modeled TIME expression that failed with
INVALID_GENERATED_COLUMN_EXPRESSION now resolves.
**Constraints:** Copy only the TIME type setting; every config that changes
how a text reads keeps its default value in the fixed settings.
**Exclusions:**
- Analysis-time feature gates other than the type gates are not audited
here; each needs the same judgment of whether it changes how a text reads.
**Verification:**
- **Regression:** With the TIME type enabled in the writing session, a CHECK
condition that a write reads from its text and that applies hour() to a TIME
column accepts a valid row and rejects a violating row with
CHECK_CONSTRAINT_VIOLATION.
- **Compatibility:** The fixed settings take the session's value of
spark.sql.timeType.enabled for both values, which a test can observe by setting
the session value to false, away from the test default, while every other
non-session config keeps its default.
- **Inspection:** The StoredExpressionText.conf Scaladoc, the
Check.predicateSql() Javadoc and the generation-expression and SPARK-61893
entries of the Spark 4.4 migration guide list spark.sql.timeType.enabled among
the settings that follow the session.
##########
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:
**Blocking (P1):** This check compares two parses of the condition with
`==`, but the parser computes a typed special datetime literal from the clock
while it builds it (`AstBuilder.constructTimestampLTZLiteral`,
`DateTimeUtils.convertSpecialTimestamp`). So, from reading the code, in a
session with every config at its default, `ALTER TABLE t ADD CONSTRAINT c CHECK
(ts <= TIMESTAMP 'now')` gets two literals holding two different microseconds,
the trees differ, and the DDL fails with `SESSION_DEPENDENT_CHECK_CONSTRAINT`,
telling the user to reset configs that are already at their defaults. The same
holds for `CREATE TABLE` and `REPLACE TABLE`, and for `TIMESTAMP_LTZ 'now'` and
`TIMESTAMP_NTZ 'now'`; `DATE 'today'`, `'tomorrow'` and `'yesterday'` fail only
when the two parses straddle midnight, so the same statement fails
intermittently. The base branch accepts these DDLs and enforces the constraint.
The SPARK-60032 tests use `CAST('now' AS TIMESTAMP)`, which the parser does not
eval
uate, so the suite does not catch this.
**Verification:**
- **Regression:** In a session with default configs, a CHECK DDL whose
condition contains a typed TIMESTAMP 'now' or DATE 'today' literal succeeds
through CREATE TABLE and ALTER TABLE, and a write of a row that violates the
stored condition fails with CHECK_CONSTRAINT_VIOLATION.
- **Behavior:** A CHECK condition that reads differently under the default
parser configs, such as one with a backslash in a string under
spark.sql.parser.escapedStringLiterals=true, is still rejected by CREATE TABLE
and ALTER TABLE.
- **Compatibility:** The comparison used for generation expressions and for
the ALTER TABLE predicate decision still treats two parses whose datetime
literal values differ as different.
##########
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:
**Nit (P3):** This paragraph says that "Only" these settings follow the
writer's session, but the migration entry for this change at
docs/sql-migration-guide.md line 100 also lists the functions found through
`SET PATH` and the configs that an expression reads during evaluation, and both
hold in the code: only built-in function names are bound to `system.builtin`,
and configs read after the fixed-settings analysis, such as
`spark.sql.legacy.timeParserPolicy` for a datetime formatter, come from the
writer. A connector that builds a condition such as `to_date(s, 'yyyy-MM-dd')
IS NOT NULL` from this Javadoc would not expect its result to depend on the
writer's settings.
**Verification:**
- **Inspection:** The Javadoc's list of settings that follow the writer's
session contains every item of the migration entry's list.
##########
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:
**Nit (P3):** Adding the legacy config here keeps this case on the
SPARK-60032 fallback, but this was the only test that reaches a `${...}`
placeholder with `spark.sql.variable.substitute=false`, and the legacy config
skips the new DDL check. The new rejection test uses only
`escapedStringLiterals` and `doubleQuotedIdentifiers`, which change
`CatalystSqlParser`'s output too. Only the session parser substitutes
variables, so `${...}` is the one input for which comparing with it rather than
with `CatalystSqlParser` decides the result: if the check compared with
`CatalystSqlParser`, `ALTER TABLE t ADD CONSTRAINT c CHECK (upper(path) <>
'${spark.sql.session.timeZone}')` would be accepted, every write would read the
text with the placeholder replaced, and no test would fail.
**Verification:**
- **Regression:** With variable substitution off and the legacy config at
its default, CREATE TABLE and ALTER TABLE with a CHECK condition that keeps a
${...} placeholder are rejected with SESSION_DEPENDENT_CHECK_CONSTRAINT and
leave no constraint, so the assertion fails if the check compared parses with a
parser that does not substitute variables.
##########
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:
**Nit (P3):** Running `SimpleAnalyzer.checkAnalysis` outside the
fixed-settings block matters only when the writer enables
`spark.sql.preserveCharVarcharTypeInfo` or
`spark.sql.charVarchar.standardSemantics.enabled`: then `query.output` keeps
`CHAR`/`VARCHAR` types, and under the fixed settings `CheckAnalysis` would
throw an internal error for that leaf. No CHECK test writes under either
config; 'Create table with check constraint: char/varchar type' only creates
the table, although a write reads its `LENGTH(name) > 0` from text. So moving
this call into the fixed block would fail every such write with no failing
test, and no test shows that a condition such as `upper(c) = 'A'` on a `CHAR`
column resolves and pads under the fixed settings as it does in the writer's
session.
**Verification:**
- **Regression:** Under each first-class CHAR/VARCHAR config and for both
CHAR and VARCHAR, a write to a table with a text-read CHECK condition,
including one that applies a string function to the column, stores a valid row
and fails on a violating row with CHECK_CONSTRAINT_VIOLATION, so the test fails
with an internal error if the analysis check ran under the fixed settings.
##########
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:
**Non-blocking (P2):** With this entry, two older entries of the same Spark
4.4 section become false under the default settings. The generation-expression
entry at docs/sql-migration-guide.md line 93 still says "A table CHECK
constraint that reads SQL text still uses the session that writes", and the
SPARK-60032 entry at docs/sql-migration-guide.md line 102 still says that each
write parses and analyzes the text under its own session and that conditions
whose text the parser settings of the `ALTER TABLE` read differently from their
default values are stored as before, while such an `ALTER TABLE` now fails with
`SESSION_DEPENDENT_CHECK_CONSTRAINT`. The
`CheckConstraint.withPredicateDecision` Scaladoc at constraints.scala line 170
also still says that a write parses the condition again with its own settings.
Each of these now describes only the behavior under
`spark.sql.legacy.useCurrentConfigsForCheckConstraint`, without saying so.
**Verification:**
- **Inspection:** Every statement of the Spark 4.4 migration section and of
the withPredicateDecision Scaladoc about how a write reads a CHECK text, and
about which ALTER TABLE conditions are stored as before, agrees with the
SPARK-61893 entry or is explicitly scoped to
spark.sql.legacy.useCurrentConfigsForCheckConstraint.
--
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]