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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -564,6 +582,27 @@ trait Nondeterministic extends Expression {
   protected def evalInternal(input: InternalRow): Any
 }
 
+/**
+ * Trait to indicate the expression does not throw an exception by itself when 
they are evaluated.
+ * For example, UDFs, [[AssertTrue]], etc can throw an exception when they are 
executed.
+ * In such case, it is necessary to call [[Expression.eval]], and the 
optimization rule should
+ * not ignore it.
+ *
+ * This trait can be used in an optimization rule such as
+ * [[org.apache.spark.sql.catalyst.optimizer.ConstantFolding]] to fold the 
expressions that
+ * do not need to execute, for example, `size(array(c0, c1, c2))`. That rule 
only does so for
+ * [[CreateArray]] and [[CreateNamedStruct]] for now.
+ *
+ * Mixing it in is a promise by the author of the expression that it is always 
total, as
+ * [[Expression.isTotal]] defines it: it must not raise for any input of its 
children, in any eval
+ * mode, and it must give equal results for equal children of a binary-stable 
type. The promise
+ * covers every subclass of the expression that mixes it in. An expression 
that is total only
+ * for some input types or in some eval modes overrides [[Expression.isTotal]] 
instead.
+ */
+trait NoThrow extends Expression {

Review Comment:
   This changes `NoThrow` from a plain marker trait (previously in 
`complexTypeCreator.scala`) to `trait NoThrow extends Expression`, and 
`ConstantFolding` no longer matches on `NoThrow`. Although catalyst is not a 
public API, third-party expressions that mixed in `NoThrow` to enable 
`ConstantFolding` would silently lose that folding and instead become eligible 
for `canEvaluateUnconditionally` and `ConstantPropagation` via `isTotal = 
true`. Also, non-`Expression` types mixing it in would fail to compile. It 
might be worth mentioning this in the PR description.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -268,13 +268,14 @@ object ExprUtils extends EvalHelper with QueryErrorsBase {
    * branch of an If/CaseWhen, or hoisting a streamed-side join conjunct above 
the probe
    * so it also runs for streamed rows that have no match.
    *
-   * Only an allowlist of total, deterministic expressions qualifies:
+   * Only total, deterministic expressions qualify. Each expression declares 
whether it is total
+   * itself, with [[Expression.isTotal]], so there is no list to keep here; 
the ones that do are:

Review Comment:
   nit. This says `there is no list to keep here`, but the following bullets 
still enumerate the expressions, casts, and arithmetic rules, which need to be 
kept in sync with `Cast.isTotalCast` and the arithmetic `isTotal` overrides 
manually. Also, the first bullet (leaves) doesn't declare `isTotal`. They are 
accepted directly by `canEvaluateUnconditionallyInternal`, and `ExprUtilsSuite` 
asserts `!Literal(1L).isTotal`. Shall we trim this list and point to 
`Expression.isTotal` and the class lists in `ExprUtilsSuite` instead?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -564,6 +582,27 @@ trait Nondeterministic extends Expression {
   protected def evalInternal(input: InternalRow): Any
 }
 
+/**
+ * Trait to indicate the expression does not throw an exception by itself when 
they are evaluated.
+ * For example, UDFs, [[AssertTrue]], etc can throw an exception when they are 
executed.
+ * In such case, it is necessary to call [[Expression.eval]], and the 
optimization rule should
+ * not ignore it.
+ *
+ * This trait can be used in an optimization rule such as
+ * [[org.apache.spark.sql.catalyst.optimizer.ConstantFolding]] to fold the 
expressions that
+ * do not need to execute, for example, `size(array(c0, c1, c2))`. That rule 
only does so for
+ * [[CreateArray]] and [[CreateNamedStruct]] for now.
+ *
+ * Mixing it in is a promise by the author of the expression that it is always 
total, as
+ * [[Expression.isTotal]] defines it: it must not raise for any input of its 
children, in any eval
+ * mode, and it must give equal results for equal children of a binary-stable 
type. The promise
+ * covers every subclass of the expression that mixes it in. An expression 
that is total only
+ * for some input types or in some eval modes overrides [[Expression.isTotal]] 
instead.
+ */
+trait NoThrow extends Expression {
+  final override def isTotal: Boolean = true

Review Comment:
   Since `isTotal` is `final` here and `NoThrow` is mixed into abstract bases 
and traits (`BinaryComparison`, `GetDateField`, `GetTimeField`), every current 
and future subclass becomes total automatically without a way to opt out. This 
includes subclasses in other modules, which the class-scan test in 
`ExprUtilsSuite` cannot see because it only scans the catalyst classes. The 
scaladoc documents this promise, but shall we drop `final` (or mix `NoThrow` 
into the concrete classes only) so that a future subclass whose evaluation can 
raise is able to override `isTotal`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -64,7 +64,10 @@ object ConstantFolding extends Rule[LogicalPlan] {
         hasNoSideEffect(c.child)
       case _ => false
     }
-    case _: NoThrow if e.deterministic => e.children.forall(hasNoSideEffect)
+    // Only these two of the expressions marked `NoThrow`, as before the other 
expressions that

Review Comment:
   Matching `CreateArray | CreateNamedStruct` by name keeps the previous 
folding behavior, which makes sense for this PR. However, the declaration 
(`NoThrow`/`isTotal`) no longer drives `ConstantFolding`, and the new test in 
`ConstantFoldingSuite` pins that `size(array(i > 1))`, `Coalesce` and `Length` 
are not folded although they cannot fail. Could you add a TODO with a follow-up 
JIRA to revisit this with `isTotal`, so that a future improvement doesn't look 
like a regression?



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala:
##########
@@ -583,6 +589,145 @@ class ExprUtilsSuite extends SparkFunSuite with SQLHelper 
{
     }
   }
 
+  test("isTotalOperator: the expressions that are always total are marked 
NoThrow") {
+    val s = AttributeReference("s", StringType)()
+    val b = AttributeReference("b", BooleanType)()
+    val d = AttributeReference("d", DoubleType)()
+    val date = AttributeReference("date", DateType)()
+    val ts = AttributeReference("ts", TimestampType)()
+    val field = StructField("f", LongType)
+    val struct = AttributeReference("st", StructType(Seq(field)))()
+    val arr = AttributeReference("arr", ArrayType(struct.dataType))()
+    val map = AttributeReference("m", MapType(LongType, LongType))()
+    val always = Seq[Expression](
+      GetStructField(struct, 0), GetArrayStructFields(arr, field, 0, 1, 
containsNull = true),
+      GetMapValue(map, a), CreateArray(Seq(a)), 
CreateNamedStruct(Seq(Literal("f"), a)),
+      Collate(s, ResolvedCollation("UNICODE_CI")),
+      And(b, b), Or(b, b), Not(b), EqualTo(a, a), EqualNullSafe(a, a), 
LessThan(a, a),
+      LessThanOrEqual(a, a), GreaterThan(a, a), GreaterThanOrEqual(a, a),
+      IsNull(a), IsNotNull(a), IsNaN(d), new NullIf(a, a), Coalesce(Seq(a, a)),
+      In(a, Seq(Literal(1L))), InSet(a, Set[Any](1L)),
+      Size(arr, legacySizeOfNull = true), Size(arr, legacySizeOfNull = false),
+      StartsWith(s, s), EndsWith(s, s), Contains(s, s), Length(s), 
OctetLength(s),
+      Substring(s, Literal(1), Literal(2)),
+      Year(date), YearOfWeek(date), Quarter(date), Month(date), 
DayOfMonth(date),
+      DayOfYear(date), DayOfWeek(date), WeekDay(date), WeekOfYear(date), 
MonthName(date),
+      DayName(date), Hour(ts, Some("UTC")), Minute(ts, Some("UTC")), 
Second(ts, Some("UTC")),
+      SecondWithFraction(ts, Some("UTC")))
+    always.foreach { e =>
+      assert(e.isInstanceOf[NoThrow], e)
+      assert(e.isTotal, e)
+      assert(ExprUtils.isTotalOperator(e), e)
+    }
+    // An expression that says nothing is not total, whatever it does. Neither 
are the leaves,
+    // which `canEvaluateUnconditionally` accepts by itself.
+    val undeclared = Seq[Expression](a, Literal(1L), GetArrayItem(arr, 
Literal(0)),
+      ElementAt(arr, Literal(1)), CreateMap(Seq(a, a)), Like(s, s, '\\'), 
RLike(s, s), Upper(s),
+      If(b, a, a), CaseWhen(Seq((b, a)), a), UnaryPositive(a), BitwiseAnd(a, 
a), BitwiseOr(a, a),
+      BitwiseXor(a, a), BitwiseNot(a), Rand(Literal(0L)))
+    undeclared.foreach { e =>
+      assert(!e.isInstanceOf[NoThrow], e)
+      assert(!e.isTotal, e)
+      assert(!ExprUtils.isTotalOperator(e), e)
+    }
+  }
+
+  test("isTotalOperator: the expressions that are total in some eval modes or 
over some types") {
+    val (legacyMode, ansiMode, tryCast) = (EvalMode.LEGACY, EvalMode.ANSI, 
EvalMode.TRY)
+    val d = AttributeReference("d", DoubleType)()
+    val dec = AttributeReference("dec", DecimalType(10, 2))()
+    val s = AttributeReference("s", StringType)()
+    val date = AttributeReference("date", DateType)()
+    val interval = AttributeReference("i", DayTimeIntervalType())()
+    def modesOf(build: EvalMode.Value => Expression): Set[EvalMode.Value] =
+      Seq(legacyMode, ansiMode, tryCast).filter { mode =>
+        val e = build(mode)
+        assert(!e.isInstanceOf[NoThrow], e)
+        assert(ExprUtils.isTotalOperator(e) === e.isTotal, e)
+        e.isTotal
+      }.toSet
+    val all = Set(legacyMode, ansiMode, tryCast)
+    val none = Set.empty[EvalMode.Value]
+    def ctx(mode: EvalMode.Value): NumericEvalContext = 
NumericEvalContext(mode)
+
+    // Add, Subtract and Multiply: outside ANSI mode, and over FLOAT and 
DOUBLE in every mode.
+    Seq[(Expression, Expression, NumericEvalContext) => Expression](Add(_, _, 
_),
+        Subtract(_, _, _), Multiply(_, _, _)).foreach { build =>
+      assert(modesOf(m => build(a, a, ctx(m))) === Set(legacyMode, tryCast))
+      assert(modesOf(m => build(dec, dec, ctx(m))) === Set(legacyMode, 
tryCast))
+      assert(modesOf(m => build(d, d, ctx(m))) === all)
+      assert(modesOf(m => build(interval, interval, ctx(m))) === none)
+    }
+    // Divide and Remainder: outside ANSI mode, also over FLOAT and DOUBLE.
+    Seq[(Expression, Expression, NumericEvalContext) => Expression](Divide(_, 
_, _),
+        Remainder(_, _, _)).foreach { build =>
+      assert(modesOf(m => build(d, d, ctx(m))) === Set(legacyMode, tryCast))
+      assert(modesOf(m => build(dec, dec, ctx(m))) === Set(legacyMode, 
tryCast))
+    }
+    // IntegralDivide and Pmod: only in LEGACY mode.
+    Seq[(Expression, Expression, NumericEvalContext) => 
Expression](IntegralDivide(_, _, _),
+        Pmod(_, _, _)).foreach { build =>
+      assert(modesOf(m => build(a, a, ctx(m))) === Set(legacyMode))
+      assert(modesOf(m => build(interval, a, ctx(m))) === none)
+    }
+    // UnaryMinus and Abs: over the integral types without `failOnError`, and 
over the fractional
+    // types with it too.
+    Seq[(Expression, Boolean) => Expression](UnaryMinus(_, _), Abs(_, 
_)).foreach { build =>
+      assert(build(a, false).isTotal && !build(a, true).isTotal)
+      Seq(d, dec).foreach(x => assert(build(x, false).isTotal && build(x, 
true).isTotal, x))
+      assert(!build(interval, false).isTotal && !build(interval, true).isTotal)
+    }
+    // Cast: by the types and the eval mode.
+    def castModes(from: Expression, to: DataType): Set[EvalMode.Value] =
+      modesOf(m => Cast(from, to, Some("UTC"), m))
+    assert(castModes(a, DecimalType(20, 0)) === all)
+    assert(castModes(dec, DoubleType) === all)
+    assert(castModes(a, StringType) === all)
+    assert(castModes(a, IntegerType) === Set(legacyMode, tryCast))
+    assert(castModes(s, LongType) === Set(legacyMode, tryCast))
+    assert(castModes(s, DateType) === Set(legacyMode, tryCast))
+    assert(castModes(date, TimestampType) === Set(tryCast))
+    assert(castModes(a, VarcharType(3)) === Set(tryCast))
+    assert(castModes(d, StringType) === none)
+    assert(castModes(AttributeReference("u", new TestUDT.MyDenseVectorUDT)(), 
StringType) === none)
+  }
+
+  test("isTotalOperator: the expression classes that declare themselves 
total") {
+    // Every expression class of catalyst, from its jar or its classes 
directory.
+    val root = new 
File(classOf[Expression].getProtectionDomain.getCodeSource.getLocation.toURI)
+    val files: Seq[String] = if (root.isDirectory) {
+      def walk(f: File): Seq[File] =
+        if (f.isDirectory) f.listFiles().toSeq.flatMap(walk) else Seq(f)
+      walk(root).map(f => root.toURI.relativize(f.toURI).getPath)
+    } else {
+      SparkErrorUtils.tryWithResource(new 
JarFile(root))(_.entries().asScala.map(_.getName).toList)
+    }
+    val classes: Seq[Class[_]] = files.filter(_.endsWith(".class")).map { path 
=>
+      val name = path.stripSuffix(".class").replace('/', '.')
+      Utils.classForName[Any](name, initialize = false)

Review Comment:
   This loads every `.class` in the catalyst jar or classes directory. It can 
fail for reasons unrelated to `isTotal`, e.g., stale classes left in 
`target/classes` after an incremental build, or a class whose dependency is not 
on the test classpath (`NoClassDefFoundError`). In addition, `getCodeSource` 
can be `null` under some class loaders. Could you make this more robust, e.g., 
by limiting the scan to the `org/apache/spark/sql/catalyst/expressions/` prefix 
and skipping classes that fail to load with `LinkageError`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala:
##########
@@ -174,6 +183,15 @@ case class Abs(child: Expression, failOnError: Boolean = 
SQLConf.get.ansiEnabled
 
   override def dataType: DataType = child.dataType
 
+  // It checks for an overflow only over the integral types, and only when 
`failOnError` is set.
+  // Over a DAY TO SECOND or YEAR TO MONTH interval, it can overflow in every 
mode, and intervals
+  // are left out.
+  override def isTotal: Boolean = child.dataType match {

Review Comment:
   nit. This `isTotal` body and its comment are identical to 
`UnaryMinus.isTotal`. Similarly, `Add`/`Subtract`/`Multiply`, 
`Divide`/`Remainder`, and `IntegralDivide`/`Pmod` share the same bodies. Shall 
we extract a few shared helpers (e.g., in `BinaryArithmetic`) so that a rule 
change doesn't need to touch nine places?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -615,6 +615,108 @@ object Cast extends QueryErrorsBase {
     case _ => false
   }
 
+  /**
+   * Returns true if a cast from `from` type to `to` type in `evalMode` is 
total, as
+   * [[Expression.isTotal]] defines it: it never fails at runtime, and it 
gives equal results for
+   * equal values. The patterns matched reflect the current implementation in 
the Cast node and
+   * must stay in sync with it.
+   *
+   * A cast of a value with a FLOAT or DOUBLE in it to a type with a STRING or 
a VARIANT in it is
+   * left out whether or not it can fail, as it tells -0.0 from 0.0, which are 
equal. So is every
+   * cast from or to a type with a UDT in it, which renders its value with its 
own
+   * `stringifyValue`, or a Python UDT as its `sqlType`, which can tell apart 
values that are
+   * equal, and the checks here do not look inside it. The target is checked 
too, defensively,
+   * although only a UDT or a NULL can be cast to one.
+   *
+   * Among the other casts, the result is the union of the ones that can not 
fail in any eval mode
+   * and of the ones that can not fail in `evalMode`, so it does not depend on 
the order of the
+   * checks.
+   */
+  def isTotalCast(from: DataType, to: DataType, evalMode: EvalMode.Value): 
Boolean =
+    !tellsSignedZeros(from, to) && !hasUserDefinedType(from) && 
!hasUserDefinedType(to) &&
+      (cannotFailInAnyMode(from, to) || cannotFailInMode(from, to, evalMode))
+
+  // 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)
+
+  // `existsRecursively` does not look inside a UDT, so neither does this.
+  private def hasUserDefinedType(dt: DataType): Boolean =
+    dt.existsRecursively(_.isInstanceOf[UserDefinedType[_]])
+
+  /**
+   * Returns true if the type has a decimal of a negative scale in it
+   * (`spark.sql.legacy.allowNegativeScaleOfDecimal`).
+   */
+  private[expressions] def hasNegativeScale(dt: DataType): Boolean = 
dt.existsRecursively {

Review Comment:
   nit. `hasNegativeScale` is a pure `DataType` predicate, and 
`BinaryArithmetic.hasNumericOperands` now depends on `object Cast` only for 
this. How about moving it to a type utility such as `TypeUtils`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -741,6 +843,8 @@ case class Cast(
 
   override protected def withNewChildInternal(newChild: Expression): Cast = 
copy(child = newChild)
 
+  override def isTotal: Boolean = Cast.isTotalCast(child.dataType, dataType, 
evalMode)

Review Comment:
   Since `isTotal` is now a public method of every `Expression`, note that this 
override (and the arithmetic ones) reads `child.dataType` and throws on an 
unresolved child, while `NoThrow` expressions return `true` regardless. All 
current callers run on resolved plans, so this is fine for now, but it might be 
worth mentioning in the `Expression.isTotal` scaladoc that it is meant for 
resolved expressions.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -615,6 +615,108 @@ object Cast extends QueryErrorsBase {
     case _ => false
   }
 
+  /**
+   * Returns true if a cast from `from` type to `to` type in `evalMode` is 
total, as
+   * [[Expression.isTotal]] defines it: it never fails at runtime, and it 
gives equal results for
+   * equal values. The patterns matched reflect the current implementation in 
the Cast node and
+   * must stay in sync with it.
+   *
+   * A cast of a value with a FLOAT or DOUBLE in it to a type with a STRING or 
a VARIANT in it is
+   * left out whether or not it can fail, as it tells -0.0 from 0.0, which are 
equal. So is every
+   * cast from or to a type with a UDT in it, which renders its value with its 
own
+   * `stringifyValue`, or a Python UDT as its `sqlType`, which can tell apart 
values that are
+   * equal, and the checks here do not look inside it. The target is checked 
too, defensively,
+   * although only a UDT or a NULL can be cast to one.
+   *
+   * Among the other casts, the result is the union of the ones that can not 
fail in any eval mode
+   * and of the ones that can not fail in `evalMode`, so it does not depend on 
the order of the
+   * checks.
+   */
+  def isTotalCast(from: DataType, to: DataType, evalMode: EvalMode.Value): 
Boolean =
+    !tellsSignedZeros(from, to) && !hasUserDefinedType(from) && 
!hasUserDefinedType(to) &&
+      (cannotFailInAnyMode(from, to) || cannotFailInMode(from, to, evalMode))
+
+  // 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)
+
+  // `existsRecursively` does not look inside a UDT, so neither does this.
+  private def hasUserDefinedType(dt: DataType): Boolean =
+    dt.existsRecursively(_.isInstanceOf[UserDefinedType[_]])
+
+  /**
+   * Returns true if the type has a decimal of a negative scale in it
+   * (`spark.sql.legacy.allowNegativeScaleOfDecimal`).
+   */
+  private[expressions] def hasNegativeScale(dt: DataType): Boolean = 
dt.existsRecursively {
+    case d: DecimalType => d.scale < 0
+    case _ => false
+  }
+
+  // The casts that can not fail in any eval mode, also in ANSI mode.
+  private def cannotFailInAnyMode(from: DataType, to: DataType): Boolean =
+    // A numeric up-cast holds also from or to a decimal of a negative scale, 
as a widening between
+    // decimals never calls `Decimal.toLong`; a change to a negative scale 
only checks that
+    // `spark.sql.legacy.allowNegativeScaleOfDecimal` is on. So does a decimal 
to a FLOAT or a
+    // DOUBLE. The other ones do not: `Decimal.toLong` raises for a decimal of 
a negative scale.
+    isNumericUpCast(from, to) || isDecimalToFloatOrDouble(from, to) ||
+      (!hasNegativeScale(from) && !hasNegativeScale(to) &&
+        (isTimestampToDate(from, to) || isToPlainString(from, to)))
+
+  // The casts that can not fail in the given eval mode but can in another 
one: outside ANSI mode,
+  // the casts that return NULL, wrap or clamp for a value they can not 
convert.
+  private def cannotFailInMode(from: DataType, to: DataType, evalMode: 
EvalMode.Value): Boolean = {
+    val negativeScale = hasNegativeScale(from) || hasNegativeScale(to)
+    evalMode match {
+      // TRY mode catches the errors of the cast, but not from a string, which 
runs the LEGACY
+      // cast, and that one raises for a decimal of a negative scale.
+      case EvalMode.TRY => !negativeScale || !from.isInstanceOf[StringType]
+      // 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.
+      case EvalMode.LEGACY =>
+        !negativeScale && (isStringToDatetime(from, to) || 
isNoThrowLegacyCast(from, to))
+      case EvalMode.ANSI => false
+    }
+  }
+
+  // Only the numeric pairs are taken from `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) => canUpCast(from, to)
+    case _ => false
+  }
+
+  // `Decimal.toDouble` and `Decimal.toFloat` round through a `BigDecimal`, 
also for a negative
+  // scale, and do not check the range in ANSI mode.
+  private def isDecimalToFloatOrDouble(from: DataType, to: DataType): Boolean 
= (from, to) match {
+    case (_: DecimalType, FloatType | DoubleType) => true
+    case _ => false
+  }
+
+  private def isTimestampToDate(from: DataType, to: DataType): Boolean = 
(from, to) match {
+    case (TimestampType | TimestampNTZType, DateType) => true
+    case _ => false
+  }
+
+  // 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.
+  private def isToPlainString(from: DataType, to: DataType): Boolean = (from, 
to) match {

Review Comment:
   nit. This is the same as the second case of `isNoThrowLegacyCast` above. 
Shall we reuse `isToPlainString` there to keep the string-target rule in one 
place?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala:
##########
@@ -215,6 +233,21 @@ abstract class BinaryArithmetic extends BinaryOperator 
with SupportQueryContext
 
   def evalMode: EvalMode.Value = evalContext.evalMode
 
+  /**
+   * Whether both operands are numbers of a non-negative scale. This is what 
the subclasses that
+   * override [[isTotal]] require first: arithmetic over a DAY TO SECOND or 
YEAR TO MONTH interval
+   * can overflow in every eval mode, and over a decimal of a negative scale
+   * (`spark.sql.legacy.allowNegativeScaleOfDecimal`) `Decimal.%` raises for a 
very negative one.
+   * A subclass that does not override [[isTotal]] is not taken as total.
+   */
+  protected def hasNumericOperands: Boolean = children.forall { e =>

Review Comment:
   nit. `hasNumericOperands` also rejects decimals of a negative scale, which 
is not obvious from the name. What about a name that reflects its purpose, 
e.g., `hasTotalNumericOperands`?



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -615,6 +615,108 @@ object Cast extends QueryErrorsBase {
     case _ => false
   }
 
+  /**
+   * Returns true if a cast from `from` type to `to` type in `evalMode` is 
total, as
+   * [[Expression.isTotal]] defines it: it never fails at runtime, and it 
gives equal results for
+   * equal values. The patterns matched reflect the current implementation in 
the Cast node and
+   * must stay in sync with it.
+   *
+   * A cast of a value with a FLOAT or DOUBLE in it to a type with a STRING or 
a VARIANT in it is
+   * left out whether or not it can fail, as it tells -0.0 from 0.0, which are 
equal. So is every
+   * cast from or to a type with a UDT in it, which renders its value with its 
own
+   * `stringifyValue`, or a Python UDT as its `sqlType`, which can tell apart 
values that are
+   * equal, and the checks here do not look inside it. The target is checked 
too, defensively,
+   * although only a UDT or a NULL can be cast to one.
+   *
+   * Among the other casts, the result is the union of the ones that can not 
fail in any eval mode
+   * and of the ones that can not fail in `evalMode`, so it does not depend on 
the order of the
+   * checks.
+   */
+  def isTotalCast(from: DataType, to: DataType, evalMode: EvalMode.Value): 
Boolean =
+    !tellsSignedZeros(from, to) && !hasUserDefinedType(from) && 
!hasUserDefinedType(to) &&
+      (cannotFailInAnyMode(from, to) || cannotFailInMode(from, to, evalMode))
+
+  // 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)
+
+  // `existsRecursively` does not look inside a UDT, so neither does this.
+  private def hasUserDefinedType(dt: DataType): Boolean =
+    dt.existsRecursively(_.isInstanceOf[UserDefinedType[_]])
+
+  /**
+   * Returns true if the type has a decimal of a negative scale in it
+   * (`spark.sql.legacy.allowNegativeScaleOfDecimal`).
+   */
+  private[expressions] def hasNegativeScale(dt: DataType): Boolean = 
dt.existsRecursively {
+    case d: DecimalType => d.scale < 0
+    case _ => false
+  }
+
+  // The casts that can not fail in any eval mode, also in ANSI mode.
+  private def cannotFailInAnyMode(from: DataType, to: DataType): Boolean =
+    // A numeric up-cast holds also from or to a decimal of a negative scale, 
as a widening between
+    // decimals never calls `Decimal.toLong`; a change to a negative scale 
only checks that
+    // `spark.sql.legacy.allowNegativeScaleOfDecimal` is on. So does a decimal 
to a FLOAT or a
+    // DOUBLE. The other ones do not: `Decimal.toLong` raises for a decimal of 
a negative scale.
+    isNumericUpCast(from, to) || isDecimalToFloatOrDouble(from, to) ||
+      (!hasNegativeScale(from) && !hasNegativeScale(to) &&
+        (isTimestampToDate(from, to) || isToPlainString(from, to)))
+
+  // The casts that can not fail in the given eval mode but can in another 
one: outside ANSI mode,
+  // the casts that return NULL, wrap or clamp for a value they can not 
convert.
+  private def cannotFailInMode(from: DataType, to: DataType, evalMode: 
EvalMode.Value): Boolean = {

Review Comment:
   nit. `isTotalCast` can traverse the type trees several times per call 
(`hasNegativeScale(from)` and `hasNegativeScale(to)` are computed in both 
`cannotFailInAnyMode` and `cannotFailInMode`), and `Cast.isTotal` is a `def` 
which `ConstantPropagation` may call repeatedly. Shall we compute 
`negativeScale` once in `isTotalCast`, or make `Cast.isTotal` a `lazy val`?



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