Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.spark.sql.catalyst.expressions;

import org.apache.spark.sql.errors.QueryExecutionErrors;

/**
* Static helpers used by {@code BinaryArithmetic.doGenCode} (and
* corresponding eval paths) for ANSI overflow-checked {@code byte} and
* {@code short} arithmetic. Primitive {@code int} / {@code long} /
* {@code float} / {@code double} arithmetic stays inline -- routing those
* single-bytecode operations through a static method would be a runtime
* regression.
*/
public final class ArithmeticUtils {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Duplication with ByteExactNumeric / ShortExactNumeric. numerics.scala already has plus/minus/times that do exactly the same int-promoted check and throw the same error. Now there are two implementations of the same logic — one in numerics.scala (still used) and one in ArithmeticUtils.java (used by the new eval branches and by codegen).


private ArithmeticUtils() {}

// ----- Byte: int arithmetic with overflow check (ANSI) -----

public static byte byteAddExact(byte a, byte b) {
int r = a + b;
if (r < Byte.MIN_VALUE || r > Byte.MAX_VALUE) {
throw QueryExecutionErrors.binaryArithmeticCauseOverflowError(a, "+", b, "try_add");
}
return (byte) r;
}

public static byte byteSubtractExact(byte a, byte b) {
int r = a - b;
if (r < Byte.MIN_VALUE || r > Byte.MAX_VALUE) {
throw QueryExecutionErrors.binaryArithmeticCauseOverflowError(a, "-", b, "try_subtract");
}
return (byte) r;
}

public static byte byteMultiplyExact(byte a, byte b) {
int r = a * b;
if (r < Byte.MIN_VALUE || r > Byte.MAX_VALUE) {
throw QueryExecutionErrors.binaryArithmeticCauseOverflowError(a, "*", b, "try_multiply");
}
return (byte) r;
}

// ----- Short: int arithmetic with overflow check (ANSI) -----

public static short shortAddExact(short a, short b) {
int r = a + b;
if (r < Short.MIN_VALUE || r > Short.MAX_VALUE) {
throw QueryExecutionErrors.binaryArithmeticCauseOverflowError(a, "+", b, "try_add");
}
return (short) r;
}

public static short shortSubtractExact(short a, short b) {
int r = a - b;
if (r < Short.MIN_VALUE || r > Short.MAX_VALUE) {
throw QueryExecutionErrors.binaryArithmeticCauseOverflowError(a, "-", b, "try_subtract");
}
return (short) r;
}

public static short shortMultiplyExact(short a, short b) {
int r = a * b;
if (r < Short.MIN_VALUE || r > Short.MAX_VALUE) {
throw QueryExecutionErrors.binaryArithmeticCauseOverflowError(a, "*", b, "try_multiply");
}
return (short) r;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -301,31 +301,22 @@ abstract class BinaryArithmetic extends BinaryOperator with SupportQueryContext
val mathUtils = IntervalMathUtils.getClass.getCanonicalName.stripSuffix("$")
defineCodeGen(ctx, ev, (eval1, eval2) => s"$mathUtils.${exactMathMethod.get}($eval1, $eval2)")
// byte and short are casted into int when add, minus, times or divide
case ByteType | ShortType if failOnError =>
val opName = symbol match {
case "+" => "Add"
case "-" => "Subtract"
case "*" => "Multiply"
case _ =>
throw QueryExecutionErrors.notOverrideExpectedMethodsError(this.getClass.getName,
s"genCode for Byte/Short with symbol '$symbol'", "genCode")
Comment on lines +309 to +311
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In practice, only Add/Subtract/Multiply reach BinaryArithmetic.doGenCode with byte/short (Divide/Remainder/Pmod/IntegralDivide override doGenCode via DivModLike). Reasonable defensive coding, but the notOverrideExpectedMethodsError message ("genCode") is a slightly awkward fit — it's normally used for missing method overrides, not for a runtime symbol mismatch. A SparkException.internalError(s"Unexpected symbol $symbol for Byte/Short BinaryArithmetic") would read more accurately.

}
val typeName = if (dataType == ByteType) "byte" else "short"
val arithmeticUtils = classOf[ArithmeticUtils].getName
defineCodeGen(ctx, ev, (eval1, eval2) =>
s"$arithmeticUtils.$typeName${opName}Exact($eval1, $eval2)")
case ByteType | ShortType =>
nullSafeCodeGen(ctx, ev, (eval1, eval2) => {
val tmpResult = ctx.freshName("tmpResult")
val try_suggestion = symbol match {
case "+" => "try_add"
case "-" => "try_subtract"
case "*" => "try_multiply"
case _ => "unknown_function"
}
val overflowCheck = if (failOnError) {
val javaType = CodeGenerator.boxedType(dataType)
s"""
|if ($tmpResult < $javaType.MIN_VALUE || $tmpResult > $javaType.MAX_VALUE) {
| throw QueryExecutionErrors.binaryArithmeticCauseOverflowError(
| $eval1, "$symbol", $eval2, "$try_suggestion");
|}
""".stripMargin
} else {
""
}
s"""
|${CodeGenerator.JAVA_INT} $tmpResult = $eval1 $symbol $eval2;
|$overflowCheck
|${ev.value} = (${CodeGenerator.javaType(dataType)})($tmpResult);
""".stripMargin
s"${ev.value} = (${CodeGenerator.javaType(dataType)})($eval1 $symbol $eval2);"
})
case IntegerType | LongType if failOnError && exactMathMethod.isDefined =>
nullSafeCodeGen(ctx, ev, (eval1, eval2) => {
Expand Down Expand Up @@ -458,6 +449,10 @@ case class Add(
MathUtils.addExact(input1.asInstanceOf[Int], input2.asInstanceOf[Int], getContextOrNull())
case _: LongType if failOnError =>
MathUtils.addExact(input1.asInstanceOf[Long], input2.asInstanceOf[Long], getContextOrNull())
case _: ByteType if failOnError =>
ArithmeticUtils.byteAddExact(input1.asInstanceOf[Byte], input2.asInstanceOf[Byte])
case _: ShortType if failOnError =>
ArithmeticUtils.shortAddExact(input1.asInstanceOf[Short], input2.asInstanceOf[Short])
Comment on lines +452 to +455
Copy link
Copy Markdown
Member

@viirya viirya May 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why route Add/Subtract/Multiply.nullSafeEval through the helper rather than just leaving them as numeric.plus(...)? The pre-PR case _ => numeric.plus(...) was concise and already correct. The new ANSI-specific branches add 8 lines × 3 expressions = 24 lines of arguably unnecessary code.

Consider dropping the eval-side branches (Add/Subtract/Multiply.nullSafeEval byte/short cases). They're redundant with the existing numeric.plus-via-ByteExactNumeric route.

case _ => numeric.plus(input1, input2)
}

Expand Down Expand Up @@ -555,6 +550,10 @@ case class Subtract(
input1.asInstanceOf[Long],
input2.asInstanceOf[Long],
getContextOrNull())
case _: ByteType if failOnError =>
ArithmeticUtils.byteSubtractExact(input1.asInstanceOf[Byte], input2.asInstanceOf[Byte])
case _: ShortType if failOnError =>
ArithmeticUtils.shortSubtractExact(input1.asInstanceOf[Short], input2.asInstanceOf[Short])
Comment on lines +553 to +556
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ditto

case _ => numeric.minus(input1, input2)
}

Expand Down Expand Up @@ -625,6 +624,10 @@ case class Multiply(
input1.asInstanceOf[Long],
input2.asInstanceOf[Long],
getContextOrNull())
case _: ByteType if failOnError =>
ArithmeticUtils.byteMultiplyExact(input1.asInstanceOf[Byte], input2.asInstanceOf[Byte])
case _: ShortType if failOnError =>
ArithmeticUtils.shortMultiplyExact(input1.asInstanceOf[Short], input2.asInstanceOf[Short])
Comment on lines +627 to +630
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ditto

case _ => numeric.times(input1, input2)
}

Expand Down