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


##########
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:
   Minor: this PR changes user-facing behavior, but 
`docs/sql-migration-guide.md` has no entry for it. The other CHECK constraint 
changes in 4.4 each added one, such as SPARK-60777, SPARK-60781 and SPARK-60822 
([sql-migration-guide.md 
L83-L91](https://github.com/apache/spark/blob/38a9a46770a2cf25c539f947f3a80489eb870ba5/docs/sql-migration-guide.md#L83-L91)).
   
   Users who upgrade would need these points, most of which the user-facing 
section of the description already has:
   
   - A CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT` adds to a Data 
Source V2 table, and whose condition reads the current time, date, catalog, 
user and the like, is checked against their values at each write. Before, it 
compared with their values at the time of the ALTER TABLE.
   - Each write reads such a constraint under its own session settings, as it 
reads a CREATE TABLE constraint without a predicate.
   - A row-level operation that copies unchanged rows, such as a DELETE on a 
copy-on-write table, fails on a copied row that no longer satisfies the 
condition. For example, `ts >= current_timestamp() - INTERVAL 30 DAYS` passed 
every such DELETE before, and now fails it once a copied row is older than 30 
days.
   - An existing constraint keeps its stored predicate until it is dropped and 
added again.
   - The violation message, also for a CREATE TABLE constraint, no longer lists 
a paren-less function name or a variable.
   
   Could you add an entry next to the other CHECK constraint entries?
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2AlterTableCommands.scala:
##########
@@ -386,8 +386,10 @@ case class AddCheckConstraint(
     analyzedQuery: Option[LogicalPlan] = None) extends UnaryCommand with 
KeepAnalyzedQuery {
 
   // The optimizer replaces the filtered scan with an empty relation if no row 
can violate the
-  // check, so keep the analyzed child to find the table when planning.
-  override def storeAnalyzedQuery(): Command = copy(analyzedQuery = 
Some(child))
+  // check, so keep the analyzed child to find the table when planning. The 
constraint decides
+  // here, with its condition analyzed, whether to store a predicate.
+  override def storeAnalyzedQuery(): Command = copy(

Review Comment:
   Minor: with the call moved here, the decision no longer has the `c.resolved` 
guard of `HandleSpecialCommand` ([Analyzer.scala 
L4542-L4543](https://github.com/apache/spark/blob/38a9a46770a2cf25c539f947f3a80489eb870ba5/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala#L4542-L4543)).
 `NormalizePlan` also calls `storeAnalyzedQuery()` on every `KeepAnalyzedQuery` 
([NormalizePlan.scala 
L220](https://github.com/apache/spark/blob/38a9a46770a2cf25c539f947f3a80489eb870ba5/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/NormalizePlan.scala#L220)).
 `PlanTest.comparePlans` ([PlanTest.scala 
L90-L91](https://github.com/apache/spark/blob/38a9a46770a2cf25c539f947f3a80489eb870ba5/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/plans/PlanTest.scala#L90-L91))
 and the dual-run check of `HybridAnalyzer` ([HybridAnalyzer.scala 
L311-L312](https://github.com/apache/spark/blob/38a9a46770a2cf25c539f947f3a80489eb870ba5/sql/catalyst/src/main/scala/org/
 apache/spark/sql/catalyst/analysis/resolver/HybridAnalyzer.scala#L311-L312)) 
go through it. So `markAsAnalyzed` now also runs on parsed and optimized plans.
   
   From reading the code, a parser test like this one fails with 
`UnresolvedException`:
   
   ```scala
   val parsed = parsePlan(
     "ALTER TABLE a.b.t ADD CONSTRAINT c1 CHECK (CAST(d AS TIMESTAMP) > 
TIMESTAMP'2020-01-01')")
   comparePlans(parsed, expected)
   ```
   
   - A `Cast` to TIMESTAMP carries `CAST_TO_TIMESTAMP` from its target type 
alone ([Cast.scala 
L747-L750](https://github.com/apache/spark/blob/38a9a46770a2cf25c539f947f3a80489eb870ba5/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala#L747-L750)),
 so `ComputeCurrentTime.applyForExpression` in `readsCurrentContext` visits it.
   - The guard of its TIME rewrite reads `c.child.dataType` 
([finishAnalysis.scala 
L186](https://github.com/apache/spark/blob/38a9a46770a2cf25c539f947f3a80489eb870ba5/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/finishAnalysis.scala#L186)),
 which throws for the unresolved `d`.
   
   The current conditions in `CheckConstraintParseSuite`, `a > 0` and `d > 0`, 
have no such cast, so the suite passes. On an optimized plan, 
`current_timestamp()` is already a literal, so the same call resets 
`omitPredicate` to false. Since both sides are decided again, `comparePlans` 
also cannot catch a wrong `omitPredicate`.
   
   Could this keep the decision made at the end of the analysis, and skip an 
unresolved constraint? For example:
   
   ```scala
   override def storeAnalyzedQuery(): Command = {
     val check = if (analyzedQuery.isEmpty && checkConstraint.resolved) {
       checkConstraint.markAsAnalyzed()
     } else {
       checkConstraint
     }
     copy(checkConstraint = check, analyzedQuery = Some(child))
   }
   ```
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/constraints.scala:
##########
@@ -151,8 +155,43 @@ case class CheckConstraint(
     }
   }
 
+  override def stringArgs: Iterator[Any] =

Review Comment:
   Nit: `stringArgs` hides `keepPredicate` and `omitPredicate`, but both take 
part in `equals`. The parser also sets `keepPredicate` for CREATE and REPLACE 
TABLE constraints, where nothing reads it.
   
   So a plan comparison can fail while the two plans print the same. For 
example, take a parser test of `CREATE TABLE t (a STRUCT<b: INT>, CONSTRAINT c1 
CHECK (a.b > 0)) USING parquet` whose expected `CheckConstraint` uses the 
default `keepPredicate`. The parsed one has `keepPredicate = true` for the 
two-part name, so `comparePlans` fails. The two trees in its message are the 
same, because `Expression.toString` prints `flatArguments`, which come from 
`stringArgs` ([Expression.scala 
L363-L366](https://github.com/apache/spark/blob/38a9a46770a2cf25c539f947f3a80489eb870ba5/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala#L363-L366)).
   
   Could `stringArgs` print the two flags when they are set, or could the 
parser set `keepPredicate` only where `visitAddTableConstraint` builds the 
`AddCheckConstraint`?
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/finishAnalysis.scala:
##########
@@ -316,14 +317,49 @@ object SpecialDatetimeValues extends Rule[LogicalPlan] {
     
expression.transformWithPruning(_.containsPattern(CAST))(specialDatetimeRewrite)
   }
 
+  /** Whether this rule may replace a cast to `dt`. */
+  private[sql] def rewrites(dt: DataType): Boolean = conv.contains(dt)
+
+  /**
+   * Whether this rule replaces a cast of `s` to `dt` with a value that reads 
the current date, that
+   * is, the value of 'now', 'today', 'tomorrow' or 'yesterday' rather than of 
'epoch'.
+   */
+  private[sql] def readsCurrentDate(s: UTF8String, dt: DataType): Boolean =
+    rewrites(dt) && DateTimeUtils.isCurrentSpecialValue(s.toString)
+
+  /**
+   * The constant string that `cast` casts, or None if it casts something else 
or evaluating the
+   * string fails. Unlike the rule, this does not throw.
+   */
+  private[sql] def constantString(cast: Cast): Option[UTF8String] = cast.child 
match {
+    case e if isConstantString(e) =>
+      try {
+        Option(e.eval().asInstanceOf[UTF8String])
+      } catch {
+        case NonFatal(_) => None
+      }
+    case _ => None
+  }
+
   private val specialDatetimeRewrite: PartialFunction[Expression, Expression] 
= {
-    case cast @ Cast(e, dt @ (DateType | TimestampType | TimestampNTZType), _, 
_)
-      if e.foldable && e.dataType.isInstanceOf[StringType] =>
+    case cast @ FoldableStringCast(e, dt) =>
       Option(e.eval())
         .flatMap(s => conv(dt)(s.toString, cast.zoneId))
         .map(Literal(_, dt))
         .getOrElse(cast)
   }
+
+  private def isConstantString(e: Expression): Boolean =
+    e.foldable && e.dataType.isInstanceOf[StringType]
+
+  /** A cast of a foldable string to a type in `conv`. */
+  private object FoldableStringCast {

Review Comment:
   Nit: `FoldableStringCast` has one caller, and the rewrite above did not need 
a new extractor. A guard with `rewrites` does the same:
   
   ```scala
   case cast @ Cast(e, dt, _, _) if rewrites(dt) && isConstantString(e) =>
   ```
   
   The keys of `conv` are the three types of the previous pattern, so 
`rewrites` still keeps them in one place.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -7189,11 +7189,27 @@ class AstBuilder extends DataTypeAstBuilder
   override def visitCheckConstraint(ctx: CheckConstraintContext): 
CheckConstraint =
     withOrigin(ctx) {
       val condition = getOriginalText(ctx.expr)
+      val child = expression(ctx.booleanExpression())
       CheckConstraint(
-        child = expression(ctx.booleanExpression()),
-        condition = condition)
+        child = child,
+        condition = condition,
+        keepPredicate = child.containsAnyPattern(PARAMETER, 
UNRESOLVED_IDENTIFIER) ||
+          hasCurrentLikeKeyword(ctx.booleanExpression()) ||
+          child.exists {
+            case u: UnresolvedAttribute =>
+              u.nameParts.length > 1 || 
LiteralFunctionResolution.isLiteralFunction(u.nameParts)
+            case _ => false
+          })
     }
 
+  /**
+   * Whether `tree` has a keyword such as `current_date` or `user` without 
parentheses, which parses
+   * as a column name or as the function depending on 
`spark.sql.ansi.enforceReservedKeywords`.
+   */
+  private def hasCurrentLikeKeyword(tree: ParseTree): Boolean = tree match {

Review Comment:
   Nit: the parsed condition already shows what this method looks for in the 
parse tree, so the check could be more cases of the `child.exists` above.
   
   - `visitCurrentLike` is the only place in the parser that builds 
`CurrentDate`, `CurrentTimestamp`, `CurrentTime` or `CurrentUser`, which it 
does under `spark.sql.ansi.enforceReservedKeywords` 
([L4079-L4103](https://github.com/apache/spark/blob/38a9a46770a2cf25c539f947f3a80489eb870ba5/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala#L4079-L4103)).
 A call with parentheses parses as an `UnresolvedFunction`.
   - Otherwise the keyword parses as an `UnresolvedAttribute`, which 
`isLiteralFunction` already matches. In a lambda body, `visitLambda` turns it 
into an `UnresolvedNamedLambdaVariable` 
([L4602-L4604](https://github.com/apache/spark/blob/38a9a46770a2cf25c539f947f3a80489eb870ba5/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala#L4602-L4604)).
   
   ```scala
   child.exists {
     case u: UnresolvedAttribute =>
       u.nameParts.length > 1 || 
LiteralFunctionResolution.isLiteralFunction(u.nameParts)
     case v: UnresolvedNamedLambdaVariable =>
       LiteralFunctionResolution.isLiteralFunction(v.nameParts)
     case _: CurrentDate | _: CurrentTimestamp | _: CurrentTime | _: 
CurrentUser => true
     case _ => false
   }
   ```
   
   This drops the second walk over the tree. It would also cover a backquoted 
`` `user` `` in a lambda body, which neither check catches now (SPARK-60787). 
And without the parse tree, the flag could be set from the expression alone, 
wherever it is needed.
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/constraints.scala:
##########
@@ -151,8 +155,43 @@ case class CheckConstraint(
     }
   }
 
+  override def stringArgs: Iterator[Any] =
+    Iterator(child, condition, userProvidedName, tableName, 
userProvidedCharacteristic)
+
+  /**
+   * Decides, once ALTER TABLE has analyzed the condition, whether to store 
the constraint without
+   * a predicate (`omitPredicate`).
+   *
+   * 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 markAsAnalyzed(): CheckConstraint = copy(omitPredicate =

Review Comment:
   Nit: `CheckConstraint` no longer extends `AnalysisAwareExpression`, but this 
method keeps the name of that trait's method. The last arm of 
`HandleSpecialCommand` calls `markAsAnalyzed()` on every 
`AnalysisAwareExpression` of a resolved plan ([Analyzer.scala 
L4544-L4547](https://github.com/apache/spark/blob/38a9a46770a2cf25c539f947f3a80489eb870ba5/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala#L4544-L4547)).
 So the name suggests that the constraint is marked there, which is the 
assumption that SPARK-60824 broke ([the earlier 
thread](https://github.com/apache/spark/pull/59545#discussion_r4464512056)). 
Its only callers are now `AddCheckConstraint.storeAnalyzedQuery` and 
`NormalizePlan` through it.
   
   Two comments also no longer match where it runs:
   
   - L186-L188 says that only ALTER TABLE calls it.
   - The doc of `KeepAnalyzedQuery` ([v2Commands.scala 
L51-L58](https://github.com/apache/spark/blob/38a9a46770a2cf25c539f947f3a80489eb870ba5/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala#L51-L58))
 says that `storeAnalyzedQuery` copies the analyzed query, not that it also 
decides the predicate of a constraint.
   
   Could this method get a name for what it does, such as 
`withPredicateDecision()`, and could the two comments say where it runs?
   



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