spark-test commented on code in PR #59545:
URL: https://github.com/apache/spark/pull/59545#discussion_r4506760251


##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/constraints/Check.java:
##########
@@ -75,8 +75,10 @@ public String predicateSql() {
 
   /**
    * Returns the search condition as a {@link Predicate}, or {@code null} if 
the condition cannot be
-   * expressed using supported predicate expressions. Use {@link 
#predicateSql()} for the canonical
-   * SQL representation, which is always present.
+   * expressed using supported predicate expressions. Spark may also leave it 
{@code null} for a

Review Comment:
   **Nit (P3):** This sentence adds a second reason for `predicate()` to be 
null, but two other places in this class still state the old contract: the 
class overview (lines 30-33) says the condition is exposed via `predicate()` 
"whenever it can be expressed using supported expressions", and the 
`predicateSql()` Javadoc (lines 69-70) says `predicate()` provides a structured 
form "when the condition can be expressed". For `ALTER TABLE ... ADD CONSTRAINT 
c CHECK (db = current_database())` the condition is expressible, yet the stored 
predicate is now null, so a connector author who reads the overview or 
`predicateSql()` draws the wrong conclusion. Could those two places describe 
the same null cases as this method?
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59545#pullrequestreview-5588300195).
   
   **Verification:**
   - **Inspection:** The class overview, the predicateSql() Javadoc and the 
predicate() Javadoc of Check state the same conditions under which Spark leaves 
the predicate null, including conditions that read the current time, date, 
catalog, user and the like.



##########
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 =
+    !keepPredicate && 
StoredExpressionFunctions.findUserDefinedFunctionCall(child).isEmpty &&
+      !CheckConstraint.resolvesDifferentlyOnWrite(child) &&
+      CheckConstraint.readsCurrentContext(child))
+
+  // ALTER TABLE builds the constraint from the optimized plan, where the 
current time, date,
+  // catalog, user and the like are replaced by their values at the time of 
the ALTER TABLE. A
+  // condition that `withPredicateDecision` finds reading one is stored 
without a predicate, so
+  // that writes check `predicateSql`.
+  // The predicate is not built from the analyzed condition, as the default 
value of a column is,

Review Comment:
   **Nit (P3):** This sentence holds for ALTER TABLE, whose planner passes the 
optimized condition, but `toV2Constraint` is shared: `ResolveTableSpec` calls 
it on the analyzed constraints of CREATE and REPLACE TABLE 
(ResolveTableSpec.scala:147), so for them the predicate is built from the 
analyzed condition and the `CAST('today' AS DATE)` folding cited here still 
applies (SPARK-60451). Read together with the next sentence, the comment 
suggests that CREATE and REPLACE TABLE avoid it. Could it scope this sentence 
to ALTER TABLE and say that CREATE and REPLACE TABLE build the predicate from 
the analyzed condition?
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/59545#discussion_r4327531723), 
[2](https://github.com/apache/spark/pull/59545#discussion_r4327531894).
   
   **Verification:**
   - **Inspection:** The comment above toV2Constraint no longer says that the 
predicate is not built from the analyzed condition for every caller, and names 
the CREATE and REPLACE TABLE path that builds it from the analyzed condition.



##########
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:
   **Non-blocking (P2):** This decision keeps the predicate built from the 
optimized condition, where the current values are already literals of the ALTER 
TABLE, for every condition the parser marks or `resolvesDifferentlyOnWrite` 
flags, so the fix misses many of the conditions it targets. With default 
settings, `ALTER TABLE t ADD CONSTRAINT c CHECK (d <= CURRENT_DATE)` parses 
`CURRENT_DATE` as an `UnresolvedAttribute` (as `CurrentDate()` under 
`spark.sql.ansi.enforceReservedKeywords`), `keepsCheckPredicate` marks it, and 
the stored predicate is `d <= DATE '<day of the ALTER TABLE>'`. On any later 
day, `INSERT INTO t VALUES (1, current_date())` fails with 
CHECK_CONSTRAINT_VIOLATION, while the same check spelled `d <= current_date()` 
is evaluated at each write. Conditions that also contain a name with more than 
one part, a variable, an IDENTIFIER clause, a CHAR column or a legacy parameter 
marker stay frozen the same way, and a time-relative bound such as `ts >= 
CURRENT_TIMESTAMP - IN
 TERVAL 30 DAYS` keeps accepting rows it should reject. The multi-part rule 
also catches ordinary struct-field access such as `e.ts <= 
current_timestamp()`, which a write resolves the same way as the ALTER TABLE, 
so it is broader than the table-qualifier hazard behind it. Casts into nested 
types or from VARIANT are not detected at all. The new tests pin these cases as 
keeping a non-null predicate (CheckConstraintSuite.scala:346, 448, 477 and 528).
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/59545#issuecomment-6410219838), 
[2](https://github.com/apache/spark/pull/59545#pullrequestreview-5588300195), 
[3](https://github.com/apache/spark/pull/59545#pullrequestreview-5615995779), 
[4](https://github.com/apache/spark/pull/59545#pullrequestreview-5745370388).
   
   **Recommended change:** Keep the current values out of the stored predicate 
instead of freezing them, for the ALTER-added conditions that read the current 
time, date, catalog, user and the like and that the PR keeps on their predicate 
because a write would read part of them differently: a literal-function name 
without parentheses, a name resolved through a table qualifier, a variable, an 
IDENTIFIER clause, a CHAR column or a legacy parameter marker. For these, build 
the predicate from the optimized condition with the current-context reads left 
in place as DSv2 scalar expressions that writes convert back into the same 
functions and casts. Decide the multi-part case against the table that the 
ALTER TABLE resolves, so that only a name whose leading parts can name that 
table counts and a struct-field access, which a write resolves the same way, is 
stored without a predicate like the other current-context conditions. Extend 
the detection to casts into nested types and from VARIANT, sto
 re every other current-context condition without a predicate as the PR does, 
add a TODO where an exempted condition has no DSv2 form and keeps its 
ALTER-time predicate, and add CHECK constraint tests for each kind of condition 
that keeps its ALTER-time values today.
   
   **Why this works:** For an ALTER-added current-context condition that a 
write would read differently, the current-context sub-expressions that the 
detection finds, namely the current-like functions, TIME-to-timestamp casts and 
top-level casts of special or time-only strings, are wrapped before the 
predicate is built, so that the finish-analysis rules and constant folding 
leave them unevaluated. The DSv2 expression builder translates the wrapped 
nodes into dedicated scalar expressions, and the conversion back to Catalyst 
rebuilds the original expressions. Everything else keeps the meaning the ALTER 
TABLE resolved: variables, IDENTIFIER clauses and legacy parameter markers are 
folded to their values, CHAR literals are padded, and qualified and paren-less 
names are resolved, while each write computes the current values itself. Such a 
condition whose wrapped form the builder cannot translate keeps the predicate 
built from the optimized condition.
   
   **Scope:** The stored representation of ALTER-added CHECK constraints that 
read the current context and that a write would read differently, and the DSv2 
expression conversion in both directions for those reads.
   
   **Compatibility:** Constraints that read no current context, CREATE and 
REPLACE TABLE constraints, and constraints stored before the change behave 
exactly as they do on the base branch, and current-context conditions without 
parts that a write reads differently are stored without a predicate, as this PR 
stores them.
   
   **Risks:** Connectors that read Check.predicate() will see DSv2 scalar 
expression names they may not know, so the names and their meaning must be 
documented and a connector must be able to fall back to predicateSql(); only 
constraint predicates may carry them, never pushed-down filters. The exempted 
conditions without a DSv2 form, including the SQL-standard ts >= 
CURRENT_TIMESTAMP - INTERVAL 30 DAYS, keep their ALTER-time values until DSv2 
can express interval arithmetic on a deferred read.
   
   **Constraints:** Each write must evaluate the deferred expressions with its 
own values, matching what current_timestamp(), current_date(), current_user() 
and the like return in that write. A condition that reads no current context 
must keep the predicate that the base branch stores. A current-context 
condition with none of the parts that a write reads differently stays stored 
without a predicate, so the question of re-reading under the writer's settings 
stays separate.
   
   **Exclusions:**
   - Typed literals such as DATE 'today', which the parser folds before 
analysis (SPARK-60452).
   - Conditions folded early under spark.sql.legacy.earlyEvalCurrentTime 
(SPARK-60456).
   - CREATE and REPLACE TABLE constraints and DEFAULT values, whose folding of 
special strings is tracked separately (SPARK-60451).
   - Constraints stored before this change, which keep their stored predicate 
until they are dropped and added again, because covering them would need a 
rewrite of stored catalog entries.
   - A cast of a string that only the optimizer makes constant, such as 
CAST(coalesce('23:59:59', s) AS TIMESTAMP), which the decision at the end of 
the analysis cannot see; in a condition stored with a predicate it keeps its 
ALTER-time value, with a TODO naming the detection it needs.
   - A condition whose deferred form has no DSv2 translation, such as a time 
window written with interval arithmetic or make_interval, and that also has a 
literal-function name without parentheses, a table-qualified column, a 
variable, an IDENTIFIER clause, a CHAR column or a legacy parameter marker 
keeps its ALTER-time predicate, with a TODO naming the DSv2 support it needs; 
this includes the SQL-standard ts >= CURRENT_TIMESTAMP - INTERVAL 30 DAYS.
   
   **Success:** ALTER-added constraints such as d <= CURRENT_DATE, e.ts <= 
current_timestamp() on a STRUCT column e, status = 'OPEN' OR closed <= 
current_date() on a CHAR column, and owner = v OR ts <= current_timestamp() 
with a session variable v are checked against the values of each write, while 
v, the CHAR padding and the resolved names keep the meaning they had at the 
ALTER TABLE. No stored predicate of an ALTER-added constraint holds a current 
time, date, catalog or user value computed at the ALTER TABLE, apart from the 
excluded cases. An ALTER-added condition that reads the current context and has 
none of the parts that a write reads differently is still stored without a 
predicate.
   
   **Verification:**
   - **Regression:** For each kind of condition that keeps its ALTER-time 
values today, a paren-less keyword in both parser modes, a struct-field access, 
a table-qualified column, a session variable, an IDENTIFIER clause, a CHAR 
column, a legacy parameter marker and a cast into a nested type or from 
VARIANT, an ALTER-added constraint whose current-context read sits in a 
comparison, such as ts <= current_timestamp() or d <= CURRENT_DATE, stores a 
predicate with the deferred read or no predicate, never a value computed at the 
ALTER TABLE, accepts a row written with the current value and rejects one 
written past it; and each kind that a write reads differently, in a time window 
written with interval arithmetic, keeps its stored predicate.
   - **Compatibility:** Constraints that read no current context store the same 
predicate as on the base branch, current-context conditions without parts that 
a write reads differently are still stored without a predicate, and a 
constraint stored with deferred current-context reads accepts and rejects the 
same rows for writers whose double-quoted identifier, escaped string literal, 
reserved keyword and ANSI settings differ.
   - **Behavior:** Converting a stored predicate with deferred current-context 
reads back to Catalyst yields the original functions and casts, and filters 
pushed down to a source never contain the new scalar expression names.
   - **Inspection:** The Check and DSv2 scalar expression documentation name 
the deferred expressions and say that a connector that cannot evaluate them 
should use predicateSql().



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