Repository navigation
Conversation
…verflow Under ANSI mode, abs(x) and negative(x) raise ARITHMETIC_OVERFLOW for the minimum value of an integral type, and there was no try_ form for them. try_abs and try_negative return NULL there instead. With ANSI mode off they behave as abs and negative do, and for the other types, including intervals, they are abs and negative. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… and streaming The docs said NULL for any unrepresentable result, but the functions return NULL only for the minimum value of an integral type under ANSI mode. The expression examples no longer depend on the ANSI default, which the non-ANSI CI job turns off. Also test DECIMAL(38, 0) extremes, which cannot overflow, and add a streaming golden test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…r try_ functions try_abs and try_negative now return NULL for the minimum value of an integral type with ANSI mode off too, and for the minimum of an ANSI interval, and try_negative for a calendar interval with a field at its minimum, as try_add, try_subtract and try_multiply return NULL on overflow in both modes and over intervals. The null-on-overflow expressions check their input types and are NoThrow. Also test invalid input types, and expect the exact interval overflow error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nd resolve their evaluation once Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@HyukjinKwon @zhengruifeng @srielau could you take a look when you have a moment? This adds |
dongjoon-hyun
left a comment
There was a problem hiding this comment.
Thank you for adding try_abs and try_negative, @MaxGekk. The core overflow logic looks correct to me: the minimum-value checks in both the interpreted and codegen paths, the CalendarInterval field checks, and the nullability. I left a few comments. In short:
- STRING input under ANSI mode (
TryEval.scala):try_abs('abc')/try_negative('abc')raiseCAST_INVALID_INPUT, whiletry_add(1, 'abc')returns NULL. This is inconsistent with the othertry_*functions. - Overflow error hint (
sql-ref-ansi-compliance.md): the ANSI overflow errors ofabs/negativedon't suggest the new functions yet, unlike+,-, and*. A follow-up is fine. - Design question (
arithmetic.scala):EvalMode.TRYforAbs/UnaryMinusinstead of a parallel*OrNullhierarchy, to avoid duplicating the overflow rule. - nit (
arithmetic.scala): share theCalendarIntervaloverflow check between the interpreted and codegen paths. - Error message (
TryEval.scala):sqlExprshowsabs(...)instead oftry_abs(...)for invalid input types. The existingtry_*functions behave the same, so this is optional. - nit (
ExprUtilsSuite): cover the interval types in theNoThrowevaluation checks. - nit (
ExprUtilsSuite): reflow the sorted class list.
| def this(expr: Expression) = this(expr, expr.dataType match { | ||
| case _: IntegralType | _: AnsiIntervalType => AbsOrNull(expr) | ||
| // The other types that `abs` accepts cannot overflow. | ||
| case _ => Abs(expr) |
There was a problem hiding this comment.
Under ANSI mode, this fallback makes a STRING argument raise CAST_INVALID_INPUT from the implicit cast to DOUBLE, e.g. SELECT try_negative('abc') in the ANSI golden file. Meanwhile, try_add(1, 'abc') returns NULL because TryAdd wraps non-numeric inputs in TryEval.
I understand from the PR description that avoiding TryEval is intentional so that the argument's own errors (e.g. try_abs(2147483647 + 1)) still surface. However, from the user's perspective, try_abs('abc') failing where try_add(1, 'abc') returns NULL looks inconsistent with the other try_* functions and with the EvalMode.TRY contract ("returning null result on errors").
Could we make the StringType case NULL-on-error as well (e.g., TryEval(Abs(expr)) only for that case), or at least document this difference in the function usage and sql-ref-ansi-compliance.md? The same applies to TryNegative (L116).
| - `try_multiply`: identical to the add operator `*`, except that it returns `NULL` result instead of throwing an exception on integral value overflow. | ||
| - `try_divide`: identical to the division operator `/`, except that it returns `NULL` result instead of throwing an exception on dividing 0. | ||
| - `try_mod`: identical to the remainder operator `%`, except that it returns `NULL` result instead of throwing an exception on dividing 0. | ||
| - `try_abs`: identical to the function `abs`, except that it returns `NULL` result instead of throwing an exception on integral or interval value overflow. |
There was a problem hiding this comment.
Now that try_abs and try_negative exist, shall we suggest them in the ANSI overflow errors of abs, negative, and the unary minus, like +, -, and * suggest try_add, try_subtract, and try_multiply? Currently, MathUtils.negateExact (Byte/Short/Int/Long) and IntervalMathUtils.negateExact pass no suggested function, so SELECT abs(-2147483648) under ANSI mode still shows only the following, the same as the example at L82 of this doc.
[ARITHMETIC_OVERFLOW] integer overflow. If necessary set spark.sql.ansi.enabled to "false" to bypass this error.
Users who hit this error have no way to discover the new functions. It's fine to do this in a follow-up.
| * or an ANSI interval, both overflow only on the minimum value of the type. `try_abs` and | ||
| * `try_negative` are replaced with a subclass over the types that can overflow. | ||
| */ | ||
| abstract class UnaryArithmeticOrNull extends UnaryExpression with ExpectsInputTypes { |
There was a problem hiding this comment.
Design question: instead of a parallel hierarchy (UnaryArithmeticOrNull, AbsOrNull, NegateOrNull), have you considered giving Abs and UnaryMinus an EvalMode with TRY, like Add, Subtract, and Multiply? Then try_abs could be Abs(expr, EvalMode.TRY), as TryAdd uses Add(left, right, EvalMode.TRY).
With the current approach, the "overflow only on the minimum value" rule lives in MathUtils.negateExact, IntervalUtils.negateExact, and here (in both the interpreted and codegen paths), and the type dispatch in TryAbs / TryNegative repeats it once more. If the supported types or overflow rules of abs / negative change later, all of them need to be kept in sync manually. I understand that changing failOnError: Boolean to EvalMode is a bigger change, so I'm fine with deferring it if you prefer.
| override protected def nonNullEvaluator: Any => Any = dataType match { | ||
| case CalendarIntervalType => input => | ||
| val v = input.asInstanceOf[CalendarInterval] | ||
| if (v.months == Int.MinValue || v.days == Int.MinValue || v.microseconds == Long.MinValue) { |
There was a problem hiding this comment.
nit: This overflow condition is duplicated in the codegen string below (L329-330), and it also mirrors IntervalUtils.negateExact. How about adding a helper like IntervalUtils.negateOrNull(interval: CalendarInterval): CalendarInterval, which returns null on overflow, and calling it from both the interpreted and codegen paths? Then the two paths cannot drift apart.
| """, | ||
| since = "4.5.0", | ||
| group = "math_funcs") | ||
| case class TryAbs(expr: Expression, replacement: Expression) |
There was a problem hiding this comment.
For an invalid input type, the type check fails on the replacement, so sqlExpr shows a function that the user didn't write. For example, the golden file has "sqlExpr" : "\"abs(true)\"" for try_abs(true) and "sqlExpr" : "\"abs(make_interval(0, 1, 0, 0, 0, 0, 0.000000))\"" for try_abs(make_interval(0, 1)). Only fragment shows try_abs(...).
I know the existing try_* functions (e.g. try_add, try_reflect) behave the same way, so this is not a blocker. Just mentioning it in case you want to report it as try_abs(...) / try_negative(...).
| } | ||
| // The null-on-overflow forms of try_abs and try_negative. | ||
| for ((t, values) <- Seq(longs, ints, shorts, bytes)) { | ||
| evalEach(t, values)(AbsOrNull(_)) |
There was a problem hiding this comment.
nit: AbsOrNull and NegateOrNull are declared NoThrow over all of their input types, but these checks cover only the integral types. TryEvalSuite already checks the interval minimums functionally, but for completeness of the NoThrow checks here, could we also add both ANSI interval types (like L289-291 do for UnaryMinus / Abs) and CalendarIntervalType for NegateOrNull? Then a later change that makes an interval path throw would fail this suite too.
| "NullIf", | ||
| "OctetLength", "Or", "Quarter", "Second", "SecondWithFraction", "Size", "StartsWith", | ||
| "Substring", "WeekDay", "WeekOfYear", "Year", "YearOfWeek")) |
There was a problem hiding this comment.
nit: "NullIf", is left alone on this line. How about reflowing the remaining lines?
| "NullIf", | |
| "OctetLength", "Or", "Quarter", "Second", "SecondWithFraction", "Size", "StartsWith", | |
| "Substring", "WeekDay", "WeekOfYear", "Year", "YearOfWeek")) | |
| "NullIf", "OctetLength", "Or", "Quarter", "Second", "SecondWithFraction", "Size", | |
| "StartsWith", "Substring", "WeekDay", "WeekOfYear", "Year", "YearOfWeek")) |
What changes were proposed in this pull request?
This PR adds two SQL functions,
try_abs(expr)andtry_negative(expr), with the semantics ofabsandnegative, except that they return NULL instead of raising an overflow error, astry_add,try_subtractandtry_multiplydo. The result is NULL for:TINYINT,SMALLINT,INTandBIGINT;YEAR TO MONTHorDAY TO SECONDinterval;try_negative, a legacyCALENDAR INTERVALwith a field at its minimum value (absdoes not accept that type).Like the other
try_arithmetic functions, they return NULL there whateverspark.sql.ansi.enabledis. For every other input they areabsandnegative: floating-point and decimal values cannot overflow (Decimal.absand negation keep the precision), and a string or NULL argument is coerced toDOUBLEas forabs.Implementation:
TryAbsandTryNegativeinTryEval.scalaareRuntimeReplaceablewithInheritAnalysisRules, likeTryAdd. Over a type that can overflow, the replacement isAbsOrNull/NegateOrNull; otherwise it isAbs/UnaryMinus.AbsOrNullandNegateOrNull(inarithmetic.scala, next toAbs) extendUnaryArithmeticOrNull. They compare the value with the minimum of its type, and return NULL there, in both the interpreted path and generated code. They arenullable, check their input types, and areNoThrow, since they cannot raise themselves.TryEval, so an error raised by the argument itself still surfaces: under ANSI mode,try_abs(2147483647 + 1)raisesARITHMETIC_OVERFLOWfrom the addition.try_addover intervals wraps the expression inTryEval, which also hides such errors. A consequence: under ANSI mode,try_negative('abc')raisesCAST_INVALID_INPUTfrom the implicit cast toDOUBLE, wheretry_add(1, 'abc')returns NULL.functions.try_abs/functions.try_negativein Scala, and the PySpark (classic and Connect) functions, with docs. The SQL function reference andsql-ref-ansi-compliance.mdlist both.Why are the changes needed?
Spark has
try_counterparts for the arithmetic operators that raise an overflow error under ANSI mode (try_add,try_subtract,try_multiply,try_divide,try_mod,try_sum,try_avg), but not for the unary ones. Under ANSI mode,abs(x)and-xraiseARITHMETIC_OVERFLOWfor the minimum value of an integral type, for exampleabs(-2147483648), and the only ways to get NULL instead were to turn ANSI mode off or to writeCASE WHEN x = <minimum> THEN NULL ELSE abs(x) ENDper type.Does this PR introduce any user-facing change?
Yes, two new SQL functions and the matching Scala and Python APIs:
How was this patch tested?
TryEvalSuite:AbsOrNullandNegateOrNullover the minimum, minimum + 1, maximum, -1, 0, 1 and NULL of each integral type and of both ANSI interval types, in the interpreted, mutable-projection and unsafe-projection modes. Alsotry_negativeover calendar intervals with each field at its minimum, the types that cannot overflow, the replacement with ANSI mode on and off, the input type checks, and an argument whose own error is not caught.ExprUtilsSuite: both classes are listed asNoThrow, and they do not raise over the extreme values of each integral type.try_arithmetic.sql(ANSI and non-ANSI golden files): literals and column-read inputs of every integral type, intervals, decimals atDECIMAL(38, 0)extremes, doubles, strings, NULL, an argument that raises, and invalid input types.streaming/try-abs-negative.sql: both functions in a streaming flow.MathFunctionsSuite: the SQL and DataFrame API forms with ANSI mode on and off.PlanGenerationTestSuite/ProtoToParsedPlanTestSuite: new Connect golden files.ExpressionsSchemaSuite(regeneratedsql-expression-schema.md),ExpressionInfoSuite(the examples), and the function parity test inDataFrameFunctionsSuite.Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 5.5)