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
Expand Up @@ -1406,7 +1406,7 @@ case class Cast(
b => try {
changePrecision(Decimal(fractional.toDouble(b)), target)
} catch {
case _: NumberFormatException => null
case _: NumberFormatException => errorOrNull(b, from, target)
}
case x: DayTimeIntervalType =>
buildCast[Long](_, dt =>
Expand Down Expand Up @@ -1943,15 +1943,24 @@ case class Cast(
"""
case x: FractionalType =>
// All other numeric types can be represented precisely as Doubles
(c, evPrim, evNull) =>
(c, evPrim, evNull) => {
val overflow = if (ansiEnabled) {
val fromDt = ctx.addReferenceObj("from", from, from.getClass.getName)
val toDt = ctx.addReferenceObj("to", target, target.getClass.getName)
code"""throw QueryExecutionErrors.castingCauseOverflowError(
$c, $fromDt, $toDt);"""
} else {
code"$evNull = true;"
}
code"""
try {
Decimal $tmp = Decimal.apply(scala.math.BigDecimal.valueOf((double) $c));
${changePrecision(tmp, target, evPrim, evNull, canNullSafeCast, ctx)}
} catch (java.lang.NumberFormatException e) {
$evNull = true;
$overflow
}
"""
}
case x: DayTimeIntervalType =>
(c, evPrim, evNull) =>
val u = IntervalUtils.getClass.getCanonicalName.stripSuffix("$")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,27 @@ class CastWithAnsiOnSuite extends CastSuiteBase with QueryErrorsBase {
cast(Literal(134.12), DecimalType(3, 2)), "cannot be represented")
}

test("SPARK-58316: casting non-finite floating values to decimal") {
val targetType = DecimalType(38, 2)
Seq(
(Literal(Float.NaN), "NaN"),
(Literal(Float.PositiveInfinity), "Infinity"),
(Literal(Float.NegativeInfinity), "-Infinity"),
(Literal(Double.NaN), "NaN"),
(Literal(Double.PositiveInfinity), "Infinity"),
(Literal(Double.NegativeInfinity), "-Infinity")
).foreach { case (literal, value) =>
checkErrorInExpression[SparkArithmeticException](
cast(literal, targetType),
"CAST_OVERFLOW",
Map(
"value" -> value,
"sourceType" -> s"\"${literal.dataType.sql}\"",
"targetType" -> s"\"${targetType.sql}\"",
"ansiConfig" -> "\"spark.sql.ansi.enabled\""))
}
}

test("ANSI mode: disallow type conversions between Numeric types and Date type") {
import DataTypeTestUtils.numericTypes
checkInvalidCastFromNumericTypeToDateType()
Expand Down