This is an automated email from the ASF dual-hosted git repository.
sarutak pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/branch-4.x by this push:
new 9a38c2b2c848 [SPARK-60882][4.X][SQL] Accept more expressions that can
not fail in ExprUtils.canEvaluateUnconditionally
9a38c2b2c848 is described below
commit 9a38c2b2c84820d03fc091aa780aef7d1a24b891
Author: Kousuke Saruta <[email protected]>
AuthorDate: Tue Nov 10 00:56:46 2026 +0900
[SPARK-60882][4.X][SQL] Accept more expressions that can not fail in
ExprUtils.canEvaluateUnconditionally
### What changes were proposed in this pull request?
Backport of #60119 to branch-4.x, tailored for it: the changes to
`InjectRuntimeFilter` and `InjectRuntimeFilterSuite` are left out, since
SPARK-60702, which made `InjectRuntimeFilter` use
`ExprUtils.canEvaluateUnconditionally`, is not on branch-4.x. So
`InjectRuntimeFilter` does not call it on branch-4.x, and this PR does not
change it.
`ExprUtils.canEvaluateUnconditionally` tells whether an expression can be
evaluated on rows it would otherwise not see, e.g. outside a short-circuited
branch. It is an allowlist of deterministic expressions that can not fail:
columns, literals, struct and map accessors, `AND` / `OR` / `NOT`, comparisons,
`IS NULL`, `IN` and the like. Its callers are `FilterExec` and the `FILTER
(WHERE ...)` clause of a code-generated aggregate, which share
`GeneratePredicateHelper` and use it to decid [...]
This PR adds the following expressions to `ExprUtils.isTotalOperator`, and
so to the allowlist, each only when its children qualify too. Whether each of
them can fail depends only on the types of its children, not on their values:
- `Size`, which returns -1 or NULL for a NULL input;
- `StartsWith`, `EndsWith` and `Contains`, which do not raise for any
collation, unlike `LIKE` and `RLIKE`, which raise on an invalid pattern, and
`Length` and `OctetLength`, which only count characters or bytes:
`LikeSimplification` rewrites `LIKE 'abc%'` to a `StartsWith`, and `LIKE
'ab%c'` to a `StartsWith` and an `EndsWith` guarded by a `Length` or an
`OctetLength` check;
- `Collate`, which an explicit `COLLATE` builds, and which only changes the
collation in the type of a string, with its collation, which evaluates to its
name;
- the expressions marked `NoThrow`, `CreateArray` and `CreateNamedStruct`,
which only build a value from their children, as `ConstantFolding` assumes for
them too;
- `Substring`, which returns an empty string for a position out of range;
- the fields of a date or a timestamp (`GetDateField` and `GetTimeField`,
e.g. `year`, `month`, `hour`), which only read the date or time of a valid
value;
- the casts that can not fail:
- in every mode: a cast that only widens a numeric type (`Cast.canUpCast`
over numeric types, such as the `INT` to `BIGINT` cast that type coercion adds
to a comparison), which includes a decimal to an integral type only when every
value fits, such as `DECIMAL(18, 0)` to `BIGINT` (SPARK-60943); a cast of a
decimal to a `FLOAT` or `DOUBLE`, which rounds, such as the one type coercion
adds to `amount > 1e3` over a decimal column; a cast of a timestamp to a date;
and a cast of a number [...]
- in LEGACY mode, i.e. with ANSI mode off, the casts that return NULL,
wrap or clamp for a value they can not convert: the ones
`Cast.isNoThrowLegacyCast` (SPARK-60868) accepts, between numbers, booleans and
strings, except to a `CHAR` or `VARCHAR`, and from a string to a date or a
timestamp, whose parsers catch their errors;
- in TRY mode (`try_cast`), every other cast: it either catches the
errors of the cast or, from a string to a fractional or datetime type, runs the
LEGACY cast.
Outside TRY mode, a cast of a date to a timestamp is left out, although
`Cast.canUpCast` accepts it, since converting a date far from the epoch to
microseconds overflows also in LEGACY mode, and so are the other casts, such as
of a date or a timestamp to a string, which this PR does not check. In every
mode, a cast of a value with a `FLOAT` or `DOUBLE` in it to a type with a
`STRING` or `VARIANT` in it is left out, also in LEGACY and TRY mode, although
such a cast to a `STRING` or ` [...]
- numeric arithmetic outside ANSI mode, 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: `Add`, `Subtract`, `Multiply`, `Divide`,
`IntegralDivide`, `Remainder`, `Pmod`, `UnaryMinus` and `Abs` in LEGACY mode,
and in TRY mode (`try_add` and the like) the five that do not raise there:
`Add`, `Subtract` and `Multiply` catch their errors, and `Divide` and
`Remainder` check a zero divisor only [...]
- 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.
`TryEval`, which `try_add` and the like build over non-numeric types, is
left out: its child can be a UDF, which `FilterExec` must not evaluate on more
rows, and subexpression elimination does not stop at it, so it can move a part
of the child that raises out of the `try`. With its child checked, accepting it
would accept nothing that its child does not already.
### Why are the changes needed?
The allowlist rejects these expressions although they can not fail, so its
callers handle them as if they could: `FilterExec` keeps the NULL-conjunct flag
for them, and `StreamedSideJoinCondition`, when enabled, does not hoist e.g. `a
+ 1 > 0` with ANSI mode off, `price * 1.1 > 100` over a `DOUBLE` column or
`substr(s, 1, 4) = '2024'`. PR #59940 (SPARK-60730) uses the same check to
decide which filter conditions written after an expensive one may still be
pushed below a projection; th [...]
### Does this PR introduce _any_ user-facing change?
No change in the results of deterministic queries that do not fail. The
callers above apply their optimizations to more expressions: `FilterExec` and
the `FILTER` clause of a code-generated aggregate generate the code without the
NULL-conjunct flag, and keep the lazy placement of the `IS NOT NULL` checks,
for more conditions, `StreamedSideJoinCondition`, when enabled, hoists more
streamed-side conjuncts, which it then evaluates once per streamed row, also on
rows without a match, `Rew [...]
### How was this patch tested?
New tests in `ExprUtilsSuite`:
- each added expression accepted, the arithmetic and the casts that can
fail in ANSI mode left out there, and each new case left out over a child that
can fail; `IntegralDivide` and `Pmod` in TRY mode, interval arithmetic, also
`UnaryMinus` and `Abs` over intervals, a cast of a date to a timestamp in
LEGACY mode, a cast of a number to a `CHAR` or `VARCHAR` and a cast of a
`DECIMAL(19, 0)` to a `BIGINT` left out, with a check that they do raise, and
`IntegralDivide`, `Remainder` and `P [...]
- each accepted arithmetic expression and cast evaluated without an error,
with and without code generation, over nullable and non-nullable input columns
of every numeric type, on NULL and on the values that raise in ANSI mode: zero
divisors, `Long.MinValue` and `-1`, the largest decimals and a small one that
makes a quotient overflow, also between decimals of different precisions and
scales and without precision loss, NaN and infinities, invalid and out-of-range
strings, such as expo [...]
- `StartsWith`, `EndsWith`, `Contains`, `Length` and `OctetLength`
evaluated without an error, with and without code generation, over binary,
lowercase, ICU and trim collations on empty, ignorable and invalid UTF-8
strings.
Existing tests that used arithmetic or a cast as an expression that can
fail, in `RewriteDistinctAggregatesSuite`,
`SplitStreamedSideJoinConditionSuite`, `WholeStageCodegenSuite` and the
SPARK-60980 test of `FilterPushdownSuite`, now set ANSI mode, or use a cast
that can fail, since the expression is accepted with ANSI mode off; one of them
used a cast of an integer to a string, which can not fail.
`SplitStreamedSideJoinConditionSuite` now also checks that an addition with
ANSI mode o [...]
Each of these mutants fails at least one test, run on master, whose tests
of this change are the same apart from `InjectRuntimeFilterSuite`, which none
of them needs: accepting `IntegralDivide` and `Pmod` in TRY mode, accepting
arithmetic over non-numeric types or in ANSI mode, accepting a cast of a date
to a timestamp in LEGACY mode or every cast in LEGACY mode, dropping the casts
of `Cast.isNoThrowLegacyCast` or of a string to a date or a timestamp in LEGACY
mode, accepting the LEGA [...]
On branch-4.x, with ANSI mode on and with `SPARK_ANSI_SQL_MODE=false`, all
tests in `org.apache.spark.sql.catalyst.optimizer` and `ExprUtilsSuite`, and
`PlanStabilitySuite`s, `SplitStreamedSideJoinConditionSuite`,
`ExistenceJoinSuite`, `OuterJoinSuite`, `WholeStageCodegenSuite`,
`DataFrameAggregateSuite`, `DataFrameSuite`,
`RewriteDistinctAggregatesConditionalQuerySuite`, the `MergeIntoTableSuite`s,
`CollationSuite`, `CollationSQLFunctionsSuite`, `CollationSQLRegexpSuite`,
`SubquerySu [...]
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Kiro CLI
Closes #60231 from sarutak/allowlist-cannot-fail-4.x.
Authored-by: Kousuke Saruta <[email protected]>
Signed-off-by: Kousuke Saruta <[email protected]>
skip-checks: true
---
docs/sql-migration-guide.md | 2 +-
.../spark/sql/catalyst/expressions/ExprUtils.scala | 170 ++++++-
.../catalyst/expressions/complexTypeCreator.scala | 5 +
.../spark/sql/catalyst/optimizer/Optimizer.scala | 7 -
.../optimizer/RewriteDistinctAggregates.scala | 12 +-
.../org/apache/spark/sql/internal/SQLConf.scala | 12 +-
.../sql/catalyst/expressions/ExprUtilsSuite.scala | 551 ++++++++++++++++++++-
.../optimizer/ConstantPropagationSuite.scala | 38 ++
.../catalyst/optimizer/FilterPushdownSuite.scala | 37 +-
.../InferFiltersFromConstraintsSuite.scala | 68 +++
.../optimizer/RewriteDistinctAggregatesSuite.scala | 16 +-
.../joins/StreamedSideJoinCondition.scala | 2 +-
.../sql/execution/WholeStageCodegenSuite.scala | 13 +-
.../SplitStreamedSideJoinConditionSuite.scala | 13 +-
14 files changed, 889 insertions(+), 57 deletions(-)
diff --git a/docs/sql-migration-guide.md b/docs/sql-migration-guide.md
index 31c78ee293fa..f7b8d0d5828b 100644
--- a/docs/sql-migration-guide.md
+++ b/docs/sql-migration-guide.md
@@ -73,7 +73,7 @@ license: |
- Since Spark 4.4, when `spark.sql.parquet.fieldId.read.enabled` is true, a
Parquet read fails with `PARQUET_FIELD_REQUESTED_MORE_THAN_ONCE` if two or more
requested fields of a struct (or of the top-level schema) resolve to the same
Parquet field. This happens when one requested field is matched by field ID and
another by name, or when two requested fields have the same field ID. In Spark
4.3 and earlier, such a read returned wrong values without an error: with the
vectorized reader one [...]
- Since Spark 4.4, when `spark.sql.groupByOrdinal` is true (the default), the
pipe `AGGREGATE` operator rejects an aliased integer literal in its `GROUP BY`
clause, such as `TABLE t |> AGGREGATE sum(x) AS s GROUP BY 2 AS grp`, with
`UNSUPPORTED_FEATURE.PIPE_OPERATOR_AGGREGATE_UNSUPPORTED_CASE`, because a bare
integer literal in the same position is an ordinal. Previously the aliased
literal was grouped as a constant. Bare ordinals and aliases on other grouping
expressions are not affecte [...]
- Since Spark 4.4, with whole-stage codegen enabled, a filter condition,
including the `FILTER` clause of an aggregate function, evaluates the remaining
top-level conjuncts of the condition on a row after one of them evaluates to
`NULL`, as the SQL standard requires, and does so in the order they appear in
the condition, as Spark already did with whole-stage codegen disabled, which
also evaluates a subexpression shared by several conjuncts before the
condition. Only a `FALSE` conjunct st [...]
-- Since Spark 4.4, the optimizer no longer infers a filter from data
constraints when evaluating the filter can fail, such as arithmetic or a
narrowing cast in ANSI mode, or when it calls a user-defined function. The
check is conservative, so a few filters that cannot fail are not inferred
either, such as `LIKE 'a%'`, `year(d) = 2024`, and arithmetic with ANSI mode
off. For example, `SELECT * FROM t WHERE x = y AND 10 / y > 0` no longer adds
the filter `10 / x > 0`, which failed with `DI [...]
+- Since Spark 4.4, the optimizer no longer infers a filter from data
constraints when evaluating the filter can fail, such as, in ANSI mode,
integral or decimal arithmetic, a division or a narrowing cast, or when it
calls a user-defined function. The check is conservative, so a few filters that
cannot fail are not inferred either, such as `upper(s) = 'A'`. For example,
with ANSI mode on, `SELECT * FROM t WHERE x = y AND 10 / y > 0` no longer adds
the filter `10 / x > 0`, which failed wit [...]
- Since Spark 4.4, when a format is specified, `to_timestamp`,
`try_to_timestamp`, and `to_timestamp_ltz` cast a numeric first argument to a
string and parse it with the format, for example `to_timestamp(20201231,
'yyyyMMdd')` returns `2020-12-31 00:00:00`. This matches the existing behavior
when `spark.sql.timestampType` is `TIMESTAMP_NTZ`. Previously, with the default
`TIMESTAMP_LTZ` timestamp type, such calls failed with `INTERNAL_ERROR`. Note
that the string form of the number is par [...]
- Since Spark 4.4, the Spark Thrift Server logs a warning at startup when
`hive.server2.enable.doAs` is `true` and `hive.server2.authentication` verifies
user identities (any recognized type other than `NONE`/`NOSASL`), because
executor-side data access still runs as the server's own service identity
rather than the connecting user (SPARK-5159). Set
`spark.sql.hive.thriftServer.allowIneffectiveDoAs` to `true` to acknowledge the
limitation and silence the warning. Spark 5.0 is expected to [...]
- Since Spark 4.4, `UPDATE` and `MERGE` on a Data Source V2 table fail with
`DATATYPE_MISMATCH.INVALID_ROW_LEVEL_OPERATION_ASSIGNMENTS` when they assign to
a metadata column of the table. This includes `UPDATE SET *` and `INSERT *` in
`MERGE WITH SCHEMA EVOLUTION` when the source has a column with the name of a
metadata column of the target table. Previously, these assignments passed
analysis and were usually ignored. To restore the previous behavior, set
`spark.sql.legacy.ignoreMetadata [...]
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala
index d8e7a3e1a6d1..1320f614ac7d 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala
@@ -31,7 +31,7 @@ import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData,
CharVarcharUtils}
import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase,
QueryExecutionErrors}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.internal.types.{AbstractMapType,
StringTypeWithCollation}
-import org.apache.spark.sql.types.{DataType, FileType, MapType, StringType,
StructType, VariantType}
+import org.apache.spark.sql.types.{BooleanType, DataType, DateType,
DecimalType, DoubleType, FileType, FloatType, FractionalType, MapType,
NumericType, StringHelper, StringType, StructType, TimestampNTZType,
TimestampType, UserDefinedType, VariantType}
import org.apache.spark.unsafe.types.UTF8String
object ExprUtils extends EvalHelper with QueryErrorsBase {
@@ -247,15 +247,58 @@ 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 a whitelist of total, deterministic expressions qualifies:
- * - leaves: attribute references and literals;
+ * 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.
- * Anything else (arithmetic, casts, string functions, UDFs, nested IF/CASE
WHEN, ...)
- * conservatively returns false. On top of the whitelist, the expression
must be
+ * 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.
*
* Note: this deliberately does not rely on [[Expression.throwable]], which
is opt-in
@@ -266,20 +309,125 @@ 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
+ // A UDT 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.
+ case (from, to) if hasUserDefinedType(from) || hasUserDefinedType(to) =>
false
+ // A numeric up-cast can not fail. It goes before the negative scales, as
a widening between
+ // decimals never calls `Decimal.toLong`, also from or to a negative
scale; a change to a
+ // negative scale only checks that
`spark.sql.legacy.allowNegativeScaleOfDecimal` is on.
+ case (from, to) if isNumericUpCast(from, to) => true
+ // `Decimal.toDouble` and `Decimal.toFloat` round through a `BigDecimal`,
also for a negative
+ // scale, and do not check the range in ANSI mode.
+ case (_: DecimalType, FloatType | DoubleType) => true
+ // 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 (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)
+
+ // `existsRecursively` does not look inside a UDT, so neither does this.
+ private def hasUserDefinedType(dt: DataType): Boolean =
+ dt.existsRecursively(_.isInstanceOf[UserDefinedType[_]])
+
+ 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
+ // `DivModLike` and Pmod override `eval` without the catch of TRY mode,
and IntegralDivide
+ // and Pmod check a zero divisor there as in ANSI mode.
+ case _: IntegralDivide | _: Pmod => b.evalMode == EvalMode.LEGACY
+ case _ => false
+ })
+ }
+
+ private def isNumericOfNonNegativeScale(e: Expression): Boolean =
+ e.dataType.isInstanceOf[NumericType] && !hasNegativeScale(e.dataType)
+
+ // Not DECIMAL: Add, Subtract and Multiply over it check for an overflow in
ANSI mode.
+ private def isFloatOrDouble(e: Expression): Boolean = e.dataType match {
+ case FloatType | DoubleType => true
+ case _ => false
+ }
+
+ // Whether UnaryMinus or Abs can not fail: over numbers, they check for an
overflow only over the
+ // integral types, and only when `failOnError` is set. Over a DAY TO SECOND
or YEAR TO MONTH
+ // interval, they can overflow in every mode, and intervals are left out.
+ private def cannotFailUnaryArithmetic(child: Expression, failOnError:
Boolean): Boolean =
+ child.dataType match {
+ case _: FractionalType => true
+ case _: NumericType => !failOnError
+ case _ => false
+ }
+
private def canEvaluateUnconditionallyInternal(e: Expression): Boolean = e
match {
- case _: AttributeReference | _: Literal => true
+ // The collation of a Collate evaluates to its name; it only sets the type.
+ case _: AttributeReference | _: Literal | _: ResolvedCollation => true
case _ if isTotalOperator(e) =>
e.children.forall(canEvaluateUnconditionallyInternal)
case _ => false
}
/**
- * Returns true if `e` itself cannot raise an error, whatever the values of
its children. See
- * [[canEvaluateUnconditionally]] for the whitelist.
+ * Returns true if `e` itself cannot raise an error, whatever the values of
its children of
+ * their current types. See [[canEvaluateUnconditionally]] for the allowlist.
+ * `ConstantPropagation` replaces a child with a value equal to it under
such an expression, so
+ * it must also give equal results for equal children, e.g. a cast of a
DOUBLE to a STRING is
+ * left out, as it tells -0.0 from 0.0, and so is a cast of a UDT. Strings
of a non-binary
+ * collation are guarded by the callers instead.
*/
def isTotalOperator(e: Expression): Boolean = e match {
- case _: GetStructField | _: GetArrayStructFields | _: GetMapValue => true
+ case _: GetStructField | _: GetArrayStructFields | _: GetMapValue | _:
NoThrow | _: Collate =>
+ true
case _: And | _: Or | _: Not | _: BinaryComparison | _: IsNull | _:
IsNotNull |
- _: IsNaN | _: NullIf | _: Coalesce | _: In | _: InSet => true
+ _: IsNaN | _: NullIf | _: Coalesce | _: In | _: InSet | _: Size | _:
StartsWith |
+ _: EndsWith | _: Contains | _: Length | _: OctetLength | _: Substring
| _: GetDateField |
+ _: GetTimeField => true
+ case c: Cast => cannotFailCast(c)
+ case b: BinaryArithmetic => cannotFailArithmetic(b)
+ case u: UnaryMinus => cannotFailUnaryArithmetic(u.child, u.failOnError)
+ case a: Abs => cannotFailUnaryArithmetic(a.child, a.failOnError)
case _ => false
}
}
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/complexTypeCreator.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/complexTypeCreator.scala
index acda793a8e77..5784d983aaf7 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/complexTypeCreator.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/complexTypeCreator.scala
@@ -47,6 +47,11 @@ import org.apache.spark.util.ArrayImplicits._
* 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))`.
+ * [[ExprUtils.canEvaluateUnconditionally]] and [[ExprUtils.isTotalOperator]]
rely on it too, to
+ * evaluate such an expression on rows it would otherwise not see, so it must
not raise for any
+ * input of its children, and to replace a child with a value equal to it, so
it must give equal
+ * results for equal children of a binary-stable type; strings of a non-binary
collation are
+ * guarded by the callers.
*/
trait NoThrow
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
index e9338c08822d..dc209aa5dbcb 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala
@@ -2328,9 +2328,7 @@ object InferFiltersFromConstraints extends
Rule[LogicalPlan]
stripCannotFail(ConstantFolding.constantFolding(constraint,
isConditionalBranch = true)))
}
- // Top-down, so that each cast is judged by the type of its original input.
private def stripCannotFail(e: Expression): Expression = e match {
- case c: Cast if isNumericUpCast(c.child.dataType, c.dataType) =>
stripCannotFail(c.child)
// An integral remainder by a non-zero constant, e.g. `x % 2 = 0`, never
fails.
case r: Remainder if r.dataType.isInstanceOf[IntegralType] &&
isNonZeroIntegral(r.right) =>
stripCannotFail(r.left)
@@ -2346,11 +2344,6 @@ object InferFiltersFromConstraints extends
Rule[LogicalPlan]
case Literal(v, _: IntegralType) => v != null && v != 0
case _ => false
}
-
- private def isNumericUpCast(from: DataType, to: DataType): Boolean = (from,
to) match {
- case (_: NumericType, _: NumericType) => Cast.canUpCast(from, to)
- case _ => false
- }
}
/**
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala
index edb38ad1e3ba..a79898115271 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala
@@ -333,8 +333,8 @@ object RewriteDistinctAggregates extends Rule[LogicalPlan] {
// occurrence, with no dedup, so copying the filter into the key
would
// join the input twice. The guard also evaluates the child only
when the
// union is true, so every child must pass
canEvaluateUnconditionally. A
- // child that fails, such as a division, stays raw and keeps today's
- // evaluation count and error behavior. The guard shares the
+ // child that fails, such as a division in ANSI mode, stays raw and
keeps
+ // today's evaluation count and error behavior. The guard shares the
// rewriteCountDistinctConditional kill switch so conf=false
restores the
// pre-feature Expand key (raw child) for user-written FILTER
distincts too.
val canGuard = SQLConf.get.rewriteCountDistinctConditionalEnabled &&
@@ -494,10 +494,10 @@ object RewriteDistinctAggregates extends
Rule[LogicalPlan] {
* holds, which is a row whose original `IF(cond_i, base, NULL)` already
evaluated
* `base`. The guard does not apply when any filter is non-deterministic,
contains
* a subquery, or when a child fails that check (a user-written FILTER on a
- * division, for example). Expand then projects the raw child on every row.
A group
- * that also has an unfiltered aggregate on the same base projects the raw
base
- * for every row too, matching the uncollapsed plan, which already evaluated
it
- * for that unfiltered member.
+ * division in ANSI mode, for example). Expand then projects the raw child on
+ * every row. A group that also has an unfiltered aggregate on the same base
+ * projects the raw base for every row too, matching the uncollapsed plan,
which
+ * already evaluated it for that unfiltered member.
*
* A condition that itself contains a subquery is not normalized. Guarding
that
* group would duplicate the predicate into a second existence join, and
collapsing
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
index f9202a68dcfa..2eec5815533e 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
@@ -1856,11 +1856,11 @@ object SQLConf {
.internal()
.doc("When true, the query optimizer also infers a filter from data
constraints when " +
"evaluating it can fail or is otherwise observable, such as `10 / x >
0` from " +
- "`x = y AND 10 / y > 0`, or a UDF. Such a filter runs on rows that the
query does not " +
- "evaluate the expression on, so the query can raise an error that it
does not raise " +
- "without the filter. When false, only a filter that `ExprUtils." +
+ "`x = y AND 10 / y > 0` in ANSI mode, or a UDF. Such a filter runs on
rows that the " +
+ "query does not evaluate the expression on, so the query can raise an
error that it " +
+ "does not raise without the filter. When false, only a filter that
`ExprUtils." +
"canEvaluateUnconditionally` accepts is inferred, which also leaves
out some " +
- "expressions that cannot fail, such as `LIKE 'a%'`.")
+ "expressions that cannot fail, such as `upper(s) = 'A'`.")
.version("4.4.0")
.withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
.booleanConf
@@ -3484,8 +3484,8 @@ object SQLConf {
"(including user-written FILTER on a plain column), so the first " +
"aggregate's output cardinality stays bounded by the un-rewritten " +
"plan. A child that is not safe to evaluate unconditionally (for
example " +
- "a division, which can throw) keeps the raw Expand key. When false,
both " +
- "the IF/CASE rewrite and the union-of-filters guard are disabled. The
" +
+ "a division in ANSI mode, which can throw) keeps the raw Expand key. "
+
+ "When false, both the IF/CASE rewrite and the union-of-filters guard
are disabled. The " +
"IF/CASE rewrite is only applied to base expressions that are safe to
" +
"evaluate unconditionally (e.g. plain columns), so the short-circuit "
+
"semantics of IF/CASE WHEN are preserved. A condition that contains a
" +
diff --git
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala
index c0ac407b0432..aa18056e0e29 100644
---
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala
+++
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala
@@ -17,14 +17,47 @@
package org.apache.spark.sql.catalyst.expressions
-import org.apache.spark.SparkFunSuite
-import org.apache.spark.sql.types.{ArrayType, IntegerType, LongType,
StringType, StructField, StructType}
+import org.apache.spark.{SparkFunSuite, SparkRuntimeException}
+import org.apache.spark.sql.catalyst.InternalRow
+import
org.apache.spark.sql.catalyst.expressions.codegen.GenerateUnsafeProjection
+import org.apache.spark.sql.catalyst.plans.SQLHelper
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{ArrayType, BinaryType, BooleanType,
ByteType, CharType, DataType, DateType, DayTimeIntervalType, Decimal,
DecimalType, DoubleType, FloatType, IntegerType, LongType, MapType, ShortType,
StringType, StructField, StructType, TestUDT, TimestampLTZNanosType,
TimestampNTZNanosType, TimestampNTZType, TimestampType, TimeType, VarcharType,
VariantType, YearMonthIntervalType}
+import org.apache.spark.unsafe.types.UTF8String
-class ExprUtilsSuite extends SparkFunSuite {
+class ExprUtilsSuite extends SparkFunSuite with SQLHelper {
private val a = AttributeReference("a", LongType)()
+ private val ansi = NumericEvalContext(EvalMode.ANSI)
+ private val legacy = NumericEvalContext(EvalMode.LEGACY)
+ private val tryMode = NumericEvalContext(EvalMode.TRY)
- test("canEvaluateUnconditionally: whitelisted total expressions") {
+ // Evaluates `build` over input columns of the given types on every
combination of their
+ // values, and NULL when the columns are nullable, without and with code
generation.
+ private def evalRows(columns: (DataType, Seq[Any])*)(
+ build: Seq[Expression] => Expression): Unit = {
+ Seq(true, false).foreach { nullable =>
+ val e = build(columns.zipWithIndex.map { case ((t, _), i) =>
BoundReference(i, t, nullable) })
+ val projection = GenerateUnsafeProjection.generate(Seq(e))
+ val inputs = columns.map { case (_, values) => if (nullable) values :+
null else values }
+ inputs.foldLeft(Seq(Seq.empty[Any])) { (rows, columnValues) =>
+ for (r <- rows; v <- columnValues) yield r :+ v
+ }.foreach { rowValues =>
+ val row = InternalRow.fromSeq(rowValues)
+ e.eval(row)
+ projection(row)
+ }
+ }
+ }
+
+ private def evalPairs(t: DataType, values: Seq[Any])(
+ build: (Expression, Expression) => Expression): Unit =
+ evalRows((t, values), (t, values))(c => build(c(0), c(1)))
+
+ private def evalEach(t: DataType, values: Seq[Any])(build: Expression =>
Expression): Unit =
+ evalRows((t, values))(c => build(c(0)))
+
+ test("canEvaluateUnconditionally: allowlisted total expressions") {
assert(ExprUtils.canEvaluateUnconditionally(a))
assert(ExprUtils.canEvaluateUnconditionally(Literal(1L)))
assert(ExprUtils.canEvaluateUnconditionally(
@@ -39,17 +72,515 @@ class ExprUtilsSuite extends SparkFunSuite {
test("canEvaluateUnconditionally: expressions that can throw are excluded") {
// Arithmetic can throw (overflow, div-by-zero in ANSI mode) even though
it does not
// override `throwable` and inherits false from its non-throwing children,
which is
- // why the whitelist is used instead of the throwable flag.
- val arithmetic = LessThan(Add(a, Literal(1L)), Literal(5L))
+ // why the allowlist is used instead of the throwable flag.
+ val arithmetic = LessThan(Add(a, Literal(1L), ansi), Literal(5L))
assert(!arithmetic.throwable)
assert(!ExprUtils.canEvaluateUnconditionally(arithmetic))
- assert(!ExprUtils.canEvaluateUnconditionally(EqualTo(Remainder(a,
Literal(3L)), Literal(0L))))
- assert(!ExprUtils.canEvaluateUnconditionally(Cast(a, StringType)))
+ assert(!ExprUtils.canEvaluateUnconditionally(
+ EqualTo(Remainder(a, Literal(3L), ansi), Literal(0L))))
+ assert(!ExprUtils.canEvaluateUnconditionally(
+ Cast(AttributeReference("s", StringType)(), IntegerType, evalMode =
EvalMode.ANSI)))
// GetArrayItem/ElementAt can throw on invalid ordinals in ANSI mode.
val arr = AttributeReference("arr", ArrayType(IntegerType))()
assert(!ExprUtils.canEvaluateUnconditionally(GetArrayItem(arr,
Literal(0))))
- // A whitelisted predicate over a non-whitelisted child is still excluded.
- assert(!ExprUtils.canEvaluateUnconditionally(IsNotNull(Add(a,
Literal(1L)))))
+ // An allowlisted predicate over a child that is not allowlisted is still
excluded.
+ assert(!ExprUtils.canEvaluateUnconditionally(IsNotNull(Add(a, Literal(1L),
ansi))))
+ }
+
+ test("SPARK-60882: canEvaluateUnconditionally: size and numeric up-casts are
included") {
+ val arr = AttributeReference("arr", ArrayType(IntegerType))()
+ val i = AttributeReference("i", IntegerType)()
+ assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(Size(arr),
Literal(0))))
+ assert(ExprUtils.canEvaluateUnconditionally(
+ EqualTo(Cast(i, LongType, evalMode = EvalMode.ANSI), a)))
+ assert(ExprUtils.canEvaluateUnconditionally(Cast(i, DoubleType, evalMode =
EvalMode.ANSI)))
+ assert(ExprUtils.canEvaluateUnconditionally(
+ Cast(i, DecimalType(20, 0), evalMode = EvalMode.ANSI)))
+ // A decimal to an integral type is an up-cast only when every value fits:
DECIMAL(18, 0) to
+ // BIGINT, but not DECIMAL(19, 0), which can overflow in ANSI mode.
+ for ((precision, to) <- Seq((18, LongType), (9, IntegerType), (4,
ShortType), (2, ByteType))) {
+ assert(Cast.canUpCast(DecimalType(precision, 0), to), to)
+ val d = AttributeReference("d", DecimalType(precision, 0))()
+ assert(ExprUtils.canEvaluateUnconditionally(Cast(d, to, evalMode =
EvalMode.ANSI)), to)
+ evalEach(DecimalType(precision, 0),
+ Seq("-" + "9" * precision, "9" * precision).map(v =>
Decimal(BigDecimal(v))))(
+ Cast(_, to, evalMode = EvalMode.ANSI))
+ }
+ assert(!Cast.canUpCast(DecimalType(19, 0), LongType))
+ assert(!ExprUtils.canEvaluateUnconditionally(Cast(AttributeReference("d",
DecimalType(19, 0))(),
+ LongType, evalMode = EvalMode.ANSI)))
+ intercept[ArithmeticException](Cast(Literal(Decimal(BigDecimal("9" * 19)),
DecimalType(19, 0)),
+ LongType, evalMode = EvalMode.ANSI).eval())
+ // Narrowing casts can fail in ANSI mode. LONG to TIMESTAMP is an up-cast
too, but only the
+ // numeric ones are taken.
+ assert(!ExprUtils.canEvaluateUnconditionally(Cast(a, IntegerType, evalMode
= EvalMode.ANSI)))
+ assert(Cast.canUpCast(LongType, TimestampType))
+ assert(!ExprUtils.canEvaluateUnconditionally(
+ Cast(a, TimestampType, evalMode = EvalMode.ANSI)))
+ // A size over an expression that can fail is still excluded.
+ assert(!ExprUtils.canEvaluateUnconditionally(Size(ElementAt(
+ AttributeReference("nested", ArrayType(ArrayType(IntegerType)))(),
Literal(1)))))
+ }
+
+ test("SPARK-60882: canEvaluateUnconditionally: string prefix, suffix,
containment and " +
+ "length checks, COLLATE and a field of a struct built from plain values
are included") {
+ val s = AttributeReference("s", StringType)()
+ // `LIKE 'ab%c'` becomes the last one.
+ Seq(StartsWith(s, Literal("abc")), EndsWith(s, Literal("abc")),
Contains(s, s),
+ GreaterThan(Length(s), Literal(1)),
+ And(GreaterThanOrEqual(OctetLength(s), Literal(3)),
+ And(StartsWith(s, Literal("ab")), EndsWith(s,
Literal("c"))))).foreach {
+ p => assert(ExprUtils.canEvaluateUnconditionally(p), p)
+ }
+ val bin = AttributeReference("bin", BinaryType)()
+ assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(Length(bin),
Literal(1))))
+ assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(OctetLength(bin),
Literal(1))))
+ // They do not raise for any collation, also on empty, ignorable and
invalid UTF-8 strings,
+ // which ICU can not search for: a combining accent after a letter and
alone, a zero-width
+ // space, NUL, U+FFFD, a bad lead byte, a truncated sequence and one above
U+10FFFF.
+ val ignorable = Seq(Seq('a', 0x0301), Seq(0x0301), Seq(0x200B),
Seq(0x0000), Seq(0xFFFD))
+ .map(_.map(_.toChar).mkString)
+ val invalid = Seq(Array(0xFF, 'a'), Array('a', 0xE2), Array(0xF4, 0xBF,
0xBF, 0xBF))
+ .map(b => UTF8String.fromBytes(b.map(_.toByte)))
+ val values = (Seq("", " ", "a", "abc") ++
ignorable).map(UTF8String.fromString) ++ invalid
+ Seq("UTF8_BINARY", "UTF8_LCASE", "UNICODE", "UNICODE_CI", "UNICODE_AI",
"UNICODE_CI_AI",
+ "UTF8_BINARY_RTRIM", "UNICODE_RTRIM", "UTF8_LCASE_RTRIM",
"sr_CI_AI").foreach {
+ collation =>
+ val collated = StringType(collation)
+ evalEach(collated, values)(Length(_))
+ evalEach(collated, values)(OctetLength(_))
+ Seq[(Expression, Expression) => Expression](StartsWith(_, _),
EndsWith(_, _),
+ Contains(_, _)).foreach(evalPairs(collated, values))
+ }
+ // LIKE and RLIKE raise on an invalid pattern.
+ assert(!ExprUtils.canEvaluateUnconditionally(Like(s, Literal("abc%"),
'\\')))
+ assert(!ExprUtils.canEvaluateUnconditionally(RLike(s, Literal("abc"))))
+ assert(!ExprUtils.canEvaluateUnconditionally(StartsWith(Upper(s),
Literal("abc"))))
+ assert(!ExprUtils.canEvaluateUnconditionally(Length(Upper(s))))
+ // Also with an explicit COLLATE: `contains(s COLLATE UNICODE_CI, s)` is
analyzed to a
+ // `Collate`, and a cast of the other side to the collation, in the
session's eval mode.
+ def collate(e: Expression): Expression = Collate(e,
ResolvedCollation("UNICODE_CI"))
+ assert(ExprUtils.canEvaluateUnconditionally(
+ Contains(collate(s), Cast(s, StringType("UNICODE_CI"), evalMode =
EvalMode.ANSI))))
+ assert(!ExprUtils.canEvaluateUnconditionally(Contains(collate(Upper(s)),
collate(s))))
+ Seq("UTF8_BINARY", "UNICODE_CI", "UTF8_LCASE_RTRIM").foreach { collation =>
+ evalEach(StringType, values)(Collate(_, ResolvedCollation(collation)))
+ }
+
+ // A struct built from plain values, and a field of it, but not when
another field can fail.
+ def field(values: Expression*): Expression =
GetStructField(CreateNamedStruct(
+ values.zipWithIndex.flatMap { case (v, i) => Seq(Literal(s"f$i"), v) }),
0)
+ assert(ExprUtils.canEvaluateUnconditionally(GreaterThan(field(a, s),
Literal(1L))))
+ assert(!ExprUtils.canEvaluateUnconditionally(GreaterThan(field(a, Add(a,
Literal(1L), ansi)),
+ Literal(1L))))
+
assert(ExprUtils.canEvaluateUnconditionally(CreateNamedStruct(Seq(Literal("f0"),
a))))
+ assert(!ExprUtils.canEvaluateUnconditionally(
+ CreateNamedStruct(Seq(Literal("f0"), Add(a, Literal(1L), ansi)))))
+ // So is an array, as both are marked `NoThrow`, but not a map, which
raises on a NULL key or,
+ // by default, a duplicate key (SPARK-60849).
+ assert(!ExprUtils.canEvaluateUnconditionally(CreateMap(Seq(a,
Literal(1)))))
+ intercept[SparkRuntimeException](
+ CreateMap(Seq(Literal(1L), Literal(1), Literal(1L), Literal(2))).eval())
+ assert(ExprUtils.canEvaluateUnconditionally(
+ EqualTo(CreateArray(Seq(a, Literal(1L))), CreateArray(Seq(Literal(1L),
Literal(2L))))))
+ assert(!ExprUtils.canEvaluateUnconditionally(CreateArray(Seq(a, Add(a,
Literal(1L), ansi)))))
+ }
+
+ test("SPARK-60882: canEvaluateUnconditionally: numeric arithmetic that can
not fail") {
+ val i = AttributeReference("i", IntegerType)()
+ def binary(ctx: NumericEvalContext): Seq[Expression] = Seq(Add(a, a, ctx),
+ Subtract(a, a, ctx), Multiply(a, a, ctx), Divide(Cast(a, DoubleType),
Literal(0.0), ctx),
+ IntegralDivide(a, a, ctx), Remainder(a, a, ctx), Pmod(i, i, ctx))
+ binary(legacy).foreach(e =>
assert(ExprUtils.canEvaluateUnconditionally(e), e))
+ binary(ansi).foreach(e => assert(!ExprUtils.canEvaluateUnconditionally(e),
e))
+ assert(ExprUtils.canEvaluateUnconditionally(UnaryMinus(a, failOnError =
false)))
+ assert(ExprUtils.canEvaluateUnconditionally(Abs(a, failOnError = false)))
+ assert(!ExprUtils.canEvaluateUnconditionally(UnaryMinus(a, failOnError =
true)))
+ assert(!ExprUtils.canEvaluateUnconditionally(Abs(a, failOnError = true)))
+ // Not over a child that can fail.
+ val failing = Add(a, a, ansi)
+ assert(!ExprUtils.canEvaluateUnconditionally(Add(failing, a, legacy)))
+ assert(!ExprUtils.canEvaluateUnconditionally(UnaryMinus(failing,
failOnError = false)))
+ assert(!ExprUtils.canEvaluateUnconditionally(Abs(failing, failOnError =
false)))
+ // In ANSI mode too, Add, Subtract and Multiply over FLOAT and DOUBLE
return an infinity or NaN,
+ // and UnaryMinus and Abs over FLOAT, DOUBLE and DECIMAL do not check for
an overflow. Divide,
+ // Remainder and Pmod raise on a zero divisor, and Add over the integral
types or DECIMAL on an
+ // overflow.
+ Seq(FloatType, DoubleType).foreach { t =>
+ val x = AttributeReference("x", t)()
+ Seq(Add(x, x, ansi), Subtract(x, x, ansi), Multiply(x, x, ansi)).foreach
{ e =>
+ assert(ExprUtils.canEvaluateUnconditionally(e), e)
+ }
+ Seq(Divide(x, x, ansi), Remainder(x, x, ansi), Pmod(x, x, ansi)).foreach
{ e =>
+ assert(!ExprUtils.canEvaluateUnconditionally(e), e)
+ }
+ }
+ Seq(FloatType, DoubleType, DecimalType(10, 2)).foreach { t =>
+ val x = AttributeReference("x", t)()
+ assert(ExprUtils.canEvaluateUnconditionally(UnaryMinus(x, failOnError =
true)), t)
+ assert(ExprUtils.canEvaluateUnconditionally(Abs(x, failOnError = true)),
t)
+ }
+ Seq(IntegerType, ShortType, ByteType).foreach { t =>
+ val x = AttributeReference("x", t)()
+ assert(!ExprUtils.canEvaluateUnconditionally(Add(x, x, ansi)), t)
+ assert(!ExprUtils.canEvaluateUnconditionally(UnaryMinus(x, failOnError =
true)), t)
+ }
+ intercept[ArithmeticException](Divide(Literal(1.0), Literal(0.0),
ansi).eval())
+ val maxDecimal = Literal(Decimal(BigDecimal("9" * 38)), DecimalType(38, 0))
+ val decimalAdd = Add(maxDecimal, maxDecimal, ansi)
+ assert(!ExprUtils.canEvaluateUnconditionally(decimalAdd))
+ intercept[ArithmeticException](decimalAdd.eval())
+ // Analysis casts both sides to one type; this only pins that every child
must be a FLOAT or a
+ // DOUBLE.
+ assert(!ExprUtils.canEvaluateUnconditionally(Add(Literal(1.0), maxDecimal,
ansi)))
+ // TRY mode catches the errors of Add, Subtract and Multiply, and Divide
and Remainder only
+ // check a zero divisor in ANSI mode, but IntegralDivide and Pmod raise
there.
+ Seq(Add(a, a, tryMode), Subtract(a, a, tryMode), Multiply(a, a, tryMode),
+ Divide(Cast(a, DoubleType), Literal(0.0), tryMode), Remainder(a, a,
tryMode))
+ .foreach(e => assert(ExprUtils.canEvaluateUnconditionally(e), e))
+ Seq(IntegralDivide(Literal(1L), Literal(0L), tryMode), Pmod(Literal(1),
Literal(0), tryMode))
+ .foreach { e =>
+ assert(!ExprUtils.canEvaluateUnconditionally(e), e)
+ intercept[ArithmeticException](e.eval())
+ }
+ // Also over decimals whose integral quotient has more digits than the
MathContext of
+ // `Decimal` holds (SPARK-61050).
+ val big = Literal(Decimal(BigDecimal("9" * 38)), DecimalType(38, 0))
+ val small = Literal(Decimal(BigDecimal("0.007"), 3, 3), DecimalType(3, 3))
+ Seq(IntegralDivide(big, small, legacy), Remainder(big, small, legacy),
+ Remainder(big, small, tryMode), Pmod(big, small, legacy), Divide(big,
small, legacy),
+ Divide(big, small, tryMode)).foreach { e =>
+ assert(ExprUtils.canEvaluateUnconditionally(e), e)
+ e.eval()
+ }
+ // But not over a decimal of a negative scale, for which `Decimal.%` can
raise, also in TRY
+ // mode.
+ withSQLConf(SQLConf.LEGACY_ALLOW_NEGATIVE_SCALE_OF_DECIMAL_ENABLED.key ->
"true") {
+ val veryNegative = DecimalType(1, -2147483000)
+ Seq(legacy, tryMode).foreach { ctx =>
+ assert(!ExprUtils.canEvaluateUnconditionally(Remainder(
+ AttributeReference("n", veryNegative)(), Literal(Decimal(3),
DecimalType(1, 0)), ctx)))
+ intercept[ArithmeticException](Remainder(BoundReference(0,
veryNegative, true),
+ BoundReference(1, DecimalType(1, 0), true), ctx)
+ .eval(InternalRow(Decimal.createUnsafe(1L, 1, -2147483000),
Decimal(3))))
+ }
+ // UnaryMinus and Abs only negate one.
+ val negativeScale = DecimalType(3, -2)
+ Seq[Expression => Expression](UnaryMinus(_, failOnError = true),
+ Abs(_, failOnError = true)).foreach { build =>
+ val n = AttributeReference("n", negativeScale)()
+ assert(ExprUtils.canEvaluateUnconditionally(build(n)))
+ evalEach(negativeScale, Seq(Decimal.createUnsafe(-999L, 3, -2)))(build)
+ }
+ }
+ // Arithmetic over DAY TO SECOND and YEAR TO MONTH intervals overflows in
every mode, also
+ // UnaryMinus and Abs.
+ val maxInterval = Literal(Long.MaxValue, DayTimeIntervalType())
+ val intervalAdd = Add(maxInterval, maxInterval, legacy)
+ assert(!ExprUtils.canEvaluateUnconditionally(intervalAdd))
+ intercept[ArithmeticException](intervalAdd.eval())
+ Seq(Literal(Long.MinValue, DayTimeIntervalType()),
+ Literal(Int.MinValue, YearMonthIntervalType())).foreach { minInterval
=>
+ Seq(UnaryMinus(minInterval, failOnError = false), Abs(minInterval,
failOnError = false))
+ .foreach { e =>
+ assert(!ExprUtils.canEvaluateUnconditionally(e), e)
+ intercept[ArithmeticException](e.eval())
+ }
+ }
+
+ // None of the accepted ones raises, also on the values that do in ANSI
mode.
+ val longs = (LongType, Seq(Long.MinValue, -1L, 0L, 1L, Long.MaxValue))
+ val ints = (IntegerType, Seq(Int.MinValue, -1, 0, 1, Int.MaxValue))
+ val shorts = (ShortType, Seq(Short.MinValue, -1.toShort, 0.toShort,
Short.MaxValue))
+ val bytes = (ByteType, Seq(Byte.MinValue, -1.toByte, 0.toByte,
Byte.MaxValue))
+ val floats = (FloatType, Seq(Float.NegativeInfinity, -1.0f, 0.0f,
Float.NaN, Float.MaxValue,
+ Float.PositiveInfinity))
+ val doubles = (DoubleType, Seq(Double.NegativeInfinity, -1.0, 0.0,
Double.NaN,
+ Double.MaxValue, Double.PositiveInfinity))
+ val decimals = (DecimalType(38, 0),
+ Seq("-" + "9" * 38, "0", "1", "9" * 38).map(d => Decimal(BigDecimal(d))))
+ // A small divisor makes the quotient overflow.
+ val smallDecimals = (DecimalType(38, 37),
+ Seq("-1", "0", "1E-37", "9." + "9" * 37).map(d => Decimal(BigDecimal(d),
38, 37)))
+ val nonDecimals = Seq(longs, ints, shorts, bytes, floats, doubles)
+ for ((t, values) <- nonDecimals ++ Seq(decimals, smallDecimals)) {
+ Seq(legacy, tryMode).foreach { ctx =>
+ Seq[(Expression, Expression) => Expression](Add(_, _, ctx),
Subtract(_, _, ctx),
+ Multiply(_, _, ctx)).foreach(evalPairs(t, values))
+ }
+ evalPairs(t, values)((l, _) => UnaryMinus(l, failOnError = false))
+ evalPairs(t, values)((l, _) => Abs(l, failOnError = false))
+ }
+ for ((t, values) <- Seq(floats, doubles)) {
+ Seq[(Expression, Expression) => Expression](Add(_, _, ansi), Subtract(_,
_, ansi),
+ Multiply(_, _, ansi)).foreach(evalPairs(t, values))
+ }
+ for ((t, values) <- Seq(floats, doubles, decimals, smallDecimals)) {
+ evalEach(t, values)(UnaryMinus(_, failOnError = true))
+ evalEach(t, values)(Abs(_, failOnError = true))
+ }
+ for ((t, values) <- nonDecimals ++ Seq(decimals, smallDecimals)) {
+ Seq(legacy, tryMode).foreach(ctx => evalPairs(t, values)(Remainder(_, _,
ctx)))
+ evalPairs(t, values)(Pmod(_, _, legacy))
+ }
+ for ((t, values) <- Seq(longs, decimals, smallDecimals)) {
+ evalPairs(t, values)(IntegralDivide(_, _, legacy))
+ }
+ for ((t, values) <- Seq(doubles, decimals, smallDecimals); ctx <-
Seq(legacy, tryMode)) {
+ evalPairs(t, values)(Divide(_, _, ctx))
+ }
+ // Decimals of different precisions and scales, also without precision
loss.
+ for (allowLoss <- Seq(true, false); mode <- Seq(EvalMode.LEGACY,
EvalMode.TRY);
+ (l, r) <- Seq((decimals, smallDecimals), (smallDecimals, decimals),
+ (decimals, (DecimalType(3, 3), Seq(Decimal(BigDecimal("0.007"), 3,
3)))))) {
+ val ctx = NumericEvalContext(mode, allowLoss)
+ Seq[(Expression, Expression) => Expression](Add(_, _, ctx), Subtract(_,
_, ctx),
+ Multiply(_, _, ctx), Divide(_, _, ctx), Remainder(_, _, ctx)).foreach
{ build =>
+ evalRows(l, r)(c => build(c(0), c(1)))
+ }
+ if (mode == EvalMode.LEGACY) {
+ Seq[(Expression, Expression) => Expression](IntegralDivide(_, _, ctx),
Pmod(_, _, ctx))
+ .foreach(build => evalRows(l, r)(c => build(c(0), c(1))))
+ }
+ }
+ }
+
+ test("SPARK-60882: canEvaluateUnconditionally: casts that can not fail") {
+ val s = AttributeReference("s", StringType)()
+ val ts = AttributeReference("ts", TimestampType)()
+ val date = AttributeReference("date", DateType)()
+ def cast(e: Expression, to: DataType, mode: EvalMode.Value): Cast =
+ Cast(e, to, Some("America/Los_Angeles"), mode)
+ // In every mode: a timestamp to a date, a decimal to a FLOAT or DOUBLE,
and a number, a
+ // boolean or a string to a STRING of any collation.
+ Seq(EvalMode.ANSI, EvalMode.LEGACY, EvalMode.TRY).foreach { mode =>
+ Seq[(Expression, DataType)]((ts, DateType),
+ (AttributeReference("ntz", TimestampNTZType)(), DateType), (a,
StringType),
+ (AttributeReference("d", DecimalType(10, 2))(), StringType),
+ (AttributeReference("b", BooleanType)(), StringType),
+ (AttributeReference("d", DecimalType(38, 0))(), DoubleType),
+ (AttributeReference("d", DecimalType(10, 2))(), FloatType), (s,
StringType),
+ (s, StringType("UNICODE_CI")),
+ (AttributeReference("v", VarcharType(3))(),
StringType("UTF8_LCASE"))).foreach {
+ case (e, to) =>
+ assert(ExprUtils.canEvaluateUnconditionally(cast(e, to, mode)), (e,
to, mode))
+ }
+ }
+ // A FLOAT or DOUBLE to a number or a boolean in LEGACY and TRY mode, but
not to a string.
+ for (mode <- Seq(EvalMode.LEGACY, EvalMode.TRY); from <- Seq(FloatType,
DoubleType);
+ to <- Seq[DataType](LongType, DecimalType(10, 2), BooleanType)) {
+ assert(ExprUtils.canEvaluateUnconditionally(
+ cast(AttributeReference("x", from)(), to, mode)), (from, to, mode))
+ }
+ // Not from or to a decimal of a negative scale
(`spark.sql.legacy.allowNegativeScaleOfDecimal`)
+ // outside TRY mode, nor from a string in TRY mode, which runs the LEGACY
cast: `Decimal.toLong`
+ // raises for one.
+ withSQLConf(SQLConf.LEGACY_ALLOW_NEGATIVE_SCALE_OF_DECIMAL_ENABLED.key ->
"true") {
+ val negativeScale = DecimalType(3, -2)
+ Seq[(Expression, DataType)]((AttributeReference("n", negativeScale)(),
LongType),
+ (a, negativeScale)).foreach { case (e, to) =>
+ assert(!ExprUtils.canEvaluateUnconditionally(cast(e, to,
EvalMode.LEGACY)), to)
+ assert(ExprUtils.canEvaluateUnconditionally(cast(e, to,
EvalMode.TRY)), to)
+ }
+ assert(!ExprUtils.canEvaluateUnconditionally(cast(s, negativeScale,
EvalMode.TRY)))
+ // But a widening between decimals, which never calls `Decimal.toLong`,
also to a negative
+ // scale or through a `BigDecimal`, and a cast to a FLOAT or DOUBLE, in
every mode.
+ for (mode <- Seq(EvalMode.ANSI, EvalMode.LEGACY, EvalMode.TRY);
+ (from, to, unscaled) <- Seq[(DecimalType, DataType, Long)](
+ (negativeScale, DecimalType(10, 0), 999L),
+ (DecimalType(3, -3), DecimalType(5, -2), 999L),
+ (DecimalType(1, -36), DecimalType(38, 0), 9L),
+ (negativeScale, DoubleType, 999L), (negativeScale, FloatType,
999L))) {
+ assert(ExprUtils.canEvaluateUnconditionally(
+ cast(AttributeReference("n", from)(), to, mode)), (from, to, mode))
+ evalEach(from, Seq(-unscaled, unscaled).map(Decimal.createUnsafe(_,
from.precision,
+ from.scale)))(cast(_, to, mode))
+ }
+ intercept[ArrayIndexOutOfBoundsException](cast(BoundReference(0,
negativeScale, true),
+ LongType, EvalMode.LEGACY).eval(InternalRow(Decimal.createUnsafe(123L,
3, -2))))
+ // The accepted TRY casts do not raise.
+ evalEach(negativeScale, Seq(Decimal.createUnsafe(123L, 3, -2)))(
+ cast(_, LongType, EvalMode.TRY))
+ evalEach(LongType, Seq(Long.MinValue, 0L, Long.MaxValue))(
+ cast(_, negativeScale, EvalMode.TRY))
+ }
+ // Not a FLOAT or DOUBLE to a string, also inside a struct, an array or a
map, or to a
+ // variant, in any mode: the string tells -0.0 from 0.0, which are equal.
+ assert(EqualTo(Literal(-0.0), Literal(0.0)).eval() == true)
+ assert(cast(Literal(-0.0), StringType, EvalMode.ANSI).eval() !=
cast(Literal(0.0), StringType,
+ EvalMode.ANSI).eval())
+ val doubles = AttributeReference("ds", ArrayType(DoubleType))()
+ Seq[(Expression, DataType)]((AttributeReference("f", FloatType)(),
StringType),
+ (AttributeReference("x", DoubleType)(), StringType("UNICODE_CI")),
+ (doubles, StringType), (doubles, ArrayType(StringType)),
+ (AttributeReference("sd", StructType(Seq(StructField("v",
DoubleType))))(),
+ StructType(Seq(StructField("v", StringType)))),
+ (AttributeReference("md", MapType(IntegerType, DoubleType))(),
+ MapType(IntegerType, StringType)),
+ (AttributeReference("x", DoubleType)(), VariantType)).foreach { case
(e, to) =>
+ Seq(EvalMode.ANSI, EvalMode.LEGACY, EvalMode.TRY).foreach { mode =>
+ assert(!ExprUtils.canEvaluateUnconditionally(cast(e, to, mode)), (e,
to, mode))
+ }
+ }
+ // Nor from or to a UDT, also inside an array or a struct, in any mode: it
renders its value
+ // with its own `stringifyValue`, e.g. this vector of -0.0 as '(-0.0)'.
+ val udt = new TestUDT.MyDenseVectorUDT()
+ Seq[(Expression, DataType)]((AttributeReference("v", udt)(), StringType),
+ (AttributeReference("vs", ArrayType(udt))(), StringType),
+ (AttributeReference("sv", StructType(Seq(StructField("v", udt))))(),
StringType),
+ (AttributeReference("v", udt)(), udt)).foreach { case (e, to) =>
+ Seq(EvalMode.ANSI, EvalMode.LEGACY, EvalMode.TRY).foreach { mode =>
+ assert(!ExprUtils.canEvaluateUnconditionally(cast(e, to, mode)), (e,
to, mode))
+ }
+ }
+ // Not to a CHAR or VARCHAR, which checks the length.
+ Seq[DataType](CharType(3), VarcharType(3)).foreach { to =>
+ assert(!ExprUtils.canEvaluateUnconditionally(cast(a, to,
EvalMode.LEGACY)), to)
+ intercept[SparkRuntimeException](cast(Literal(12345L), to,
EvalMode.LEGACY).eval())
+ assert(!ExprUtils.canEvaluateUnconditionally(cast(s, to,
EvalMode.ANSI)), to)
+ intercept[SparkRuntimeException](cast(Literal("abcd"), to,
EvalMode.ANSI).eval())
+ }
+ // Not a decimal to a narrower decimal, which raises in ANSI mode.
+ assert(!ExprUtils.canEvaluateUnconditionally(
+ cast(AttributeReference("d", DecimalType(38, 0))(), DecimalType(5, 2),
EvalMode.ANSI)))
+ intercept[ArithmeticException](cast(Literal(Decimal(BigDecimal("9" * 38)),
DecimalType(38, 0)),
+ DecimalType(5, 2), EvalMode.ANSI).eval())
+ // In LEGACY mode, the casts that return NULL or wrap for a value they can
not convert.
+ Seq[(Expression, DataType)]((a, IntegerType), (a, ByteType), (a,
DecimalType(5, 2)),
+ (s, IntegerType), (s, DoubleType), (s, DecimalType(5, 2)), (s,
BooleanType),
+ (s, DateType), (s, TimestampType), (s, TimestampNTZType)).foreach {
case (e, to) =>
+ assert(ExprUtils.canEvaluateUnconditionally(cast(e, to,
EvalMode.LEGACY)), (e, to))
+ assert(!ExprUtils.canEvaluateUnconditionally(cast(e, to,
EvalMode.ANSI)), (e, to))
+ }
+ // And the other casts `Cast.isNoThrowLegacyCast` accepts.
+ Seq[(Expression, DataType)]((AttributeReference("b", BooleanType)(),
IntegerType),
+ (a, BooleanType)).foreach { case (e, to) =>
+ assert(Cast.isNoThrowLegacyCast(e.dataType, to), (e, to))
+ assert(ExprUtils.canEvaluateUnconditionally(cast(e, to,
EvalMode.LEGACY)), (e, to))
+ }
+ // A date to a timestamp can overflow for a date far from the epoch, also
in LEGACY mode,
+ // although it is an up-cast.
+ assert(Cast.canUpCast(DateType, TimestampType))
+ val farDate = cast(Literal(Int.MaxValue, DateType), TimestampType,
EvalMode.LEGACY)
+ assert(!ExprUtils.canEvaluateUnconditionally(cast(date, TimestampType,
EvalMode.LEGACY)))
+ intercept[ArithmeticException](farDate.eval())
+ // A try_cast to a CHAR or VARCHAR returns NULL for a string that is too
long.
+ assert(ExprUtils.canEvaluateUnconditionally(cast(a, VarcharType(3),
EvalMode.TRY)))
+ assert(cast(Literal(12345L), CharType(3), EvalMode.TRY).eval() == null)
+ Seq[DataType](CharType(3), VarcharType(3)).foreach { to =>
+ evalEach(LongType, Seq(12345L, Long.MinValue))(cast(_, to, EvalMode.TRY))
+ }
+ // Not over a child that can fail, in LEGACY mode either.
+ assert(!ExprUtils.canEvaluateUnconditionally(
+ cast(Add(a, a, ansi), IntegerType, EvalMode.LEGACY)))
+ // TRY mode returns NULL for any error of the cast itself, but not of its
input.
+ assert(ExprUtils.canEvaluateUnconditionally(cast(date, TimestampType,
EvalMode.TRY)))
+ assert(cast(Literal(Int.MaxValue, DateType), TimestampType,
EvalMode.TRY).eval() == null)
+ assert(!ExprUtils.canEvaluateUnconditionally(
+ cast(Add(a, a, ansi), IntegerType, EvalMode.TRY)))
+
+ // None of the accepted ones raises.
+ val strings = Seq("", " ", "x", "1e400", "-9" * 30, "9999-99-99",
"+294247-01-10 04:00:54",
+ "-290308-12-21 19:59:05", "25:61:61", "true", "1e-2147483647",
"1e2147483647",
+ "-1e-600000000", "0e-600000000").map(UTF8String.fromString)
+ val numbers = Seq[(DataType, Seq[Any])]((LongType, Seq(Long.MinValue,
Long.MaxValue)),
+ (DoubleType, Seq(Double.NaN, Double.NegativeInfinity, Double.MaxValue)),
+ (FloatType, Seq(Float.NaN, Float.MaxValue)),
+ (DecimalType(38, 0), Seq(Decimal(BigDecimal("9" * 38)))))
+ val integrals = Seq[(DataType, Seq[Any])]((IntegerType, Seq(Int.MinValue,
Int.MaxValue)),
+ (ShortType, Seq(Short.MinValue, Short.MaxValue)), (ByteType,
Seq(Byte.MinValue)))
+ for (mode <- Seq(EvalMode.LEGACY, EvalMode.TRY)) {
+ for (to <- Seq(IntegerType, LongType, ShortType, ByteType, FloatType,
DoubleType,
+ DecimalType(5, 2), DecimalType(38, 0), BooleanType, DateType,
TimestampType,
+ TimestampNTZType)) {
+ evalEach(StringType, strings)(cast(_, to, mode))
+ }
+ for ((from, values) <- numbers ++ integrals :+ ((BooleanType, Seq(true,
false)));
+ to <- Seq(ByteType, ShortType, IntegerType, LongType, FloatType,
DoubleType,
+ DecimalType(5, 2), DecimalType(1, 1), BooleanType)) {
+ evalEach(from, values)(cast(_, to, mode))
+ }
+ // From strings of other collations and from a VARCHAR.
+ for (from <- Seq(StringType("UTF8_LCASE"), VarcharType(3)); to <-
Seq(IntegerType,
+ DateType)) {
+ evalEach(from, strings)(cast(_, to, mode))
+ }
+ }
+ // The numeric widening casts in ANSI mode.
+ for ((from, values) <- integrals :+ ((LongType, Seq(Long.MinValue,
Long.MaxValue)));
+ to <- Seq(LongType, DoubleType, DecimalType(20, 0)) if
Cast.canUpCast(from, to)) {
+ evalEach(from, values)(cast(_, to, EvalMode.ANSI))
+ }
+ evalEach(DecimalType(10, 2), Seq(Decimal(BigDecimal("-99999999.99"), 10,
2)))(
+ cast(_, DecimalType(20, 4), EvalMode.ANSI))
+ // A try_cast of a string to a time or a timestamp with nanoseconds takes
the LEGACY path.
+ for (to <- Seq(TimeType(6), TimestampNTZNanosType(9),
TimestampLTZNanosType(9))) {
+ evalEach(StringType, strings)(cast(_, to, EvalMode.TRY))
+ }
+ for (mode <- Seq(EvalMode.ANSI, EvalMode.LEGACY, EvalMode.TRY)) {
+ for ((from, values) <- numbers.filterNot(n => n._1 == DoubleType || n._1
== FloatType) :+
+ (BooleanType, Seq(true, false))) {
+ evalEach(from, values)(cast(_, StringType, mode))
+ }
+ for (from <- Seq(TimestampType, TimestampNTZType)) {
+ evalEach(from, Seq(Long.MinValue, 0L, Long.MaxValue))(cast(_,
DateType, mode))
+ }
+ for ((from, values) <- Seq[(DataType, Seq[Any])]((DecimalType(38, 0),
+ Seq("-" + "9" * 38, "9" * 38).map(d => Decimal(BigDecimal(d)))),
+ (DecimalType(38, 37), Seq("-9." + "9" * 37, "9." + "9" * 37)
+ .map(d => Decimal(BigDecimal(d), 38, 37))));
+ to <- Seq(FloatType, DoubleType)) {
+ evalEach(from, values)(cast(_, to, mode))
+ }
+ for (from <- Seq(StringType, StringType("UTF8_LCASE"), VarcharType(3),
CharType(3));
+ to <- Seq(StringType, StringType("UNICODE_CI"))) {
+ evalEach(from, strings)(cast(_, to, mode))
+ }
+ }
+ }
+
+ test("SPARK-60882: canEvaluateUnconditionally: substring and date and time
fields") {
+ val s = AttributeReference("s", StringType)()
+ assert(ExprUtils.canEvaluateUnconditionally(Substring(s, Literal(2),
Literal(3))))
+ assert(!ExprUtils.canEvaluateUnconditionally(Substring(s, Cast(a,
IntegerType,
+ evalMode = EvalMode.ANSI), Literal(3))))
+ val date = AttributeReference("date", DateType)()
+ val ts = AttributeReference("ts", TimestampType)()
+ val ntz = AttributeReference("ntz", TimestampNTZType)()
+ def dateFields(d: Expression): Seq[Expression] = Seq(Year(d),
YearOfWeek(d), Quarter(d),
+ Month(d), DayOfMonth(d), DayOfYear(d), DayOfWeek(d), WeekDay(d),
WeekOfYear(d),
+ MonthName(d), DayName(d))
+ def timeFields(t: Expression): Seq[Expression] = Seq(Hour(t, Some("UTC")),
+ Minute(t, Some("Asia/Tokyo")), Second(t, Some("America/Los_Angeles")),
+ SecondWithFraction(t, Some("UTC")))
+ (dateFields(date) ++ timeFields(ts) ++ timeFields(ntz)).foreach { e =>
+ assert(ExprUtils.canEvaluateUnconditionally(e), e)
+ }
+ // `year(ts)` reads the date of a timestamp, but `year(s)` casts a string
to a date, which
+ // can fail in ANSI mode.
+ assert(ExprUtils.canEvaluateUnconditionally(
+ EqualTo(Year(Cast(ts, DateType, Some("UTC"), EvalMode.ANSI)),
Literal(2024))))
+ assert(!ExprUtils.canEvaluateUnconditionally(
+ Year(Cast(s, DateType, Some("UTC"), EvalMode.ANSI))))
+ assert(!ExprUtils.canEvaluateUnconditionally(
+ Hour(Cast(s, TimestampType, Some("UTC"), EvalMode.ANSI), Some("UTC"))))
+
+ // None of them raises, also at the ends of the ranges of dates and
timestamps.
+ dateFields(date).indices.foreach { idx =>
+ evalEach(DateType, Seq(Int.MinValue, 0, Int.MaxValue))(d =>
dateFields(d)(idx))
+ }
+ for (t <- Seq(TimestampType, TimestampNTZType); idx <-
timeFields(ts).indices) {
+ evalEach(t, Seq(Long.MinValue, 0L, Long.MaxValue))(v =>
timeFields(v)(idx))
+ }
+ val positions = Seq(Int.MinValue, -1, 0, 1, Int.MaxValue)
+ // Also non-ASCII strings, which take another path, and invalid UTF-8.
+ val nonAscii = Seq(0xE9, 'a', 0x4E2D).map(_.toChar).mkString
+ val strings = Seq("", "abc", nonAscii).map(UTF8String.fromString) ++
+ Seq(Array(0xFF, 'a'), Array('a', 0xE2)).map(b =>
UTF8String.fromBytes(b.map(_.toByte)))
+ for (input <- Seq((StringType, strings), (BinaryType,
strings.map(_.getBytes)))) {
+ evalRows(input, (IntegerType, positions), (IntegerType, positions))(c =>
+ Substring(c(0), c(1), c(2)))
+ }
}
test("canEvaluateUnconditionally: non-deterministic expressions are
excluded") {
diff --git
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ConstantPropagationSuite.scala
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ConstantPropagationSuite.scala
index 1dd1641fec47..906b68784dbb 100644
---
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ConstantPropagationSuite.scala
+++
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/ConstantPropagationSuite.scala
@@ -286,4 +286,42 @@ class ConstantPropagationSuite extends PlanTest {
assert(first(conjunct) == "(a = 1)")
}
}
+
+ test("SPARK-60882: Propagate a constant into an expression that can not
fail") {
+ // An addition with ANSI mode off can not fail, so `b` is replaced in it,
although `c` is not.
+ val legacy = NumericEvalContext(EvalMode.LEGACY)
+ comparePlans(
+ Optimize.execute(
+ testRelation.where(columnA > Add(columnC, columnB, legacy) && columnB
=== 2).analyze),
+ testRelation.where(columnA > Add(columnC, Literal(2), legacy) && columnB
=== 2).analyze)
+
+ // In ANSI mode it can overflow, so it keeps `b`, and the equality goes
first.
+ val ansi = NumericEvalContext(EvalMode.ANSI)
+ comparePlans(
+ Optimize.execute(
+ testRelation.where(columnA > Add(columnC, columnB, ansi) && columnB
=== 2).analyze),
+ testRelation.where(columnB === 2 && columnA > Add(columnC, columnB,
ansi)).analyze)
+
+ // Also under a `COLLATE`.
+ val strings = LocalRelation($"s".string, $"n".int)
+ comparePlans(
+ Optimize.execute(strings.where($"s" === "ab" &&
+ Length(Collate(Substring($"s", Literal(1), $"n"),
ResolvedCollation("UNICODE_CI"))) > 1)
+ .analyze),
+ strings.where($"s" === "ab" &&
+ Length(Collate(Substring(Literal("ab"), Literal(1), $"n"),
ResolvedCollation("UNICODE_CI")))
+ > 1).analyze)
+
+ // Not into a cast of a DOUBLE to a string: a row with `x` = -0.0 passes
`x = 0.0`, but
+ // `CAST(x * y AS STRING)` keeps the sign.
+ val doubles = LocalRelation($"x".double, $"y".double)
+ val signed = doubles.where($"x" === 0.0 &&
+ Cast(Multiply($"x", $"y", ansi), StringType) === "-0.0").analyze
+ comparePlans(Optimize.execute(signed), signed)
+
+ // Nor a string of a trim collation into `length`: a row with `s` = 'a '
passes `s = 'a'`.
+ val trimmed = LocalRelation(AttributeReference("s",
StringType("UTF8_BINARY_RTRIM"))())
+ val lengthOfTrimmed = trimmed.where($"s" === "a" && Length($"s") ===
2).analyze
+ comparePlans(Optimize.execute(lengthOfTrimmed), lengthOfTrimmed)
+ }
}
diff --git
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala
index 536f9fe79f44..5907fdee4bd6 100644
---
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala
+++
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/FilterPushdownSuite.scala
@@ -137,23 +137,54 @@ class FilterPushdownSuite extends PlanTest {
test("SPARK-60980: a condition that can fail is not combined ahead of a
non-deterministic " +
"or throwable one") {
+ // The divisions are built in ANSI mode, where they can fail, whatever the
session's mode is.
+ def divide(l: Expression, r: Expression): Expression =
+ Divide(l, r, NumericEvalContext(EvalMode.ANSI))
Seq(Rand(0) > 0.1, IsNull(RaiseError(Literal("boom")))).foreach { blocker
=>
val originalQuery =
testRelation
.where($"c" === 1)
- .where($"a" / $"b" > 1 && blocker && $"b" / $"a" > 1 && $"a" === 1)
+ .where(divide($"a", $"b") > 1 && blocker && divide($"b", $"a") > 1
&& $"a" === 1)
val optimized = Optimize.execute(originalQuery.analyze)
val correctAnswer =
testRelation
- .where($"c" === 1 && $"a" / $"b" > 1 && $"a" === 1)
- .where(blocker && $"b" / $"a" > 1)
+ .where($"c" === 1 && divide($"a", $"b") > 1 && $"a" === 1)
+ .where(blocker && divide($"b", $"a") > 1)
.analyze
comparePlans(optimized, correctAnswer)
}
}
+ test("SPARK-60882: a condition that can not fail is combined ahead of a
non-deterministic " +
+ "or throwable one") {
+ // An addition or a division with ANSI mode off, a multiplication of
doubles also with ANSI
+ // mode on, a substring and a string search with an explicit COLLATE can
not fail, so they are
+ // combined with the filter below, as a comparison is.
+ val legacy = NumericEvalContext(EvalMode.LEGACY)
+ val ansi = NumericEvalContext(EvalMode.ANSI)
+ Seq(Rand(0) > 0.1, IsNull(RaiseError(Literal("boom")))).foreach { blocker
=>
+ Seq[Expression](Add($"a", Literal(1), legacy) > 0, Divide($"b", $"a",
legacy) > 1,
+ Multiply($"a".cast(DoubleType), Literal(1.1), ansi) > 100,
+ Substring($"a".cast(StringType), Literal(1), Literal(2)) === "1",
+ Contains(Collate($"a".cast(StringType),
ResolvedCollation("UNICODE_CI")),
+ Substring($"b".cast(StringType), Literal(1), Literal(1)))
+ ).foreach { cannotFail =>
+ val originalQuery = testRelation
+ .where($"c" === 1)
+ .where(blocker && cannotFail)
+
+ val correctAnswer = testRelation
+ .where($"c" === 1 && cannotFail)
+ .where(blocker)
+ .analyze
+
+ comparePlans(Optimize.execute(originalQuery.analyze), correctAnswer)
+ }
+ }
+ }
+
test("SPARK-16164: Filter pushdown should keep the ordering in the logical
plan") {
val originalQuery =
testRelation
diff --git
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/InferFiltersFromConstraintsSuite.scala
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/InferFiltersFromConstraintsSuite.scala
index af728c5974d7..976dca2f24ce 100644
---
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/InferFiltersFromConstraintsSuite.scala
+++
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/InferFiltersFromConstraintsSuite.scala
@@ -381,6 +381,74 @@ class InferFiltersFromConstraintsSuite extends PlanTest {
anyOf($"y") && anyOf($"x")).analyze)
}
+ test("SPARK-60882: a constraint that can not fail is inferred as a filter") {
+ val legacy = NumericEvalContext(EvalMode.LEGACY)
+ val ansi = NumericEvalContext(EvalMode.ANSI)
+ val dates = LocalRelation($"x".date, $"y".date)
+ val strings = LocalRelation($"x".string, $"y".string)
+ val ints = LocalRelation($"x".int, $"y".int)
+ val doubles = LocalRelation($"x".double, $"y".double)
+ def infer(relation: LocalRelation, condition: Expression => Expression):
LogicalPlan =
+ InferFiltersFromConstraints(
+ LikeSimplification(relation.where($"x" === $"y" &&
condition($"y")).analyze))
+ def notNullAnd(relation: LocalRelation, condition: Expression =>
Expression): LogicalPlan =
+ relation.where(IsNotNull($"x") && IsNotNull($"y") && $"x" === $"y" &&
condition($"y"))
+ // `LIKE 'a%'` is simplified to a `StartsWith` before this rule runs.
+ Seq[(LocalRelation, Expression => Expression, Expression => Expression)](
+ (dates, Year(_) === 2024, Year(_) === 2024),
+ (strings, Like(_, Literal("a%"), '\\'), StartsWith(_, Literal("a"))),
+ (ints, Add(_, Literal(1), legacy) > 5, Add(_, Literal(1), legacy) > 5),
+ (doubles, Multiply(_, Literal(1.1), ansi) > 100.0, Multiply(_,
Literal(1.1), ansi) > 100.0)
+ ).foreach { case (relation, condition, simplified) =>
+ comparePlans(infer(relation, condition), relation.where(simplified($"x")
&& IsNotNull($"x") &&
+ IsNotNull($"y") && $"x" === $"y" && simplified($"y")).analyze)
+ }
+ // Not `upper`, which can not fail but is not accepted, nor an addition in
ANSI mode, which can.
+ // Nor a cast of a DOUBLE to a string: on a row with `x` = 0.0 and `y` =
-0.0, `x = y` holds,
+ // but `CAST(x AS STRING)` is '0.0'. Nor `length` of a string of a trim
collation: on a row
+ // with `x` = 'a' and `y` = 'a ', `x = y` holds, but their lengths differ.
+ val trimmed = LocalRelation(AttributeReference("x",
StringType("UTF8_BINARY_RTRIM"))(),
+ AttributeReference("y", StringType("UTF8_BINARY_RTRIM"))())
+ // Nor a `try_cast` of a UDT to a string: on a row with vectors (0.0) and
(-0.0), `x = y`
+ // holds, but their strings differ.
+ val udt = new TestUDT.MyDenseVectorUDT()
+ val vectors = LocalRelation(AttributeReference("x", udt)(),
AttributeReference("y", udt)())
+ Seq[(LocalRelation, Expression => Expression)](
+ (strings, Upper(_) === "A"), (ints, Add(_, Literal(1), ansi) > 5),
+ (doubles, Cast(_, StringType) === "-0.0"), (trimmed, Length(_) === 2),
+ (vectors, Cast(_, StringType, evalMode = EvalMode.TRY) ===
"(-0.0)")).foreach {
+ case (relation, condition) =>
+ comparePlans(infer(relation, condition), notNullAnd(relation,
condition).analyze)
+ }
+ }
+
+ test("SPARK-60882: a constraint through a widening of a decimal of a
negative scale is " +
+ "inferred") {
+ withSQLConf(SQLConf.LEGACY_ALLOW_NEGATIVE_SCALE_OF_DECIMAL_ENABLED.key ->
"true") {
+ val relation = LocalRelation(AttributeReference("x", DecimalType(3,
-2))(),
+ AttributeReference("y", DecimalType(10, 0))())
+ val query = relation.where($"x" === $"y" && $"y" > 5).analyze
+ val Filter(condition, _) = InferFiltersFromConstraints(query)
+ // Type coercion widens `x` to DECIMAL(10, 0), and `CAST(x AS
DECIMAL(10, 0)) > 5` follows.
+ assert(splitConjunctivePredicates(condition).exists {
+ case GreaterThan(Cast(a: AttributeReference, _: DecimalType, _, _), _)
=> a.name == "x"
+ case _ => false
+ }, condition)
+ }
+ }
+
+ test("SPARK-60882: a constraint that can not fail is inferred on the other
side of a join") {
+ val left = LocalRelation($"x".date)
+ val right = LocalRelation($"y".date)
+ testConstraintsAfterJoin(
+ left.subquery("l"),
+ right.where(Year($"y") === 2024).subquery("r"),
+ left.where(IsNotNull($"x") && Year($"x") === 2024).subquery("l"),
+ right.where(IsNotNull($"y") && Year($"y") === 2024).subquery("r"),
+ Inner,
+ Some("l.x".attr === "r.y".attr))
+ }
+
test("SPARK-36978: IsNotNull constraints on structs should apply at the
member field " +
"instead of the root level nested type") {
val structTestRelation = LocalRelation($"a".struct(StructType(
diff --git
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala
index a627d00d20a7..2f5360b50df8 100644
---
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala
+++
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregatesSuite.scala
@@ -18,7 +18,7 @@ package org.apache.spark.sql.catalyst.optimizer
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.dsl.plans._
-import org.apache.spark.sql.catalyst.expressions.{AttributeReference,
CaseWhen, Cast, Coalesce, Exists, Expression, GetMapValue, GetStructField, If,
InSubquery, ListQuery, Literal, Lower, Not, Or, Rand, Round}
+import org.apache.spark.sql.catalyst.expressions.{Add, AttributeReference,
CaseWhen, Cast, Coalesce, Divide, EvalMode, Exists, Expression, GetMapValue,
GetStructField, If, InSubquery, ListQuery, Literal, Lower, Not,
NumericEvalContext, Or, Rand, Round, Substring}
import
org.apache.spark.sql.catalyst.expressions.aggregate.{AggregateExpression,
CollectSet, Count, Sum}
import org.apache.spark.sql.catalyst.plans.PlanTest
import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, Expand,
LocalRelation, LogicalPlan}
@@ -482,9 +482,10 @@ class RewriteDistinctAggregatesSuite extends PlanTest {
test("conditional: throwable distinct child keeps the raw key") {
// Division can throw under ANSI on rows the filter rejects. Wrapping it in
// the guard would skip those evaluations, so the Expand key stays raw.
+ val division = Divide(Symbol("c"), Symbol("b"),
NumericEvalContext(EvalMode.ANSI))
val input = conditionalTestRelation
.groupBy(Symbol("a"))(
- Count(Symbol("c") / Symbol("b")).toAggregateExpression(
+ Count(division).toAggregateExpression(
isDistinct = true, filter = Some(Symbol("a") > 0)).as("cnt"))
.analyze
val child = input.collectFirst {
@@ -805,10 +806,10 @@ class RewriteDistinctAggregatesSuite extends PlanTest {
val unsafeBases = Seq(
// Division may throw (e.g. divide-by-zero under ANSI mode) on rows
where the
// original IF branch is not taken.
- Symbol("c") / Symbol("b"),
+ Divide(Symbol("c"), Symbol("b"), NumericEvalContext(EvalMode.ANSI)),
// Cast may throw under ANSI mode.
- Cast(Symbol("c"), StringType),
- // String functions are not in the branch-safe whitelist.
+ Cast(Symbol("d"), IntegerType, evalMode = EvalMode.ANSI),
+ // Lower is not in the branch-safe allowlist.
Lower(Symbol("d")))
unsafeBases.foreach { base =>
assertNotCanonicalized(conditionalTestRelation, base)
@@ -819,7 +820,10 @@ class RewriteDistinctAggregatesSuite extends PlanTest {
// Predicate and null-handling bases on the flat test relation.
Seq(
Symbol("b") > Symbol("c"),
- Coalesce(Seq(Symbol("b"), Literal(0, IntegerType))))
+ Coalesce(Seq(Symbol("b"), Literal(0, IntegerType))),
+ // Arithmetic with ANSI mode off and a substring can not fail either.
+ Add(Symbol("b"), Symbol("c"), NumericEvalContext(EvalMode.LEGACY)),
+ Substring(Symbol("d"), Literal(1), Literal(2)))
.foreach { base =>
assertCanonicalized(conditionalTestRelation, base)
}
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/StreamedSideJoinCondition.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/StreamedSideJoinCondition.scala
index e5e5778e5d2f..7157d8ff48b7 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/StreamedSideJoinCondition.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/joins/StreamedSideJoinCondition.scala
@@ -43,7 +43,7 @@ private[joins] object StreamedSideJoinCondition extends
PredicateHelper {
* row, including rows that have no buffered match and would never evaluate
the conjunct
* otherwise, so hoisting a conjunct that can throw could turn a valid
outer/anti result
* into an exception, and hoisting a non-deterministic conjunct would change
how many
- * times it is evaluated per streamed row. A whitelist of total expression
families is
+ * times it is evaluated per streamed row. An allowlist of total expression
families is
* used instead of [[Expression.throwable]], which is opt-in metadata that
UDFs such as
* ScalaUDF do not override, so a throwing UDF would report non-throwable.
*/
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
index 7a2753571c4e..6dd2810b6812 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/WholeStageCodegenSuite.scala
@@ -3060,10 +3060,17 @@ class WholeStageCodegenSuite extends SharedSparkSession
val noRaise = "SELECT a FROM t WHERE (a > 0 OR b > 0) AND x = 1 AND y =
0"
checkAnswer(sql(noRaise), Row(0))
assert(!hasNullConjunctFlag(noRaise))
- // `y + 1 > 0` can raise, so the flag is generated.
+ // `y + 1 > 0` can raise in ANSI mode, so the flag is generated.
val raise = "SELECT a FROM t WHERE (a > 0 OR b > 0) AND x = 1 AND y + 1
> 0"
- checkAnswer(sql(raise), Row(0))
- assert(hasNullConjunctFlag(raise))
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+ checkAnswer(sql(raise), Row(0))
+ assert(hasNullConjunctFlag(raise))
+ }
+ // With ANSI mode off, it can not, so no flag is generated.
+ withSQLConf(SQLConf.ANSI_ENABLED.key -> "false") {
+ checkAnswer(sql(raise), Row(0))
+ assert(!hasNullConjunctFlag(raise))
+ }
}
}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SplitStreamedSideJoinConditionSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SplitStreamedSideJoinConditionSuite.scala
index ec3f8d3c8c43..1c81131c375b 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SplitStreamedSideJoinConditionSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/joins/SplitStreamedSideJoinConditionSuite.scala
@@ -18,7 +18,7 @@
package org.apache.spark.sql.execution.joins
import org.apache.spark.sql.{DataFrame, QueryTest}
-import org.apache.spark.sql.catalyst.expressions.{Add, And, LessThan, Literal,
Rand}
+import org.apache.spark.sql.catalyst.expressions.{Add, And, EvalMode,
LessThan, Literal, NumericEvalContext, Rand}
import org.apache.spark.sql.catalyst.plans.LeftOuter
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.test.SharedSparkSession
@@ -111,12 +111,19 @@ class SplitStreamedSideJoinConditionSuite extends
QueryTest with SharedSparkSess
// non-throwing children. It must stay in the residual, which is why a
!throwable
// gate is not sufficient and the hoisted part is restricted to expression
families
// with a reliable non-throwing contract.
- val unmarkedThrowable = LessThan(Add(a, Literal(1L)), Literal(5L))
+ val unmarkedThrowable =
+ LessThan(Add(a, Literal(1L), NumericEvalContext(EvalMode.ANSI)),
Literal(5L))
assert(!unmarkedThrowable.throwable)
val (streamedOnly, rest) = StreamedSideJoinCondition.split(
Some(And(hoistable, unmarkedThrowable)), LeftOuter, streamed,
splitEnabled = true)
assert(streamedOnly.contains(hoistable))
assert(rest.contains(unmarkedThrowable))
+ // With ANSI mode off, the addition can not fail, so it is hoisted.
+ val legacyAdd = LessThan(Add(a, Literal(1L),
NumericEvalContext(EvalMode.LEGACY)), Literal(5L))
+ val (legacyStreamedOnly, legacyRest) = StreamedSideJoinCondition.split(
+ Some(And(hoistable, legacyAdd)), LeftOuter, streamed, splitEnabled =
true)
+ assert(legacyStreamedOnly.contains(And(hoistable, legacyAdd)))
+ assert(legacyRest.isEmpty)
}
test("split does not hoist non-deterministic conjuncts") {
@@ -223,7 +230,7 @@ class SplitStreamedSideJoinConditionSuite extends QueryTest
with SharedSparkSess
// when it is false or null. The UDF conjunct holds for the matched rows
(ids 0..3) and
// throws for the unmatched ones (ids 4..7), so it throws exactly when it is
wrongly
// hoisted and evaluated before probing. A ScalaUDF does not override
`throwable`, so
- // the old !throwable gate hoisted it; the whitelist keeps it in the
residual.
+ // the old !throwable gate hoisted it; the allowlist keeps it in the
residual.
private def throwingUdfJoin: DataFrame = {
spark.udf.register("throw_unless_true", (v: Boolean) =>
if (v) true else throw new RuntimeException("throw_unless_true evaluated
to false"))
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]