Skip to content

[SPARK-41219][SQL] IntegralDivide use decimal(1, 0) to represent 0 #38760

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

Closed
wants to merge 1 commit into from
Closed
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
Expand Up @@ -865,7 +865,9 @@ case class IntegralDivide(
// This follows division rule
val intDig = p1 - s1 + s2
// No precision loss can happen as the result scale is 0.
DecimalType.bounded(intDig, 0)
// If intDig is 0 that means the result data is 0, to be safe we use decimal(1, 0)
// to represent 0.
DecimalType.bounded(if (intDig == 0) 1 else intDig, 0)
}

override def sqlOperator: String = "div"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3584,6 +3584,11 @@ class DataFrameSuite extends QueryTest
assert(row.getInt(0).toString == row.getString(3))
}
}

test("SPARK-41219: IntegralDivide use decimal(1, 0) to represent 0") {
val df = Seq("0.5944910").toDF("a")
checkAnswer(df.selectExpr("cast(a as decimal(7,7)) div 100"), Row(0))
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@cloud-fan see this test, the decimal type of IntegralDivide can be decimal(0, 0) (other BinaryArithmetic does not have the issue).

override def resultDecimalType(p1: Int, s1: Int, p2: Int, s2: Int): DecimalType = {
// This follows division rule
val intDig = p1 - s1 + s2
// No precision loss can happen as the result scale is 0.
DecimalType.bounded(intDig, 0)

Or, we may change it to max(p1 - s1 + s2, 1)

}
}

case class GroupByKey(a: Int, b: Int)
Expand Down