sarutak commented on code in PR #60119:
URL: https://github.com/apache/spark/pull/60119#discussion_r4505808097


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,20 +307,113 @@ object ExprUtils extends EvalHelper with QueryErrorsBase 
{
     e.deterministic && !e.containsPattern(PLAN_EXPRESSION) &&
       canEvaluateUnconditionallyInternal(e)
 
+  // Only the numeric pairs are taken from `Cast.canUpCast`, which also covers 
e.g. DATE to
+  // TIMESTAMP, which can overflow, and casts between complex types. Among the 
numeric ones, it
+  // only takes a decimal to an integral type whose values all fit.
+  private def isNumericUpCast(from: DataType, to: DataType): Boolean = (from, 
to) match {
+    case (_: NumericType, _: NumericType) => Cast.canUpCast(from, to)
+    case _ => false
+  }
+
+  // Whether a cast can not fail. A cast of a date to a timestamp is left out 
also in LEGACY mode,
+  // as converting a date far from the epoch to microseconds overflows there.
+  private def cannotFailCast(c: Cast): Boolean = (c.child.dataType, 
c.dataType) match {
+    // Left out whether or not it can fail, as it may tell -0.0 from 0.0: see
+    // `canEvaluateUnconditionally`.
+    case (from, to) if tellsSignedZeros(from, to) => false
+    // TRY mode catches the errors of the cast, but not from a string, which 
runs the LEGACY cast.
+    case (from, to) if hasNegativeScale(from) || hasNegativeScale(to) =>
+      c.evalMode == EvalMode.TRY && !from.isInstanceOf[StringType]
+    case (from, to) if isNumericUpCast(from, to) => true
+    // `Decimal.toDouble` and `Decimal.toFloat` round, and do not check the 
range in ANSI mode.
+    case (_: DecimalType, FloatType | DoubleType) => true
+    case (TimestampType | TimestampNTZType, DateType) => true
+    // A CHAR or VARCHAR target checks the length of the string. A string to a 
STRING of another
+    // collation, as `CollationTypeCoercion` adds for an explicit `COLLATE`, 
keeps the value.
+    case (_: NumericType | BooleanType | _: StringType, s: StringType)
+        if StringHelper.isPlainString(s) => true
+    case _ if c.evalMode == EvalMode.TRY => true
+    // `Cast.isNoThrowLegacyCast` covers the numbers, booleans and strings. A 
string to a date or
+    // a timestamp does not raise in LEGACY mode either: the parsers catch the 
errors and return
+    // None, which becomes NULL.
+    case (_: StringType, DateType | TimestampType | TimestampNTZType)
+        if c.evalMode == EvalMode.LEGACY => true
+    case (from, to) if c.evalMode == EvalMode.LEGACY => 
Cast.isNoThrowLegacyCast(from, to)
+    case _ => false
+  }
+
+  // Whether the source type has a FLOAT or DOUBLE and the target type a 
STRING or VARIANT in it,
+  // so that the cast may keep the sign of a zero, e.g. -0.0 as '-0.0'. This 
is conservative: it
+  // does not match the fields of the types.
+  private def tellsSignedZeros(from: DataType, to: DataType): Boolean =
+    from.existsRecursively(t => t == FloatType || t == DoubleType) &&

Review Comment:
   Right, thanks: `existsRecursively` does not look inside a UDT, and neither 
does `isBinaryStable`. The check now leaves out every cast from or to a type 
with a UDT in it, in every mode. `ExprUtilsSuite` checks a TRY, LEGACY and ANSI 
cast to a string of a UDT, of an array of UDTs and of a struct with one, and 
`InferFiltersFromConstraintsSuite` that `x = y AND try_cast(y AS STRING) = 
'(-0.0)'` over two columns of a test vector UDT, which renders a vector of -0.0 
as `(-0.0)`, infers no filter on `x`.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,20 +307,113 @@ object ExprUtils extends EvalHelper with QueryErrorsBase 
{
     e.deterministic && !e.containsPattern(PLAN_EXPRESSION) &&
       canEvaluateUnconditionallyInternal(e)
 
+  // Only the numeric pairs are taken from `Cast.canUpCast`, which also covers 
e.g. DATE to
+  // TIMESTAMP, which can overflow, and casts between complex types. Among the 
numeric ones, it
+  // only takes a decimal to an integral type whose values all fit.
+  private def isNumericUpCast(from: DataType, to: DataType): Boolean = (from, 
to) match {
+    case (_: NumericType, _: NumericType) => Cast.canUpCast(from, to)
+    case _ => false
+  }
+
+  // Whether a cast can not fail. A cast of a date to a timestamp is left out 
also in LEGACY mode,
+  // as converting a date far from the epoch to microseconds overflows there.
+  private def cannotFailCast(c: Cast): Boolean = (c.child.dataType, 
c.dataType) match {
+    // Left out whether or not it can fail, as it may tell -0.0 from 0.0: see
+    // `canEvaluateUnconditionally`.
+    case (from, to) if tellsSignedZeros(from, to) => false
+    // TRY mode catches the errors of the cast, but not from a string, which 
runs the LEGACY cast.
+    case (from, to) if hasNegativeScale(from) || hasNegativeScale(to) =>

Review Comment:
   Done: the up-cast case now comes before the negative-scale one, so a 
widening between decimals, such as `DECIMAL(3, -2)` to `DECIMAL(10, 0)`, also 
to a negative scale, is accepted in every mode, and so is a cast of one to a 
`FLOAT` or `DOUBLE`, which goes through a `BigDecimal`. `ExprUtilsSuite` checks 
and evaluates them in ANSI, LEGACY and TRY mode, and 
`InferFiltersFromConstraintsSuite` that `x = y AND y > 5` over a `DECIMAL(3, 
-2)` and a `DECIMAL(10, 0)` infers `CAST(x AS DECIMAL(10, 0)) > 5` again. The 
other casts from or to a negative scale, such as to or from an integral type, 
are still left out outside TRY mode, and from a string also in TRY mode. As 
`canEvaluateUnconditionally` now takes every numeric up-cast, 
`InjectRuntimeFilter` no longer needs its own stand-in for them, so this commit 
removes it, and the two checks agree on these casts.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -266,20 +307,113 @@ object ExprUtils extends EvalHelper with QueryErrorsBase 
{
     e.deterministic && !e.containsPattern(PLAN_EXPRESSION) &&
       canEvaluateUnconditionallyInternal(e)
 
+  // Only the numeric pairs are taken from `Cast.canUpCast`, which also covers 
e.g. DATE to
+  // TIMESTAMP, which can overflow, and casts between complex types. Among the 
numeric ones, it
+  // only takes a decimal to an integral type whose values all fit.
+  private def isNumericUpCast(from: DataType, to: DataType): Boolean = (from, 
to) match {
+    case (_: NumericType, _: NumericType) => Cast.canUpCast(from, to)
+    case _ => false
+  }
+
+  // Whether a cast can not fail. A cast of a date to a timestamp is left out 
also in LEGACY mode,
+  // as converting a date far from the epoch to microseconds overflows there.
+  private def cannotFailCast(c: Cast): Boolean = (c.child.dataType, 
c.dataType) match {
+    // Left out whether or not it can fail, as it may tell -0.0 from 0.0: see
+    // `canEvaluateUnconditionally`.
+    case (from, to) if tellsSignedZeros(from, to) => false
+    // TRY mode catches the errors of the cast, but not from a string, which 
runs the LEGACY cast.
+    case (from, to) if hasNegativeScale(from) || hasNegativeScale(to) =>
+      c.evalMode == EvalMode.TRY && !from.isInstanceOf[StringType]
+    case (from, to) if isNumericUpCast(from, to) => true
+    // `Decimal.toDouble` and `Decimal.toFloat` round, and do not check the 
range in ANSI mode.
+    case (_: DecimalType, FloatType | DoubleType) => true
+    case (TimestampType | TimestampNTZType, DateType) => true
+    // A CHAR or VARCHAR target checks the length of the string. A string to a 
STRING of another
+    // collation, as `CollationTypeCoercion` adds for an explicit `COLLATE`, 
keeps the value.
+    case (_: NumericType | BooleanType | _: StringType, s: StringType)
+        if StringHelper.isPlainString(s) => true
+    case _ if c.evalMode == EvalMode.TRY => true
+    // `Cast.isNoThrowLegacyCast` covers the numbers, booleans and strings. A 
string to a date or
+    // a timestamp does not raise in LEGACY mode either: the parsers catch the 
errors and return
+    // None, which becomes NULL.
+    case (_: StringType, DateType | TimestampType | TimestampNTZType)
+        if c.evalMode == EvalMode.LEGACY => true
+    case (from, to) if c.evalMode == EvalMode.LEGACY => 
Cast.isNoThrowLegacyCast(from, to)
+    case _ => false
+  }
+
+  // Whether the source type has a FLOAT or DOUBLE and the target type a 
STRING or VARIANT in it,
+  // so that the cast may keep the sign of a zero, e.g. -0.0 as '-0.0'. This 
is conservative: it
+  // does not match the fields of the types.
+  private def tellsSignedZeros(from: DataType, to: DataType): Boolean =
+    from.existsRecursively(t => t == FloatType || t == DoubleType) &&
+      to.existsRecursively(t => t.isInstanceOf[StringType] || t == VariantType)
+
+  private def hasNegativeScale(dt: DataType): Boolean = dt.existsRecursively {
+    case d: DecimalType => d.scale < 0
+    case _ => false
+  }
+
+  // Whether numeric arithmetic can not fail, in its own eval mode.
+  private def cannotFailArithmetic(b: BinaryArithmetic): Boolean = {
+    b.children.forall(isNumericOfNonNegativeScale) && (b match {
+      // Over FLOAT and DOUBLE, they do not check for an overflow, also in 
ANSI mode. Divide,
+      // Remainder and Pmod raise on a zero divisor in ANSI mode, also over 
them.
+      case _: Add | _: Subtract | _: Multiply if 
b.children.forall(isFloatOrDouble) => true
+      case _ if b.evalMode == EvalMode.ANSI => false
+      case _: Add | _: Subtract | _: Multiply | _: Divide | _: Remainder => 
true

Review Comment:
   Right, thanks. The six SPARK-60702 tests that use arithmetic or casts as 
keys or creation sides that can fail now set ANSI mode in `withDppTestConf`, 
and pass with `SPARK_ANSI_SQL_MODE=false` too. A new test checks that a key `f5 
- 1`, and a creation side with `c2 + 1` and `a2 - 1`, get a bloom filter with 
ANSI mode off, and that the queries, which return rows, return the same rows as 
without it, but get none with ANSI mode on.



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