dongjoon-hyun commented on code in PR #60769:
URL: https://github.com/apache/spark/pull/60769#discussion_r4660826572
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TryEval.scala:
##########
@@ -54,6 +54,76 @@ case class TryEval(child: Expression) extends
UnaryExpression {
copy(child = newChild)
}
+@ExpressionDescription(
+ usage = "_FUNC_(expr) - Returns the absolute value of `expr`, and NULL on
overflow. " +
+ "The acceptable input types are the same as for `abs`.",
+ arguments = """
+ Arguments:
+ * expr - The numeric or interval value to take the absolute value of.
+ An expression that evaluates to a numeric or interval.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(-1);
+ 1
+ > SELECT _FUNC_(-2147483648);
+ NULL
+ > SELECT _FUNC_(INTERVAL -'1-1' YEAR TO MONTH);
+ 1-1
+ """,
+ since = "4.5.0",
+ group = "math_funcs")
+case class TryAbs(expr: Expression, replacement: Expression)
+ extends RuntimeReplaceable with InheritAnalysisRules {
+ 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)
Review 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).
##########
docs/sql-ref-ansi-compliance.md:
##########
@@ -408,6 +408,8 @@ When ANSI mode is on, it throws exceptions for invalid
operations. You can use t
- `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.
Review 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.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala:
##########
@@ -223,6 +223,123 @@ private[expressions] object UnaryArithmetic {
}
}
+/**
+ * [[Abs]] or [[UnaryMinus]] that returns NULL where the ANSI form raises an
overflow error, in
+ * every mode. It cannot raise itself, so the subclasses are [[NoThrow]]. Over
an integral value
+ * 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 {
Review 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.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TryEval.scala:
##########
@@ -54,6 +54,76 @@ case class TryEval(child: Expression) extends
UnaryExpression {
copy(child = newChild)
}
+@ExpressionDescription(
+ usage = "_FUNC_(expr) - Returns the absolute value of `expr`, and NULL on
overflow. " +
+ "The acceptable input types are the same as for `abs`.",
+ arguments = """
+ Arguments:
+ * expr - The numeric or interval value to take the absolute value of.
+ An expression that evaluates to a numeric or interval.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(-1);
+ 1
+ > SELECT _FUNC_(-2147483648);
+ NULL
+ > SELECT _FUNC_(INTERVAL -'1-1' YEAR TO MONTH);
+ 1-1
+ """,
+ since = "4.5.0",
+ group = "math_funcs")
+case class TryAbs(expr: Expression, replacement: Expression)
Review 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(...)`.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala:
##########
@@ -326,6 +326,11 @@ class ExprUtilsSuite extends SparkFunSuite with SQLHelper {
evalEach(t, values)(UnaryMinus(_, failOnError = true))
evalEach(t, values)(Abs(_, failOnError = true))
}
+ // The null-on-overflow forms of try_abs and try_negative.
+ for ((t, values) <- Seq(longs, ints, shorts, bytes)) {
+ evalEach(t, values)(AbsOrNull(_))
Review 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.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ExprUtilsSuite.scala:
##########
@@ -725,11 +730,12 @@ class ExprUtilsSuite extends SparkFunSuite with SQLHelper
{
val (always, others) = classes.partition(classOf[NoThrow].isAssignableFrom)
always.foreach(c => assert(!Modifier.isAbstract(c.getModifiers), c))
assert(always.map(_.getSimpleName).sorted === Seq(
- "And", "Coalesce", "Collate", "Contains", "CreateArray",
"CreateNamedStruct", "DayName",
- "DayOfMonth", "DayOfWeek", "DayOfYear", "EndsWith", "EqualNullSafe",
"EqualTo",
+ "AbsOrNull", "And", "Coalesce", "Collate", "Contains", "CreateArray",
"CreateNamedStruct",
+ "DayName", "DayOfMonth", "DayOfWeek", "DayOfYear", "EndsWith",
"EqualNullSafe", "EqualTo",
"GetArrayStructFields", "GetMapValue", "GetStructField", "GreaterThan",
"GreaterThanOrEqual", "Hour", "In", "InSet", "IsNaN", "IsNotNull",
"IsNull", "Length",
- "LessThan", "LessThanOrEqual", "Minute", "Month", "MonthName", "Not",
"NullIf",
+ "LessThan", "LessThanOrEqual", "Minute", "Month", "MonthName",
"NegateOrNull", "Not",
+ "NullIf",
"OctetLength", "Or", "Quarter", "Second", "SecondWithFraction", "Size",
"StartsWith",
"Substring", "WeekDay", "WeekOfYear", "Year", "YearOfWeek"))
Review Comment:
nit: `"NullIf",` is left alone on this line. How about reflowing the
remaining lines?
```suggestion
"NullIf", "OctetLength", "Or", "Quarter", "Second",
"SecondWithFraction", "Size",
"StartsWith", "Substring", "WeekDay", "WeekOfYear", "Year",
"YearOfWeek"))
```
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/arithmetic.scala:
##########
@@ -223,6 +223,123 @@ private[expressions] object UnaryArithmetic {
}
}
+/**
+ * [[Abs]] or [[UnaryMinus]] that returns NULL where the ANSI form raises an
overflow error, in
+ * every mode. It cannot raise itself, so the subclasses are [[NoThrow]]. Over
an integral value
+ * 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 {
+ override def nullIntolerant: Boolean = true
+
+ override def nullable: Boolean = true
+
+ override def dataType: DataType = child.dataType
+
+ override def contextIndependentFoldable: Boolean =
child.contextIndependentFoldable
+
+ /** The result for `value`, which is not the minimum value of its type. */
+ protected def op(value: Long): Long
+
+ /** The Java code of the result for `value`, which is not the minimum value
of its type. */
+ protected def opCode(value: String): String
+
+ /** The interpreted evaluation of a non-null input for the input type. */
+ protected def nonNullEvaluator: Any => Any = dataType match {
+ case ByteType => input =>
+ val v = input.asInstanceOf[Byte]
+ if (v == Byte.MinValue) null else op(v).toByte
+ case ShortType => input =>
+ val v = input.asInstanceOf[Short]
+ if (v == Short.MinValue) null else op(v).toShort
+ case IntegerType | _: YearMonthIntervalType => input =>
+ val v = input.asInstanceOf[Int]
+ if (v == Int.MinValue) null else op(v).toInt
+ case LongType | _: DayTimeIntervalType => input =>
+ val v = input.asInstanceOf[Long]
+ if (v == Long.MinValue) null else op(v)
+ }
+
+ // Resolved once, rather than for every row.
+ private lazy val evalNonNull = nonNullEvaluator
+
+ protected override def nullSafeEval(input: Any): Any = evalNonNull(input)
+
+ override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val javaType = CodeGenerator.javaType(dataType)
+ val boxedType = CodeGenerator.boxedType(dataType)
+ nullSafeCodeGen(ctx, ev, c => {
+ val value = ctx.freshName("value")
+ s"""
+ |$javaType $value = $c;
+ |if ($value == $boxedType.MIN_VALUE) {
+ | ${ev.isNull} = true;
+ |} else {
+ | ${ev.value} = ($javaType) (${opCode(value)});
+ |}
+ |""".stripMargin
+ })
+ }
+}
+
+case class AbsOrNull(child: Expression) extends UnaryArithmeticOrNull with
NoThrow {
+ override def inputTypes: Seq[AbstractDataType] =
+ Seq(TypeCollection(IntegralType, AnsiIntervalType))
+
+ override def prettyName: String = "try_abs"
+
+ override protected def op(value: Long): Long = math.abs(value)
+
+ override protected def opCode(value: String): String =
s"java.lang.Math.abs($value)"
+
+ override protected def withNewChildInternal(newChild: Expression): AbsOrNull
=
+ copy(child = newChild)
+}
+
+/**
+ * Also over a [[CalendarInterval]], which overflows when one of its fields is
the minimum value
+ * of its type.
+ */
+case class NegateOrNull(child: Expression) extends UnaryArithmeticOrNull with
NoThrow {
+ override def inputTypes: Seq[AbstractDataType] =
+ Seq(TypeCollection(IntegralType, AnsiIntervalType, CalendarIntervalType))
+
+ override def prettyName: String = "try_negative"
+
+ override protected def op(value: Long): Long = -value
+
+ override protected def opCode(value: String): String = s"-($value)"
+
+ 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) {
Review 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.
--
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]