spark-test commented on code in PR #60469:
URL: https://github.com/apache/spark/pull/60469#discussion_r4571584506
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -610,11 +610,108 @@ object Cast extends QueryErrorsBase {
*/
def isNoThrowLegacyCast(from: DataType, to: DataType): Boolean = (from, to)
match {
case (_: NumericType | BooleanType | _: StringType, _: NumericType |
BooleanType) => true
+ case _ => isToPlainString(from, to)
+ }
+
+ /**
+ * 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 = {
+ // Whether a decimal of a negative scale
(`spark.sql.legacy.allowNegativeScaleOfDecimal`) is
+ // cast from or to.
+ val negativeScale = TypeUtils.hasNegativeScale(from) ||
TypeUtils.hasNegativeScale(to)
Review Comment:
**Nit (P3):** `negativeScale` is a strict `val`, so it is computed before
`tellsSignedZeros` and `hasUserDefinedType` get to reject the cast, and
`hasNegativeScale` is `existsRecursively`, which visits every node of a type
that has no negative-scale decimal. So a check of e.g. `CAST(s AS STRING)`,
with `s` a wide struct whose first field is a DOUBLE, now walks all of `s`
before returning the same false, where the removed `ExprUtils.cannotFailCast`
(and this PR's first commit) returned right after `tellsSignedZeros`. A cast
between nested types with a UDT inside pays the same walk. It happens in every
caller of `isTotalOperator` and `canEvaluateUnconditionally`, such as
`InferFiltersFromConstraints`, `ConstantPropagation`, `CombineFilters` and the
filter's `mayRaise`, during optimization, planning and code generation only;
plans and results do not change. Computing it once after the exclusions keeps
the single computation that the earlier review asked for, e.g.:
```scala
!tellsSignedZeros(from, to) && !hasUserDefinedType(from) &&
!hasUserDefinedType(to) && {
val negativeScale = TypeUtils.hasNegativeScale(from) ||
TypeUtils.hasNegativeScale(to)
cannotFailInAnyMode(from, to, negativeScale) ||
cannotFailInMode(from, to, evalMode, negativeScale)
}
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/60469#discussion_r4569454097).
**Verification:**
- **Inspection:** `isTotalCast` computes `TypeUtils.hasNegativeScale` only
after `tellsSignedZeros` and both `hasUserDefinedType` checks pass, at most
once per call, and combines the same conditions as before, so its result is
unchanged for every cast and eval mode.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -268,59 +268,26 @@ 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:
- * - leaves: attribute references, literals and the collation of a Collate;
- * - total accessors: GetStructField, GetArrayStructFields and GetMapValue
never throw.
- * Note that GetArrayItem/ElementAt are NOT included: they throw on
invalid ordinals
- * when ANSI mode is on;
- * - the expressions marked [[NoThrow]], such as CreateArray and
CreateNamedStruct, which
- * only build a value from their children, as `ConstantFolding` assumes
too;
- * - logic/predicates: And, Or, Not, comparisons, IsNull, IsNotNull,
IsNaN, NullIf,
- * Coalesce, In and InSet are total boolean functions;
- * - Size, which returns -1 or NULL for a NULL input rather than raising;
- * - StartsWith, EndsWith and Contains, which are total for every
collation, unlike Like
- * and RLike, which raise on an invalid pattern;
- * - Length and OctetLength, which only count the characters or bytes of a
string or binary,
- * and with which `LikeSimplification` guards a StartsWith and an
EndsWith;
- * - Collate, which only changes the collation in the type of a string
(`COLLATE`);
- * - Substring, which returns an empty string for a position out of range;
- * - the fields of a date or a timestamp, such as Year and Hour
(GetDateField and
- * GetTimeField), which only read the date or time of a valid value;
- * - in every mode: a cast that widens a numeric type to another one
(`Cast.canUpCast`),
- * such as the INT to BIGINT cast that type coercion adds to a
comparison, or a cast of a
- * DECIMAL(18, 0), whose values all fit, to BIGINT; a cast of a DECIMAL
to a FLOAT or a
- * DOUBLE, which rounds; a cast of a timestamp to a date; and a cast of
a number other than
- * a FLOAT or DOUBLE, a boolean or a string to a STRING of any
collation, not to a CHAR or
- * VARCHAR, which checks the length;
- * - outside ANSI mode, the casts that return NULL, wrap or clamp for a
value they can not
- * convert: in LEGACY mode, the ones `Cast.isNoThrowLegacyCast` accepts,
between numbers,
- * booleans and strings, except to a CHAR or VARCHAR, and from a string
to a date or a
- * timestamp; in TRY mode (`try_cast`), every cast, which either catches
the errors of the
- * cast or, from a string to a fractional or datetime type, runs the
LEGACY cast;
- * - outside ANSI mode, numeric arithmetic, which returns NULL on a
division by zero or a
- * decimal overflow, and wraps an integral overflow in LEGACY mode and
returns NULL for it
- * in TRY mode: in LEGACY mode, Add, Subtract, Multiply, Divide,
IntegralDivide, Remainder
- * and Pmod, UnaryMinus and Abs; in TRY mode, which only catches the
errors of Add,
- * Subtract and Multiply, and in which Divide and Remainder behave as in
LEGACY mode, those
- * five. Arithmetic over intervals is left out, which over a DAY TO
SECOND or YEAR TO MONTH
- * interval can overflow in every mode;
- * - in every mode, also in ANSI mode, Add, Subtract and Multiply over
FLOAT and DOUBLE, which
- * return an infinity or NaN rather than raising, and UnaryMinus and Abs
over FLOAT, DOUBLE
- * and DECIMAL, which only check for an overflow over the integral types.
- * In every mode, 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, although such a cast to a STRING or a VARIANT
can not fail: it
- * tells -0.0 from 0.0, which are equal, and `InferFiltersFromConstraints`
and
- * `ConstantPropagation` replace an attribute with a value equal to it under
the operators this
- * check accepts (`isTotalOperator`). For the same reason, 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`. Outside TRY mode, and in TRY mode from a string, the casts
from or to a decimal
- * of a negative scale (`spark.sql.legacy.allowNegativeScaleOfDecimal`)
other than the widenings
- * between decimals and the casts to a FLOAT or DOUBLE are left out, as
`Decimal.toLong` raises
- * for one, and in every mode so is the binary arithmetic over one, as
`Decimal.%` raises for a
- * very negative one. UnaryMinus and Abs only negate one and are kept.
- * Anything else (other arithmetic, other casts, other functions, UDFs,
nested IF/CASE
- * WHEN, ...) conservatively returns false. On top of the allowlist, the
expression must be
- * deterministic and must not contain subqueries.
+ * Only a tree of these qualifies:
+ * - at the leaves, attribute references, literals and the collation of a
Collate, which
+ * evaluate to a value they hold or read. They are accepted here, and
declare nothing;
+ * - above them, the expressions that declare themselves total with
[[Expression.isTotal]].
+ * The declaration is on each expression, next to how it evaluates, and
says why it holds:
Review Comment:
**Nit (P3):** This holds for `Cast.isTotalCast` and the arithmetic
overrides, which explain their conditions in comments, but not for the classes
that mix in `NoThrow`: none of the 42 new mixins has a comment (e.g. `Size` in
collectionOperations.scala or `Substring` in stringExpressions.scala), and the
`NoThrow` scaladoc states only the general promise. The reasons the allowlist
gave, e.g. that `Size` returns -1 or NULL for a NULL input, that `Substring`
returns an empty string for a position out of range, that `StartsWith`,
`EndsWith` and `Contains` are total for every collation, and that the date and
time fields only read the date or time of a valid value, were removed with the
list rather than moved. So a maintainer who changes how one of these classes
evaluates is pointed at a reason that is not there. A short comment next to
each mixin, or once on `GetDateField` and `GetTimeField` for the date and time
fields, would make this sentence true without bringing the list back.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60469#discussion_r4569454049).
**Verification:**
- **Inspection:** Each `with NoThrow` mixin in catalyst, or the trait its
class evaluates through, carries a reason for totality that matches what the
base branch's allowlist said for that class.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala:
##########
@@ -583,6 +590,156 @@ 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))
Review Comment:
**Nit (P3):** This block checks `Divide` only over DOUBLE and DECIMAL(10,
2), where `hasTotalNumericOperands` is true. `Divide` has no interval row, as
its `inputType` is DOUBLE or DECIMAL, and the only negative-scale arithmetic
check is the existing one on `Remainder` (lines 263-272), so its copy of the
operand guard has no assertion that fails without it. Before this PR one shared
operand check covered every class, so that `Remainder` test pinned it for
`Divide` too. Reading the code, if a later edit drops `hasTotalNumericOperands
&&` from `Divide.isTotal`, the suite still passes, yet with
`spark.sql.legacy.allowNegativeScaleOfDecimal` on, `Divide` over a DECIMAL(1,
-2147483000) operand becomes total in LEGACY and TRY mode although
`Decimal.div` raises an `ArithmeticException` for it, so the optimizer could
evaluate it on rows the original plan never reached. A row here over such a
decimal, asserting that `Divide` and `Remainder` are total in no eval mode,
would catch that.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60469#discussion_r4569454059).
**Verification:**
- **Regression:** With the negative-scale setting on, Divide over a
DECIMAL(1, -2147483000) operand is total in none of LEGACY, ANSI and TRY mode,
and this check fails when Divide's operand guard is removed.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Cast.scala:
##########
@@ -610,11 +610,108 @@ object Cast extends QueryErrorsBase {
*/
def isNoThrowLegacyCast(from: DataType, to: DataType): Boolean = (from, to)
match {
case (_: NumericType | BooleanType | _: StringType, _: NumericType |
BooleanType) => true
+ case _ => isToPlainString(from, to)
+ }
+
+ /**
+ * 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 = {
+ // Whether a decimal of a negative scale
(`spark.sql.legacy.allowNegativeScaleOfDecimal`) is
+ // cast from or to.
+ val negativeScale = TypeUtils.hasNegativeScale(from) ||
TypeUtils.hasNegativeScale(to)
+ !tellsSignedZeros(from, to) && !hasUserDefinedType(from) &&
!hasUserDefinedType(to) &&
+ (cannotFailInAnyMode(from, to, negativeScale) ||
+ cannotFailInMode(from, to, evalMode, negativeScale))
+ }
+
+ // 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[_]])
+
+ // The casts that can not fail in any eval mode, also in ANSI mode.
+ private def cannotFailInAnyMode(
+ from: DataType, to: DataType, negativeScale: Boolean): 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) ||
+ (!negativeScale && (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,
+ negativeScale: Boolean): Boolean = evalMode match {
+ // TRY mode catches the errors of the cast, but not from a string, which
runs the LEGACY cast,
Review Comment:
**Nit (P3):** `canUseLegacyCastForTryCast` is true only from a string to a
`FractionalType` or a `DatetimeType`; every other TRY cast from a string, e.g.
to an interval or an integral type, runs inside the try/catch in `cast`. Taken
literally, this comment says a TRY cast of a string to an interval runs the
LEGACY cast, which the `isNoThrowLegacyCast` scaladoc lists as able to fail, so
this branch would look wrong for accepting it. The rule itself is right: from a
string, a decimal of a negative scale can only be the target, and that cast
does run the LEGACY cast. Before this PR the sentence sat on the negative-scale
case only, and the `canEvaluateUnconditionally` scaladoc stated the exact rule,
which the follow-up commit removed when trimming that scaladoc; naming the
cases of `canUseLegacyCastForTryCast` here would restore it.
**Verification:**
- **Inspection:** The comment on the TRY branch of `cannotFailInMode`
matches `canUseLegacyCastForTryCast`: in TRY mode, only a cast from a string to
a fractional or datetime type runs the LEGACY cast.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/Expression.scala:
##########
@@ -168,6 +168,27 @@ abstract class Expression extends TreeNode[Expression] {
*/
lazy val throwable: Boolean = children.exists(_.throwable)
+ /**
+ * Returns true if this expression is total by itself, whatever its children
are: it cannot
+ * raise an error for any values of its children of their current types, and
it gives equal
+ * results for equal children of a binary-stable type (strings of a
non-binary collation are
+ * guarded by the callers). This is about this node only, not about its
children, and it is the
+ * declaration that [[ExprUtils.isTotalOperator]] and
[[ExprUtils.canEvaluateUnconditionally]]
+ * read: the optimizer evaluates a total expression on rows it would
otherwise not see, and
+ * replaces a child of it with a value equal to that child.
+ *
+ * Unlike [[throwable]], this is false unless an expression says otherwise,
so an expression
Review Comment:
**Nit (P3):** `throwable` is `children.exists(_.throwable)` (line 169), so
for an expression that says nothing and whose children do not throw it is false
too, and the `canEvaluateUnconditionally` note calls it "opt-in metadata that
most expressions do not override". Read as a contrast of defaults, this
sentence contradicts that note. What differs is that `throwable` also becomes
true through a child, and that its false default claims the expression cannot
throw, the unsafe answer, while a false `isTotal` is the safe answer, which
only leaves the expression out of some optimizations. Saying that directly
would avoid the contradiction, e.g. "Like [[throwable]], this defaults to
false, but here false is the safe answer: an expression that says nothing is
only left out of some optimizations."
**Verification:**
- **Inspection:** The `Expression.isTotal` scaladoc describes the default of
`throwable` accurately and agrees with the `ExprUtils` note that `throwable` is
opt-in metadata.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:
##########
@@ -268,59 +268,26 @@ 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:
- * - leaves: attribute references, literals and the collation of a Collate;
- * - total accessors: GetStructField, GetArrayStructFields and GetMapValue
never throw.
- * Note that GetArrayItem/ElementAt are NOT included: they throw on
invalid ordinals
- * when ANSI mode is on;
- * - the expressions marked [[NoThrow]], such as CreateArray and
CreateNamedStruct, which
- * only build a value from their children, as `ConstantFolding` assumes
too;
- * - logic/predicates: And, Or, Not, comparisons, IsNull, IsNotNull,
IsNaN, NullIf,
- * Coalesce, In and InSet are total boolean functions;
- * - Size, which returns -1 or NULL for a NULL input rather than raising;
- * - StartsWith, EndsWith and Contains, which are total for every
collation, unlike Like
- * and RLike, which raise on an invalid pattern;
- * - Length and OctetLength, which only count the characters or bytes of a
string or binary,
- * and with which `LikeSimplification` guards a StartsWith and an
EndsWith;
- * - Collate, which only changes the collation in the type of a string
(`COLLATE`);
- * - Substring, which returns an empty string for a position out of range;
- * - the fields of a date or a timestamp, such as Year and Hour
(GetDateField and
- * GetTimeField), which only read the date or time of a valid value;
- * - in every mode: a cast that widens a numeric type to another one
(`Cast.canUpCast`),
- * such as the INT to BIGINT cast that type coercion adds to a
comparison, or a cast of a
- * DECIMAL(18, 0), whose values all fit, to BIGINT; a cast of a DECIMAL
to a FLOAT or a
- * DOUBLE, which rounds; a cast of a timestamp to a date; and a cast of
a number other than
- * a FLOAT or DOUBLE, a boolean or a string to a STRING of any
collation, not to a CHAR or
- * VARCHAR, which checks the length;
- * - outside ANSI mode, the casts that return NULL, wrap or clamp for a
value they can not
- * convert: in LEGACY mode, the ones `Cast.isNoThrowLegacyCast` accepts,
between numbers,
- * booleans and strings, except to a CHAR or VARCHAR, and from a string
to a date or a
- * timestamp; in TRY mode (`try_cast`), every cast, which either catches
the errors of the
- * cast or, from a string to a fractional or datetime type, runs the
LEGACY cast;
- * - outside ANSI mode, numeric arithmetic, which returns NULL on a
division by zero or a
- * decimal overflow, and wraps an integral overflow in LEGACY mode and
returns NULL for it
- * in TRY mode: in LEGACY mode, Add, Subtract, Multiply, Divide,
IntegralDivide, Remainder
- * and Pmod, UnaryMinus and Abs; in TRY mode, which only catches the
errors of Add,
- * Subtract and Multiply, and in which Divide and Remainder behave as in
LEGACY mode, those
- * five. Arithmetic over intervals is left out, which over a DAY TO
SECOND or YEAR TO MONTH
- * interval can overflow in every mode;
- * - in every mode, also in ANSI mode, Add, Subtract and Multiply over
FLOAT and DOUBLE, which
- * return an infinity or NaN rather than raising, and UnaryMinus and Abs
over FLOAT, DOUBLE
- * and DECIMAL, which only check for an overflow over the integral types.
- * In every mode, 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, although such a cast to a STRING or a VARIANT
can not fail: it
- * tells -0.0 from 0.0, which are equal, and `InferFiltersFromConstraints`
and
- * `ConstantPropagation` replace an attribute with a value equal to it under
the operators this
- * check accepts (`isTotalOperator`). For the same reason, 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`. Outside TRY mode, and in TRY mode from a string, the casts
from or to a decimal
- * of a negative scale (`spark.sql.legacy.allowNegativeScaleOfDecimal`)
other than the widenings
- * between decimals and the casts to a FLOAT or DOUBLE are left out, as
`Decimal.toLong` raises
- * for one, and in every mode so is the binary arithmetic over one, as
`Decimal.%` raises for a
- * very negative one. UnaryMinus and Abs only negate one and are kept.
- * Anything else (other arithmetic, other casts, other functions, UDFs,
nested IF/CASE
- * WHEN, ...) conservatively returns false. On top of the allowlist, the
expression must be
- * deterministic and must not contain subqueries.
+ * Only a tree of these qualifies:
+ * - at the leaves, attribute references, literals and the collation of a
Collate, which
+ * evaluate to a value they hold or read. They are accepted here, and
declare nothing;
+ * - above them, the expressions that declare themselves total with
[[Expression.isTotal]].
+ * The declaration is on each expression, next to how it evaluates, and
says why it holds:
+ * the expressions that are always total mix in [[NoThrow]], e.g. And, a
comparison, IsNull,
+ * Coalesce, GetStructField, Size, StartsWith, Substring and Year, and
[[Cast]]
+ * (`Cast.isTotalCast`), Add, Subtract, Multiply, Divide,
IntegralDivide, Remainder, Pmod,
+ * UnaryMinus and Abs are total for some input types and eval modes
only. `ExprUtilsSuite`
+ * checks the classes of both kinds against a list.
+ * Some expressions that look alike are not total: GetArrayItem and
ElementAt raise on an invalid
+ * ordinal in ANSI mode, Like and RLike on an invalid pattern, and CreateMap
on a NULL or a
+ * duplicate key.
+ * Being total is more than not raising: `InferFiltersFromConstraints` and
`ConstantPropagation`
+ * replace an attribute with a value equal to it under the operators this
check accepts
+ * (`isTotalOperator`), so e.g. 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, although it can not fail: it tells
-0.0 from 0.0,
Review Comment:
**Nit (P3):** The class this sentence names is what `Cast.tellsSignedZeros`
matches, which "does not match the fields of the types", and it includes casts
that can fail: `VarcharType` extends `StringType`, so a DOUBLE to VARCHAR(3) is
in it and raises on the length check outside TRY mode, and so is a STRUCT<d:
DOUBLE, s: STRING> to STRUCT<d: INT, s: STRING>, which raises in ANSI mode when
`d` overflows. Before the scaladoc was trimmed, it limited the claim to "such a
cast to a STRING or a VARIANT", and the `Cast.isTotalCast` scaladoc says these
casts are left out "whether or not it can fail", so the two docs now disagree.
Naming a cast the claim holds for, such as the DOUBLE to STRING example the
`isTotalOperator` scaladoc uses, or saying "whether or not it can fail" as
`Cast.isTotalCast` does, would fix it; restoring the old clause alone would
still read as covering a VARCHAR target.
**Verification:**
- **Inspection:** The scaladoc's 'can not fail' claim covers none of the
casts this exclusion matches that can fail, such as a DOUBLE to a VARCHAR(3), a
STRUCT<d: DOUBLE, s: STRING> to a STRUCT<d: INT, s: STRING> in ANSI mode, or a
large ARRAY<DOUBLE> to a VARIANT, and its account agrees with the
`Cast.isTotalCast` scaladoc.
--
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]