dongjoon-hyun commented on code in PR #59545:
URL: https://github.com/apache/spark/pull/59545#discussion_r4515521794
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/constraints.scala:
##########
@@ -194,6 +238,58 @@ case class CheckConstraint(
}
}
+object CheckConstraint {
+ /**
+ * Whether `e`, with its `RuntimeReplaceable`s replaced, reads the current
time, date, catalog,
+ * user and the like, which the optimizer replaces with their values. The
CURRENT_LIKE pattern
+ * stands in for `ReplaceCurrentLike`, which needs a `CatalogManager`, and
for the functions
+ * `ComputeCurrentTime` replaces. `ComputeCurrentTime` is still applied for
the casts from TIME
+ * to a timestamp it rewrites, which carry no CURRENT_LIKE bit.
+ */
+ private def readsCurrentContext(e: Expression): Boolean = {
+ val replaced = ReplaceExpressions.replace(e)
+ replaced.containsPattern(CURRENT_LIKE) ||
+ (ComputeCurrentTime.applyForExpression(replaced) ne replaced) ||
+ replaced.exists {
+ case c: Cast => castReadsCurrentDate(c)
+ case _ => false
+ }
+ }
+
+ /**
+ * Whether `cast` reads the current date: `SpecialDatetimeValues` replaces
it with the value of
+ * 'now', 'today', 'tomorrow' or 'yesterday', or it casts a string with only
a time part to a
+ * timestamp with local time zone, which completes it with the current date.
Only a cast of a
+ * constant string at the top level counts, not one into an array, map or
struct of timestamps,
+ * from a VARIANT, or of a string that only the optimizer makes constant.
+ */
+ private def castReadsCurrentDate(cast: Cast): Boolean = {
+ val completesTime = cast.dataType match {
+ case TimestampType | _: TimestampLTZNanosType => true
+ case _ => false
+ }
+ (completesTime || SpecialDatetimeValues.rewrites(cast.dataType)) &&
+ SpecialDatetimeValues.constantString(cast).exists { s =>
+ SpecialDatetimeValues.readsCurrentDate(s, cast.dataType) ||
+ (completesTime && DateTimeUtils.isTimeOnlyTimestamp(s))
+ }
+ }
+
+ /**
+ * Whether a write that parses the condition resolves `e` differently: `e`
reads a variable, which
+ * the write looks up in its own session, or a column whose type is or
contains CHAR, which the
+ * write reads without the CHAR type that pads the literals compared with
it. A user-defined
+ * function is rejected by `failIfCallsUserDefinedFunction`.
+ */
+ private def resolvesDifferentlyOnWrite(e: Expression): Boolean = {
Review Comment:
`resolvesDifferentlyOnWrite` does not account for the session time zone.
Once the predicate is omitted, a fixed datetime string (or a typed `TIMESTAMP`
literal) in the same condition as a current-time function is re-interpreted in
each writer's `spark.sql.session.timeZone`, instead of being fixed when the
constraint is added.
For example, in a UTC session:
```sql
ALTER TABLE t ADD CONSTRAINT c
CHECK (ts >= '2024-01-01 00:00:00' AND ts <= current_timestamp())
```
On master, the lower bound is stored as the fixed instant
`2024-01-01T00:00Z`. With this PR, a writer in `America/Los_Angeles` re-parses
it as `2024-01-01T08:00Z` and rejects rows with `ts` in `[00:00Z, 08:00Z)` that
UTC writers accept. Neither the detector nor the migration guide mentions this.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/constraints.scala:
##########
@@ -151,8 +155,48 @@ case class CheckConstraint(
}
}
+ // The two flags are printed only when set, so that the plan string of a
constraint without
+ // them stays as it was.
+ override def stringArgs: Iterator[Any] =
+ Iterator(child, condition, userProvidedName, tableName,
userProvidedCharacteristic) ++
+ Iterator("keepPredicate").filter(_ => keepPredicate) ++
+ Iterator("omitPredicate").filter(_ => omitPredicate)
+
+ /**
+ * Decides from the analyzed condition whether to store the constraint
without a predicate
+ * (`omitPredicate`). `AddCheckConstraint.storeAnalyzedQuery` calls this at
the end of the
+ * analysis of an ALTER TABLE.
+ *
+ * A write parses `condition` again, with its own settings. It cannot bind a
parameter marker
+ * that the legacy parameter substitution leaves there, resolves an
IDENTIFIER clause in its own
+ * session, and does not resolve a column qualified by the table name the
way ALTER TABLE does.
+ * It also resolves a name such as `current_date` or `user` to the function
or to a column,
+ * depending on its case sensitivity, its reserved keywords and the columns
of the table at that
+ * time. None of them can be told apart after analysis, so the parser sets
`keepPredicate` for
+ * them, and for any name with more than one part, since it cannot tell a
table qualifier from a
+ * struct column. Such a condition, or one that
`resolvesDifferentlyOnWrite`, keeps the predicate
+ * built from the optimized plan, as before. So does one that calls a
user-defined function,
+ * which the analysis rejects next and which is not evaluated here.
+ */
+ def withPredicateDecision(): CheckConstraint = copy(omitPredicate =
Review Comment:
This switches existing-style rolling-window constraints to per-write
evaluation unconditionally. For copy-on-write DELETE/UPDATE/MERGE, unchanged
rows that are only copied are then re-checked against the current time of the
write.
For example:
```sql
ALTER TABLE t ADD CONSTRAINT keep30 CHECK (ts >= current_timestamp() -
INTERVAL 30 DAYS)
```
31 days later, `DELETE FROM t WHERE id = 5` copies the other rows of the
touched files and fails with `CHECK_CONSTRAINT_VIOLATION` on an old copied row.
Every row-level change to those files keeps failing until the constraint is
dropped, while the same statement succeeded before this PR.
The migration guide documents this (SPARK-60453), but there is no
`spark.sql.legacy.*` config to restore the previous behavior. Could we add one?
##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/constraints/Check.java:
##########
@@ -66,17 +66,19 @@ private Check(
* Returns the SQL representation of the search condition (Spark SQL
dialect).
* <p>
* This is the canonical representation of the condition and is always
present (never
- * {@code null}). The optional {@link #predicate()} provides a structured
form when the condition
- * can be expressed using supported {@link Predicate} expressions.
+ * {@code null}). The optional {@link #predicate()} provides a structured
form, except in the
+ * cases that method lists.
*/
public String predicateSql() {
return predicateSql;
}
/**
* Returns the search condition as a {@link Predicate}, or {@code null} if
the condition cannot be
Review Comment:
This changes the public connector contract of `Check.predicate()`: a
condition that is expressible as a predicate may now be `null`, and connectors
get no capability flag or other signal for it.
A connector that enforces CHECK constraints natively, or validates them in
`alterTable`, and relies on `predicate()` being non-null for expressible
conditions will now receive `null` for e.g. `ALTER TABLE ... CHECK (ts <=
now())`. Depending on the connector, it may reject the change, skip
enforcement, or need to re-parse the Spark SQL text in `predicateSql()` itself,
which hits the same session-setting issues. Is there a way to signal this to
connectors, or at least to document why the predicate is omitted?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/constraints.scala:
##########
@@ -151,8 +155,48 @@ case class CheckConstraint(
}
}
+ // The two flags are printed only when set, so that the plan string of a
constraint without
+ // them stays as it was.
+ override def stringArgs: Iterator[Any] =
+ Iterator(child, condition, userProvidedName, tableName,
userProvidedCharacteristic) ++
+ Iterator("keepPredicate").filter(_ => keepPredicate) ++
+ Iterator("omitPredicate").filter(_ => omitPredicate)
+
+ /**
+ * Decides from the analyzed condition whether to store the constraint
without a predicate
+ * (`omitPredicate`). `AddCheckConstraint.storeAnalyzedQuery` calls this at
the end of the
+ * analysis of an ALTER TABLE.
+ *
+ * A write parses `condition` again, with its own settings. It cannot bind a
parameter marker
+ * that the legacy parameter substitution leaves there, resolves an
IDENTIFIER clause in its own
+ * session, and does not resolve a column qualified by the table name the
way ALTER TABLE does.
+ * It also resolves a name such as `current_date` or `user` to the function
or to a column,
+ * depending on its case sensitivity, its reserved keywords and the columns
of the table at that
+ * time. None of them can be told apart after analysis, so the parser sets
`keepPredicate` for
+ * them, and for any name with more than one part, since it cannot tell a
table qualifier from a
+ * struct column. Such a condition, or one that
`resolvesDifferentlyOnWrite`, keeps the predicate
+ * built from the optimized plan, as before. So does one that calls a
user-defined function,
+ * which the analysis rejects next and which is not evaluated here.
+ */
+ def withPredicateDecision(): CheckConstraint = copy(omitPredicate =
Review Comment:
Design question: this fix keeps building the V2 predicate from the optimized
plan, where `ComputeCurrentTime` and `SpecialDatetimeValues` have already
replaced current-like values with literals. It then adds a parse-time hint plus
several analysis-time heuristics to decide when to drop the predicate. As a
result, common conditions are still silently frozen at the ALTER TABLE time,
e.g.
- `CHECK (d <= CURRENT_DATE)` / `CHECK (ts <= CURRENT_TIMESTAMP)`
(paren-less, default settings)
- any condition on a table with a column named `user` or `current_date`
- qualified or struct field names such as `s.f`
- tables with a `CHAR` column
I understand these are deferred to SPARK-61194. Have you considered letting
`V2ExpressionBuilder`/`V2ExpressionUtils` translate current-like functions and
special datetime casts into V2 expressions, and building the predicate in
`storeAnalyzedQuery` before those rules run? That could remove the need for
`keepPredicate`/`omitPredicate` altogether.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala:
##########
@@ -877,6 +877,32 @@ object DateTimeUtils extends SparkDateTimeUtils {
}
}
+ /**
+ * Whether `input` is one of the special values that read the current date
or time: 'now',
+ * 'today', 'tomorrow' and 'yesterday'.
+ *
+ * @param input A string to check. It can contain trailing or leading
whitespaces.
+ */
+ private[sql] def isCurrentSpecialValue(input: String): Boolean = {
Review Comment:
This hard-codes `now`/`today`/`tomorrow`/`yesterday` separately from
`convertSpecialDate`/`convertSpecialTimestamp`/`convertSpecialTimestampNTZ`,
which define the same set. If a new clock-reading special value is added there
(used by `SpecialDatetimeValues`), `castReadsCurrentDate` silently returns
false for it, and such ALTER TABLE constraints are frozen again without any
test failure. Could we derive this from the same source, e.g.
`extractSpecialValue(...).exists(_ != "epoch")` guarded by the corresponding
conversion?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveTableConstraints.scala:
##########
@@ -71,6 +71,16 @@ class ResolveTableConstraints(
case _ =>
v2Write
}
+ // Once the analysis resolves the names of a parsed condition, drop the
ones that are not a
+ // value of the row, such as `current_user` without parentheses or a
variable, from the values
+ // that the violation message lists.
+ case v2Write: V2WriteCommand if containsCheckInvariant(v2Write.query) =>
Review Comment:
This new case runs as a separate transform in every fixed-point iteration of
the Resolution batch for every V2 write that has check invariants, so the
`Filter` condition is re-walked in each iteration. Could the non-row extractors
be filtered once, e.g. when `CheckInvariant` is resolved, or be skipped in
eval/codegen when they have no references?
Also, this changes the violation messages of existing CREATE TABLE
constraints (entries like ` - current_user : ...` disappear), which seems to be
outside the scope of the ALTER TABLE fix. Should it be a separate JIRA?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/LiteralFunctionResolution.scala:
##########
@@ -38,6 +38,12 @@ object LiteralFunctionResolution {
}
}
+ /** Whether `nameParts` is the name of a literal function, which `resolve`
resolves. */
+ def isLiteralFunction(nameParts: Seq[String]): Boolean = {
Review Comment:
nit: `isLiteralFunction` repeats the name lookup in `resolve`, so the
case-insensitive matching rule now lives in two places. If `resolve` changes (a
new alias, a different resolver), the two can disagree, and the parser would
stop marking a paren-less name that still resolves to a function at write time.
How about a shared private `find(name)` used by both?
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala:
##########
@@ -877,6 +877,32 @@ object DateTimeUtils extends SparkDateTimeUtils {
}
}
+ /**
+ * Whether `input` is one of the special values that read the current date
or time: 'now',
+ * 'today', 'tomorrow' and 'yesterday'.
+ *
+ * @param input A string to check. It can contain trailing or leading
whitespaces.
+ */
+ private[sql] def isCurrentSpecialValue(input: String): Boolean = {
+ extractSpecialValue(input.trim).exists {
+ case "now" | "today" | "tomorrow" | "yesterday" => true
+ case _ => false
+ }
+ }
+
+ /**
+ * Whether `input` is a valid timestamp string with only a time part, which
a cast to a timestamp
+ * with local time zone completes with the current date.
+ */
+ private[sql] def isTimeOnlyTimestamp(input: UTF8String): Boolean = {
Review Comment:
nit: this parses the string twice: `parseTimestampString`, and then
`stringToTimestamp`, which calls `parseTimestampString` again (and
`LocalDate.now`). The segments from the first parse should be enough to
validate the time fields (e.g. `LocalTime.of` inside a `try`).
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/constraints.scala:
##########
@@ -120,7 +122,9 @@ case class CheckConstraint(
condition: String,
override val userProvidedName: String = null,
override val tableName: String = null,
- override val userProvidedCharacteristic: ConstraintCharacteristic =
ConstraintCharacteristic.empty)
+ override val userProvidedCharacteristic: ConstraintCharacteristic =
ConstraintCharacteristic.empty,
+ keepPredicate: Boolean = false,
Review Comment:
nit: `keepPredicate` is a parse-time hint used only by ALTER TABLE, but it
lives on the shared `CheckConstraint` expression (also used by CREATE/REPLACE
TABLE, where nothing reads it), takes part in `equals` and plan comparison, and
needs a custom `stringArgs` override. Could the hint live on
`AddCheckConstraint` instead, or could the two flags be folded into a single
`Option[Boolean]` decision?
Also, `keepsCheckPredicate` has two identical arms for `UnresolvedAttribute`
and `UnresolvedNamedLambdaVariable`, which could be merged into a single
`nameParts` check.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -7194,6 +7194,23 @@ class AstBuilder extends DataTypeAstBuilder
condition = condition)
}
+ /**
+ * Whether a write that parses the condition of a CHECK constraint again can
resolve it
+ * differently from the ALTER TABLE, so that the constraint keeps its
predicate; see
+ * `CheckConstraint.withPredicateDecision`. A keyword such as `current_date`
or `user` without
+ * parentheses parses as a name, or as the function under
+ * `spark.sql.ansi.enforceReservedKeywords`, which is the only way the
parser builds these
+ * functions.
+ */
+ private def keepsCheckPredicate(condition: Expression): Boolean =
Review Comment:
`keepsCheckPredicate` does not consider the ALTER TABLE session's parser
settings. When a condition is stored without a predicate, every later write
re-parses `predicateSql` under the writer's own settings, which may differ.
For example, with `spark.sql.ansi.doubleQuotedIdentifiers=true`:
```sql
ALTER TABLE t ADD CONSTRAINT c CHECK ("ts" <= current_timestamp())
```
`omitPredicate` becomes true and `predicateSql` keeps the double quotes. A
writer with the default settings parses `"ts"` as the string literal `'ts'`.
Under ANSI, every INSERT fails with `CAST_INVALID_INPUT`. Without ANSI, the
check evaluates to NULL and accepts every row.
Similarly, with `spark.sql.parser.escapedStringLiterals=true`, `CHECK (path
<> 'C:\temp' OR ts <= now())` is read as `'C:<TAB>emp'` by a default writer, so
a row with `path = 'C:\temp'` and a future `ts` is silently accepted.
On master, the stored column-based predicate enforced these correctly. Since
the parser already looks at `enforceReservedKeywords` here, could it also set
`keepPredicate` when these settings are enabled?
--
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]