LuciferYang commented on code in PR #59545:
URL: https://github.com/apache/spark/pull/59545#discussion_r4521577007
##########
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:
Done in 641b196cc4f: the predicate is kept when the parser settings of the
ALTER TABLE session read the condition differently from the default ones. It
uses the check that CREATE TABLE already makes for a generation expression
(`StoredExpressionText.readsAsInSession`), so it covers
`spark.sql.ansi.doubleQuotedIdentifiers`,
`spark.sql.parser.escapedStringLiterals` and the other parser settings. It runs
in `withPredicateDecision` rather than in the parser, since it parses the text
again. It also counts a `${...}` placeholder, which a write with
`spark.sql.variable.substitute` replaces. A new test checks both of your
examples.
##########
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:
Done in 641b196cc4f: `resolvesDifferentlyOnWrite` also keeps the predicate
when the condition has a constant that depends on the session time zone and
reads no current value, such as a typed `TIMESTAMP` literal, a string cast to a
timestamp or `make_timestamp(DATE'2024-01-01', TIME'00:00')`. A new test adds
your example in UTC and writes from America/Los_Angeles. The migration guide
entry lists it with the other cases.
##########
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:
Added `spark.sql.legacy.freezeCurrentValuesInCheckConstraint` in
641b196cc4f. With it, ALTER TABLE stores the predicate built from the optimized
condition, as before. It is read when the constraint is added, and the
migration guide entry names it.
##########
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:
Yes. A predicate built from the analyzed condition, with the current-like
functions and the special datetime casts as V2 expressions, would let each
write evaluate them. But connectors would then see new expression names in
`Check.predicate()`, and `V2ExpressionBuilder` would first have to stop folding
`CAST('today' AS DATE)` as an ordinary cast (SPARK-60451). I'd rather settle
that interface in SPARK-61194, which tracks the conditions that still keep the
values of the ALTER TABLE. This PR keeps the predicate wherever Spark cannot
tell that a write reads the condition the same way.
--
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]