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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -856,9 +857,17 @@ case class Cast(
   }
 
   override def contextIndependentFoldable: Boolean = {
-    child.contextIndependentFoldable && !Cast.needsTimeZone(child.dataType, 
dataType)
+    child.contextIndependentFoldable && !Cast.needsTimeZone(child.dataType, 
dataType) &&

Review Comment:
   **[2] Could the title and the description say that this fixes wrong results, 
and what happens to existing tables?**
   
   With ANSI mode off, a CHECK constraint on `CAST('today' AS DATE)` accepted 
every row, and a DEFAULT value or a generated column on it wrote `NULL`. Both 
are silent wrong results. A title that says it fixes them, and the 
`correctness` label on the JIRA if it does not have it yet, would make this 
visible to users and release managers.
   
   Also, a table created by Spark 4.1 to 4.3 with ANSI mode off keeps what it 
stored: the predicate `d <= NULL`, or a `ColumnDefaultValue` or 
`GenerationExpression` whose expression is `LiteralValue(null)`. After this 
fix, a write still reads the stored predicate (`TableConstraintResolution`) and 
the stored default expression (`ResolveDefaultColumnsUtil.scala:219`). So such 
a table keeps accepting every row, or writing `NULL`, until the constraint is 
dropped and added again or the default is set again, and a generated column 
keeps its stored expression. Could the description, and maybe the migration 
guide, say so?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -856,9 +857,17 @@ case class Cast(
   }
 
   override def contextIndependentFoldable: Boolean = {
-    child.contextIndependentFoldable && !Cast.needsTimeZone(child.dataType, 
dataType)
+    child.contextIndependentFoldable && !Cast.needsTimeZone(child.dataType, 
dataType) &&
+      !castsSpecialDatetimeValue
   }
 
+  /**
+   * Whether this casts a special value such as 'today' or 'epoch', which 
`SpecialDatetimeValues`
+   * replaces with its value. Evaluating the cast does not give that value.
+   */
+  private[sql] def castsSpecialDatetimeValue: Boolean = 
SpecialDatetimeValues.rewrites(dataType) &&

Review Comment:
   **[1] 'epoch' has a fixed value, but now gets no V2 form.**
   
   `castsSpecialDatetimeValue` uses `replaces`, not `readsCurrentDate`, so 
`CAST('epoch' AS DATE)` also stops being context independent and gets no V2 
form, although its value never changes. As a result:
   
   - `CREATE TABLE ... CHECK (d >= CAST('epoch' AS DATE))` stores no predicate, 
as the new test asserts (`CheckConstraintSuite.scala:676`). `ALTER TABLE ... 
ADD CONSTRAINT` keeps the predicate for 'epoch', because it does not read the 
current date (`CheckConstraintSuite.scala:357`). So the same condition is 
stored differently depending on the statement that adds it.
   - `DEFAULT CAST('epoch' AS DATE)` has no V2 expression 
(`DataSourceV2DataFrameSuite.scala:1159`), while `DEFAULT DATE'1970-01-01'` has 
one.
   - A connector that validates or enforces the constraint itself now has to 
evaluate its SQL text for a fixed date.
   
   Could the builder fold 'epoch' to its value instead, for example by running 
`SpecialDatetimeValues.applyForExpression` before 
`ConstantFolding.constantFolding` in the folding case? Then only the casts that 
`readsCurrentDate` would need to be excluded and get no V2 form.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/V2ExpressionBuilder.scala:
##########
@@ -172,6 +172,8 @@ class V2ExpressionBuilder(e: Expression, isPredicate: 
Boolean = false) extends L
       } else {
         None
       }
+    // Like `current_date()`, such a cast has no V2 form, so that the SQL text 
is read instead.

Review Comment:
   **[6] nit: the comment describes only the DDL callers.**
   
   `V2ExpressionBuilder` also translates scan and DELETE filters 
(`PushableExpression`, `DataSourceV2Strategy.scala:1190`), where `None` means 
that the filter is not pushed down, not that a SQL text is read. Those filters 
come from the optimized plan, where `SpecialDatetimeValues` has already 
replaced such a cast, so the behavior is fine there. Only the comment is 
narrower than the builder. Maybe something like:
   
   ```suggestion
       // Like `current_date()`, such a cast has no V2 form. Only 
`SpecialDatetimeValues` gives it.
   ```



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/finishAnalysis.scala:
##########
@@ -320,13 +320,16 @@ object SpecialDatetimeValues extends Rule[LogicalPlan] {
   /** 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 the value of a 
special value. */
+  private[sql] def replaces(s: UTF8String, dt: DataType): Boolean =

Review Comment:
   **[3] After the conflict is resolved, this also covers nanosecond 
timestamps, which the tests do not cover yet.**
   
   The conflict with master is here. SPARK-61538 (9cfdfbd4603) made `conv` a 
`PartialFunction` and added `TIMESTAMP_LTZ(p)` and `TIMESTAMP_NTZ(p)` for p 
from 7 to 9, so `conv.get(dt)` has to become `conv.lift(dt)`, as 
`readsCurrentDate` already does on master. Then `castsSpecialDatetimeValue` 
also covers a cast such as `CAST('today' AS TIMESTAMP_NTZ(9))`. On master that 
cast is context independent, so the builder folds it by evaluating the cast, 
the same problem this PR fixes. Could the tests include a nanosecond type, for 
example in `CastSuiteBase` and in the CREATE TABLE test?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -856,9 +857,17 @@ case class Cast(
   }
 
   override def contextIndependentFoldable: Boolean = {
-    child.contextIndependentFoldable && !Cast.needsTimeZone(child.dataType, 
dataType)
+    child.contextIndependentFoldable && !Cast.needsTimeZone(child.dataType, 
dataType) &&
+      !castsSpecialDatetimeValue

Review Comment:
   **[4] `castsSpecialDatetimeValue` evaluates the string every time it is 
asked.**
   
   It is a `def`, and `contextIndependentFoldable` calls it. 
`V2ExpressionBuilder.generateExpression` asks every node on the way down for 
`contextIndependentFoldable`, which recurses into the whole subtree, and then 
the case at `V2ExpressionBuilder.scala:176` asks once more. So the child 
string, such as a `concat`, is evaluated once for each ancestor plus once more. 
Each time, it is also converted with `convertSpecialDate` or the like, which 
computes the current date only to tell that the string is special. Each call is 
cheap, but a `lazy val` would compute it once per `Cast`.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -856,9 +857,17 @@ case class Cast(
   }
 
   override def contextIndependentFoldable: Boolean = {
-    child.contextIndependentFoldable && !Cast.needsTimeZone(child.dataType, 
dataType)
+    child.contextIndependentFoldable && !Cast.needsTimeZone(child.dataType, 
dataType) &&
+      !castsSpecialDatetimeValue
   }
 
+  /**
+   * Whether this casts a special value such as 'today' or 'epoch', which 
`SpecialDatetimeValues`
+   * replaces with its value. Evaluating the cast does not give that value.
+   */
+  private[sql] def castsSpecialDatetimeValue: Boolean = 
SpecialDatetimeValues.rewrites(dataType) &&
+    
SpecialDatetimeValues.constantString(this).exists(SpecialDatetimeValues.replaces(_,
 dataType))

Review Comment:
   **[5] nit: the special-value check is now written twice.**
   
   `CheckConstraint.castReadsCurrentDate` (`constraints.scala:286-293`) already 
checks `SpecialDatetimeValues.rewrites(cast.dataType) && 
SpecialDatetimeValues.constantString(cast).exists(...)`, and this adds the same 
pattern with `replaces`. A helper in `SpecialDatetimeValues`, such as 
`specialValueOf(cast: Cast): Option[UTF8String]`, would let both share the type 
check and the evaluation. The nanosecond types in [3] are the kind of change 
that would otherwise need both places updated.



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