Skip to content

[SPARK-52659][SQL]Misleading modulo error message in ansi mode #51378

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
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
6 changes: 6 additions & 0 deletions common/utils/src/main/resources/error/error-conditions.json
Original file line number Diff line number Diff line change
Expand Up @@ -1366,6 +1366,12 @@
],
"sqlState" : "22012"
},
"REMAINDER_BY_ZERO" : {
"message" : [
"Remainder by zero. Use `try_mod` to tolerate divisor being 0 and return NULL instead. If necessary set <config> to \"false\" to bypass this error."
],
"sqlState" : "22012"
},
"DUPLICATED_CTE_NAMES" : {
"message" : [
"CTE definition can't have duplicate names: <duplicateNames>."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,13 @@ trait DivModLike extends BinaryArithmetic {
} else {
if (isZero(input2)) {
// when we reach here, failOnError must be true.
throw QueryExecutionErrors.divideByZeroError(getContextOrNull())
val context = getContextOrNull()
val ex = this match {
case _: Remainder => QueryExecutionErrors.remainderByZeroError(context)
case _: Pmod => QueryExecutionErrors.remainderByZeroError(context)
case _ => QueryExecutionErrors.divideByZeroError(context)
}
throw ex
}
if (checkDivideOverflow && input1 == Long.MinValue && input2 == -1) {
throw QueryExecutionErrors.overflowInIntegralDivideError(getContextOrNull())
Expand All @@ -660,6 +666,15 @@ trait DivModLike extends BinaryArithmetic {
/**
* Special case handling due to division/remainder by 0 => null or ArithmeticException.
*/
protected def divideByZeroErrorCode(ctx: CodegenContext): String = {
val errorContextCode = getContextOrNullCode(ctx, failOnError)
this match {
case _: Remainder => s"QueryExecutionErrors.remainderByZeroError($errorContextCode)"
case _: Pmod => s"QueryExecutionErrors.remainderByZeroError($errorContextCode)"
case _ => s"QueryExecutionErrors.divideByZeroError($errorContextCode)"
}
}

override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
val eval1 = left.genCode(ctx)
val eval2 = right.genCode(ctx)
Expand Down Expand Up @@ -697,7 +712,7 @@ trait DivModLike extends BinaryArithmetic {
// evaluate right first as we have a chance to skip left if right is 0
if (!left.nullable && !right.nullable) {
val divByZero = if (failOnError) {
s"throw QueryExecutionErrors.divideByZeroError($errorContextCode);"
s"throw ${divideByZeroErrorCode(ctx)};"
} else {
s"${ev.isNull} = true;"
}
Expand All @@ -715,7 +730,7 @@ trait DivModLike extends BinaryArithmetic {
} else {
val nullOnErrorCondition = if (failOnError) "" else s" || $isZero"
val failOnErrorBranch = if (failOnError) {
s"if ($isZero) throw QueryExecutionErrors.divideByZeroError($errorContextCode);"
s"if ($isZero) throw ${divideByZeroErrorCode(ctx)};"
} else {
""
}
Expand Down Expand Up @@ -1038,7 +1053,7 @@ case class Pmod(
} else {
if (isZero(input2)) {
// when we reach here, failOnError must bet true.
throw QueryExecutionErrors.divideByZeroError(getContextOrNull())
throw QueryExecutionErrors.remainderByZeroError(getContextOrNull())
}
pmodFunc(input1, input2)
}
Expand Down Expand Up @@ -1095,7 +1110,7 @@ case class Pmod(
// evaluate right first as we have a chance to skip left if right is 0
if (!left.nullable && !right.nullable) {
val divByZero = if (failOnError) {
s"throw QueryExecutionErrors.divideByZeroError($errorContext);"
s"throw QueryExecutionErrors.remainderByZeroError($errorContext);"
} else {
s"${ev.isNull} = true;"
}
Expand All @@ -1112,7 +1127,7 @@ case class Pmod(
} else {
val nullOnErrorCondition = if (failOnError) "" else s" || $isZero"
val failOnErrorBranch = if (failOnError) {
s"if ($isZero) throw QueryExecutionErrors.divideByZeroError($errorContext);"
s"if ($isZero) throw QueryExecutionErrors.remainderByZeroError($errorContext);"
} else {
""
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,14 @@ private[sql] object QueryExecutionErrors extends QueryErrorsBase with ExecutionE
summary = getSummary(context))
}

def remainderByZeroError(context: QueryContext): ArithmeticException = {
new SparkArithmeticException(
errorClass = "REMAINDER_BY_ZERO",
messageParameters = Map("config" -> toSQLConf(SQLConf.ANSI_ENABLED.key)),
context = Array(context),
summary = getSummary(context))
}

def intervalDividedByZeroError(context: QueryContext): ArithmeticException = {
new SparkArithmeticException(
errorClass = "INTERVAL_DIVIDED_BY_ZERO",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ class ArithmeticExpressionSuite extends SparkFunSuite with ExpressionEvalHelper
}
withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
checkExceptionInExpression[ArithmeticException](
Remainder(left, Literal(convert(0))), "Division by zero")
Remainder(left, Literal(convert(0))), "Remainder by zero")
}
}
checkEvaluation(Remainder(positiveShortLit, positiveShortLit), 0.toShort)
Expand Down Expand Up @@ -567,7 +567,7 @@ class ArithmeticExpressionSuite extends SparkFunSuite with ExpressionEvalHelper
}
withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
checkExceptionInExpression[ArithmeticException](
Pmod(left, Literal(convert(0))), "Division by zero")
Pmod(left, Literal(convert(0))), "Remainder by zero")
}
}
checkEvaluation(Pmod(Literal(-7), Literal(3)), 2)
Expand Down Expand Up @@ -873,12 +873,11 @@ class ArithmeticExpressionSuite extends SparkFunSuite with ExpressionEvalHelper

test("SPARK-33008: division by zero on divide-like operations returns incorrect result") {
withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
val operators: Seq[((Expression, Expression) => Expression, ((Int => Any) => Unit) => Unit)] =
// Test division operations
val divideOperators: Seq[((Expression, Expression) => Expression, ((Int => Any) => Unit) => Unit)] =
Seq((Divide(_, _), testDecimalAndDoubleType),
(IntegralDivide(_, _), testDecimalAndLongType),
(Remainder(_, _), testNumericDataTypes),
(Pmod(_, _), testNumericDataTypes))
operators.foreach { case (operator, testTypesFn) =>
(IntegralDivide(_, _), testDecimalAndLongType))
divideOperators.foreach { case (operator, testTypesFn) =>
testTypesFn { convert =>
val one = Literal(convert(1))
val zero = Literal(convert(0))
Expand All @@ -887,6 +886,20 @@ class ArithmeticExpressionSuite extends SparkFunSuite with ExpressionEvalHelper
checkExceptionInExpression[ArithmeticException](operator(one, zero), "Division by zero")
}
}

// Test remainder operations
val remainderOperators: Seq[((Expression, Expression) => Expression, ((Int => Any) => Unit) => Unit)] =
Seq((Remainder(_, _), testNumericDataTypes),
(Pmod(_, _), testNumericDataTypes))
remainderOperators.foreach { case (operator, testTypesFn) =>
testTypesFn { convert =>
val one = Literal(convert(1))
val zero = Literal(convert(0))
checkEvaluation(operator(Literal.create(null, one.dataType), zero), null)
checkEvaluation(operator(one, Literal.create(null, zero.dataType)), null)
checkExceptionInExpression[ArithmeticException](operator(one, zero), "Remainder by zero")
}
}
}
}

Expand Down Expand Up @@ -931,12 +944,11 @@ class ArithmeticExpressionSuite extends SparkFunSuite with ExpressionEvalHelper

test("SPARK-34920: error class") {
withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
val operators: Seq[((Expression, Expression) => Expression, ((Int => Any) => Unit) => Unit)] =
// Test division operations
val divideOperators: Seq[((Expression, Expression) => Expression, ((Int => Any) => Unit) => Unit)] =
Seq((Divide(_, _), testDecimalAndDoubleType),
(IntegralDivide(_, _), testDecimalAndLongType),
(Remainder(_, _), testNumericDataTypes),
(Pmod(_, _), testNumericDataTypes))
operators.foreach { case (operator, testTypesFn) =>
(IntegralDivide(_, _), testDecimalAndLongType))
divideOperators.foreach { case (operator, testTypesFn) =>
testTypesFn { convert =>
val one = Literal(convert(1))
val zero = Literal(convert(0))
Expand All @@ -946,6 +958,21 @@ class ArithmeticExpressionSuite extends SparkFunSuite with ExpressionEvalHelper
"Division by zero")
}
}

// Test remainder operations
val remainderOperators: Seq[((Expression, Expression) => Expression, ((Int => Any) => Unit) => Unit)] =
Seq((Remainder(_, _), testNumericDataTypes),
(Pmod(_, _), testNumericDataTypes))
remainderOperators.foreach { case (operator, testTypesFn) =>
testTypesFn { convert =>
val one = Literal(convert(1))
val zero = Literal(convert(0))
checkEvaluation(operator(Literal.create(null, one.dataType), zero), null)
checkEvaluation(operator(one, Literal.create(null, zero.dataType)), null)
checkExceptionInExpression[SparkArithmeticException](operator(one, zero),
"Remainder by zero")
}
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ struct<>
-- !query output
org.apache.spark.SparkArithmeticException
{
"errorClass" : "DIVIDE_BY_ZERO",
"errorClass" : "REMAINDER_BY_ZERO",
"sqlState" : "22012",
"messageParameters" : {
"config" : "\"spark.sql.ansi.enabled\""
Expand All @@ -58,7 +58,7 @@ struct<>
-- !query output
org.apache.spark.SparkArithmeticException
{
"errorClass" : "DIVIDE_BY_ZERO",
"errorClass" : "REMAINDER_BY_ZERO",
"sqlState" : "22012",
"messageParameters" : {
"config" : "\"spark.sql.ansi.enabled\""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,26 @@ class QueryExecutionAnsiErrorsSuite extends QueryTest
callSitePattern = getCurrentClassCallSitePattern))
}

test("REMAINDER_BY_ZERO: can't take modulo of an integer by zero") {
checkError(
exception = intercept[SparkArithmeticException] {
sql("select 6 % 0").collect()
},
condition = "REMAINDER_BY_ZERO",
sqlState = "22012",
parameters = Map("config" -> ansiConf),
context = ExpectedContext(fragment = "6 % 0", start = 7, stop = 11))

checkError(
exception = intercept[SparkArithmeticException] {
sql("select pmod(6, 0)").collect()
},
condition = "REMAINDER_BY_ZERO",
sqlState = "22012",
parameters = Map("config" -> ansiConf),
context = ExpectedContext(fragment = "pmod(6, 0)", start = 7, stop = 17))
}

test("INTERVAL_DIVIDED_BY_ZERO: interval divided by zero") {
checkError(
exception = intercept[SparkArithmeticException] {
Expand Down