dongjoon-hyun commented on code in PR #60285:
URL: https://github.com/apache/spark/pull/60285#discussion_r4555459697
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/IntervalExpressionsSuite.scala:
##########
@@ -514,6 +517,73 @@ class IntervalExpressionsSuite extends SparkFunSuite with
ExpressionEvalHelper {
}
}
+ test("SPARK-61352: an interval error keeps its query context") {
+ // The helpers evaluate a serialized copy of the expression, as an
executor does. `TreeNode`
+ // does not serialize `origin`, so the copy must carry the context itself.
Each expression is
+ // built inside `withOrigin` and evaluated outside it: evaluated inside,
the copy would read
+ // the origin back from `CurrentOrigin` and the test could not fail.
+ def withQuery(query: String)(expr: => Expression): (() => Expression,
String) = {
+ val o = Origin(
+ line = Some(1),
+ startPosition = Some(7),
+ startIndex = Some(7),
+ stopIndex = Some(7 + query.length - 1),
+ sqlText = Some(s"select $query"))
+ (() => withOrigin(o)(expr), s"== SQL (line 1, position 8) ==\nselect
$query")
+ }
+ // A cast to the type of the expression, with a context of its own (ANSI)
or none (LEGACY).
+ val castContext = "== SQL (line 1, position 1) ==\ncast"
+ def sameTypeCast(expr: Expression, evalMode: EvalMode.Value): Expression =
{
+ val o = Origin(
+ line = Some(1),
+ startPosition = Some(0),
+ startIndex = Some(0),
+ stopIndex = Some(3),
+ sqlText = Some("cast"))
+ withOrigin(o)(Cast(expr, expr.dataType, None, evalMode))
+ }
+ val ser = new JavaSerializer(new SparkConf()).newInstance()
+
+ val ymMin = Literal(Period.ofMonths(Int.MinValue))
+ val dtMin = Literal(Duration.of(Long.MinValue, ChronoUnit.MICROS))
+ Seq(
+ withQuery("ym / -1")(DivideYMInterval(ymMin, Literal(-1))),
+ withQuery("ym / -1.0D")(DivideYMInterval(ymMin, Literal(-1.0d))),
+ withQuery("ym / 0")(DivideYMInterval(ymMin, Literal(0))),
+ withQuery("dt / -1L")(DivideDTInterval(dtMin, Literal(-1L))),
+ withQuery("dt / -1BD")(DivideDTInterval(dtMin, Literal(Decimal(-1)))),
+ withQuery("dt / 0")(DivideDTInterval(dtMin, Literal(0))),
+ withQuery("make_ym_interval(2147483647, 0)")(
+ MakeYMInterval(Literal(Int.MaxValue), Literal(0))),
+ withQuery("make_dt_interval(2147483647)")(
+ MakeDTInterval(Literal(Int.MaxValue), Literal(0), Literal(0),
+ Literal(Decimal(0, Decimal.MAX_LONG_DIGITS, 6))))
+ ).foreach { case (newExpr, context) =>
+ // Each form gets an instance of its own, since `copyTagsFrom` changes
the instance that a
+ // rule returns, so that a failure tells which form lost the context.
+ // A rule that replaces a node calls `copyTagsFrom` on the replacement,
as `SimplifyCasts`
+ // does when it replaces a cast to the same type with its child: the
expression takes the
+ // context of an ANSI cast, and keeps its own under a LEGACY cast, which
has none.
+ val replacingCasts = Seq(EvalMode.ANSI -> castContext, EvalMode.LEGACY
-> context).map {
+ case (evalMode, expected) =>
+ sameTypeCast(newExpr(), evalMode).transformDown {
+ case Cast(child, dataType, _, _) if child.dataType == dataType =>
child
Review Comment:
nit: this partial function copies the same-type case of `SimplifyCasts`
(`expressions.scala` L1419) instead of running the rule, so the test checks a
copy of the rule rather than the rule that the PR description and the
end-to-end tests rely on, and it would not notice a change in `SimplifyCasts`
itself. How about applying the rule to a one-column `Project`?
```scala
val plan = Project(
Seq(Alias(sameTypeCast(newExpr(), evalMode), "c")()),
OneRowRelation())
SimplifyCasts(plan).expressions.head.children.head -> expected
```
This needs imports of
`org.apache.spark.sql.catalyst.optimizer.SimplifyCasts` and
`org.apache.spark.sql.catalyst.plans.logical.{OneRowRelation, Project}`.
##########
sql/core/src/test/scala/org/apache/spark/sql/errors/QueryExecutionAnsiErrorsSuite.scala:
##########
@@ -115,6 +116,47 @@ class QueryExecutionAnsiErrorsSuite extends
SharedSparkSession {
context = ExpectedContext(fragment = "interval 1 day / 0", start = 7,
stop = 24))
}
+ test("SPARK-61352: an interval division error keeps its query context") {
+ // Without whole-stage codegen the projection is built on the executor
from a deserialized
+ // copy of the expression. `SimplifyCasts` replaces a cast to the type of
the division with
+ // the division, which takes the context of the cast, as the other ANSI
expressions do.
+ Seq("true", "false").foreach { wholeStage =>
+ withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage) {
+ Seq(ymDivide, s"CAST($ymDivide AS INTERVAL YEAR TO MONTH)").foreach {
query =>
Review Comment:
A same-type `try_cast` gives the division its context too, and unlike
`CAST`, it does so whatever the session's ANSI setting. If I read the code
correctly:
- `Cast.ansiEnabled` is true for `EvalMode.TRY` unless
`canUseLegacyCastForTryCast`, which holds only from a string to a fractional or
datetime type. So `initQueryContext` gives an interval-to-interval `try_cast` a
context, even with `spark.sql.ansi.enabled=false`.
- `SimplifyCasts` removes a cast to the same type whatever its eval mode,
and `copyTagsFrom` then gives the context of the `try_cast` to the division,
which now keeps it in its `queryContext` field.
For example, in either mode:
```sql
SELECT try_cast(CAST(CAST(id - 2147483648 AS INT) AS INTERVAL MONTH) / -1 AS
INTERVAL YEAR TO MONTH)
FROM range(1)
```
The query still fails, since `try_cast` does not catch an error of its
child, but the `== SQL ==` block now points at the whole `try_cast(...)`, which
reads as if `try_cast` itself had failed. On master, with whole-stage codegen,
it pointed at the division. In non-ANSI mode this also differs from a `CAST` to
the division's own type, where the division keeps its own context
(`QueryExecutionErrorsSuite` L851-852).
Is this intended? If so, could we list it in the user-facing section and add
a `try_cast` case here and in `QueryExecutionErrorsSuite`?
##########
sql/core/src/test/scala/org/apache/spark/sql/errors/QueryExecutionAnsiErrorsSuite.scala:
##########
@@ -115,6 +116,47 @@ class QueryExecutionAnsiErrorsSuite extends
SharedSparkSession {
context = ExpectedContext(fragment = "interval 1 day / 0", start = 7,
stop = 24))
}
+ test("SPARK-61352: an interval division error keeps its query context") {
+ // Without whole-stage codegen the projection is built on the executor
from a deserialized
+ // copy of the expression. `SimplifyCasts` replaces a cast to the type of
the division with
+ // the division, which takes the context of the cast, as the other ANSI
expressions do.
+ Seq("true", "false").foreach { wholeStage =>
+ withSQLConf(SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> wholeStage) {
+ Seq(ymDivide, s"CAST($ymDivide AS INTERVAL YEAR TO MONTH)").foreach {
query =>
+ checkError(
+ exception = intercept[SparkArithmeticException] {
+ sql(s"SELECT $query FROM range(1)").collect()
+ },
+ condition = "INTERVAL_ARITHMETIC_OVERFLOW.WITH_SUGGESTION",
+ sqlState = "22015",
+ parameters = Map("functionName" -> "`try_divide`"),
+ context = expectedContext(query, query))
+ }
+ Seq(dtDivide, s"CAST($dtDivide AS INTERVAL DAY TO SECOND)").foreach {
query =>
+ checkError(
+ exception = intercept[SparkArithmeticException] {
+ sql(s"SELECT $query FROM range(1)").collect()
+ },
+ condition = "INTERVAL_DIVIDED_BY_ZERO",
+ sqlState = "22012",
+ parameters = Map.empty[String, String],
+ context = expectedContext(query, query))
+ }
Review Comment:
nit: the two `checkError` blocks differ only in the queries, `condition`,
`sqlState` and `parameters`. How about a case table and one loop, as the new
test in `QueryExecutionErrorsSuite` (L858-882) does? Then the two suites keep
the same structure.
```suggestion
Seq(
(Seq(ymDivide, s"CAST($ymDivide AS INTERVAL YEAR TO MONTH)"),
"INTERVAL_ARITHMETIC_OVERFLOW.WITH_SUGGESTION", "22015",
Map("functionName" -> "`try_divide`")),
(Seq(dtDivide, s"CAST($dtDivide AS INTERVAL DAY TO SECOND)"),
"INTERVAL_DIVIDED_BY_ZERO", "22012", Map.empty[String, String])
).foreach { case (queries, condition, sqlState, parameters) =>
queries.foreach { query =>
checkError(
exception = intercept[SparkArithmeticException] {
sql(s"SELECT $query FROM range(1)").collect()
},
condition = condition,
sqlState = sqlState,
parameters = parameters,
context = expectedContext(query, query))
}
}
```
--
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]