Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Add a new implementation for sum for dec type to handle overflow, Add…
… a new DecimalSum and add a analyzer rule and changes to optimizer rule. Add tests

For now the DecimalSum has the code to handle other types, incase we want to put this logic back into Sum after discussion
  • Loading branch information
skambha committed Apr 27, 2020
commit 6979e8dceed4ad632ee8114ccf4561ed63f35d19
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ class Analyzer(
ExtractWindowExpressions ::
GlobalAggregates ::
ResolveAggregateFunctions ::
UseDecimalSum ::
TimeWindowing ::
ResolveInlineTables(conf) ::
ResolveHigherOrderFunctions(v1SessionCatalog) ::
Expand Down Expand Up @@ -3066,6 +3067,15 @@ class Analyzer(
}
}

/**
* Substitute Sum on decimal type to use DecimalSum implementation as it handles overflow
*/
object UseDecimalSum extends Rule[LogicalPlan] {
def apply(plan: LogicalPlan): LogicalPlan = plan.resolveExpressions {
case Sum(e) if e.resolved && e.dataType.isInstanceOf[DecimalType] => DecimalSum(e)
}
}

/** Rule to mostly resolve, normalize and rewrite column names based on case sensitivity. */
object ResolveAlterTableChanges extends Rule[LogicalPlan] {
def apply(plan: LogicalPlan): LogicalPlan = plan.resolveOperatorsUp {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* 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.aggregate

import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._

case class DecimalSum(child: Expression) extends DeclarativeAggregate with ImplicitCastInputTypes {

override def children: Seq[Expression] = child :: Nil

override def nullable: Boolean = true

// Return data type.
override def dataType: DataType = resultType

override def inputTypes: Seq[AbstractDataType] = Seq(NumericType)

private lazy val resultType = child.dataType match {
case DecimalType.Fixed(precision, scale) =>
DecimalType.bounded(precision + 10, scale)
case _: IntegralType => LongType
case _ => DoubleType
}

private lazy val sumDataType = resultType

private lazy val sum = AttributeReference("sum", sumDataType)()
private lazy val overflow = AttributeReference("overflow", BooleanType, false)()

private lazy val zero = Literal.default(resultType)

override lazy val aggBufferAttributes = sum :: overflow :: Nil

override lazy val initialValues: Seq[Expression] = Seq(
/* sum = */ Literal.create(null, sumDataType),
/* overflow = */ Literal.create(false, BooleanType)
)

override lazy val updateExpressions: Seq[Expression] = {
if (child.nullable) {
resultType match {
case d: DecimalType =>
Seq(
If(overflow, Literal.create(null, sumDataType), coalesce(
CheckOverflow(coalesce(sum, zero) + child.cast(sumDataType), d, true), sum)),
Copy link
Contributor

Choose a reason for hiding this comment

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

I don't think we should check overflow at every step. For example, we may add a big value which makes the sum overflow, then add a big negative value and we are not overflow afer that.

overflow ||
coalesce(HasOverflow(coalesce(sum, zero) + child.cast(sumDataType), d), false)
)
case _ => Seq(coalesce(coalesce(sum, zero) + child.cast(sumDataType), sum), false)
}
} else {
resultType match {
case d: DecimalType =>
Seq(
If(overflow, Literal.create(null, sumDataType),
CheckOverflow(coalesce(sum, zero) + child.cast(sumDataType), d, true)),
overflow ||
coalesce(HasOverflow(coalesce(sum, zero) + child.cast(sumDataType), d), false)
)
case _ => Seq(coalesce(sum, zero) + child.cast(sumDataType), false)
}
}
}

override lazy val mergeExpressions: Seq[Expression] = {
resultType match {
case d: DecimalType =>
Seq(
If(coalesce(overflow.left, false) || coalesce(overflow.right, false),
Literal.create(null, d),
coalesce(CheckOverflow(coalesce(sum.left, zero) + sum.right, d, true), sum.left)),
If(coalesce(overflow.left, false) || coalesce(overflow.right, false),
true, HasOverflow(coalesce(sum.left, zero) + sum.right, d))
)
case _ =>
Seq(
coalesce(coalesce(sum.left, zero) + sum.right, sum.left),
If(coalesce(overflow.left, false) || coalesce(overflow.right, false), true, false)
)
}
}

override lazy val evaluateExpression: Expression = resultType match {
case d: DecimalType =>
If(EqualTo(overflow, true),
If(!SQLConf.get.ansiEnabled,
Literal.create(null, sumDataType),
OverflowException(resultType, "Arithmetic Operation overflow")),
sum)
case _ => sum
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,104 +61,38 @@ case class Sum(child: Expression) extends DeclarativeAggregate with ImplicitCast
private lazy val sumDataType = resultType

private lazy val sum = AttributeReference("sum", sumDataType)()
private lazy val overflow = AttributeReference("overflow", BooleanType, false)()

private lazy val zero = Literal.default(sumDataType)

override lazy val aggBufferAttributes = sum :: overflow :: Nil
override lazy val aggBufferAttributes = sum :: Nil

override lazy val initialValues: Seq[Expression] = Seq(
/* sum = */ Literal.create(null, sumDataType),
/* overflow = */ Literal.create(false, BooleanType)
/* sum = */ Literal.create(null, sumDataType)
)

override lazy val updateExpressions: Seq[Expression] = {
if (!SQLConf.get.ansiEnabled) {
if (child.nullable) {
Seq(
/* sum = */
coalesce(coalesce(sum, zero) + child.cast(sumDataType), sum),
/* overflow = */
resultType match {
case d: DecimalType =>
If(overflow, true,
HasOverflow(coalesce(sum, zero) + child.cast(sumDataType), d))
case _ => false
})
} else {
Seq(
/* sum = */
coalesce(sum, zero) + child.cast(sumDataType),
/* overflow = */
resultType match {
case d: DecimalType =>
If(overflow, true, HasOverflow(coalesce(sum, zero) + child.cast(sumDataType), d))
case _ => false
})
}
} else {
if (child.nullable) {
Seq(
/* sum = */
resultType match {
case d: DecimalType => coalesce(
CheckOverflow(
coalesce(sum, zero) + child.cast(sumDataType), d, !SQLConf.get.ansiEnabled), sum)
case _ => coalesce(coalesce(sum, zero) + child.cast(sumDataType), sum)
},
/* overflow = */
// overflow flag doesnt need any updates since CheckOverflow will throw exception
// if overflow happens
false
)
} else {
Seq(
/* sum = */
resultType match {
case d: DecimalType => CheckOverflow(
coalesce(sum, zero) + child.cast(sumDataType), d, !SQLConf.get.ansiEnabled)
case _ => coalesce(sum, zero) + child.cast(sumDataType)
},
/* overflow = */
false
)
}
}
}

override lazy val mergeExpressions: Seq[Expression] = {
if (!SQLConf.get.ansiEnabled) {
if (child.nullable) {
Seq(
/* sum = */
coalesce(coalesce(sum.left, zero) + sum.right, sum.left),
/* overflow = */
resultType match {
case d: DecimalType =>
If(coalesce(overflow.left, false) || coalesce(overflow.right, false),
true, HasOverflow(coalesce(sum.left, zero) + sum.right, d))
case _ =>
If(coalesce(overflow.left, false) || coalesce(overflow.right, false), true, false)
}
coalesce(coalesce(sum, zero) + child.cast(sumDataType), sum)
)
} else {
Seq(
/* sum = */
resultType match {
case d: DecimalType =>
coalesce(
CheckOverflow(coalesce(sum.left, zero) + sum.right, d, !SQLConf.get.ansiEnabled),
sum.left)
case _ => coalesce(coalesce(sum.left, zero) + sum.right, sum.left)
},
/* overflow = */
If(coalesce(overflow.left, false) || coalesce(overflow.right, false), true, false)
coalesce(sum, zero) + child.cast(sumDataType)
)
}
}

override lazy val mergeExpressions: Seq[Expression] = {
Seq(
/* sum = */
coalesce(coalesce(sum.left, zero) + sum.right, sum.left)
)
}

override lazy val evaluateExpression: Expression = resultType match {
case d: DecimalType =>
If(overflow && !SQLConf.get.ansiEnabled, Literal.create(null, resultType), sum)
case d: DecimalType => CheckOverflow(sum, d, !SQLConf.get.ansiEnabled)
case _ => sum
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
package org.apache.spark.sql.catalyst.expressions

import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.codegen.{CodegenContext, EmptyBlock, ExprCode}
import org.apache.spark.sql.catalyst.expressions.codegen._
import org.apache.spark.sql.catalyst.expressions.codegen.Block._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._

Expand Down Expand Up @@ -173,3 +174,23 @@ case class HasOverflow(

override def sql: String = child.sql
}

case class OverflowException(dtype: DataType, msg: String) extends LeafExpression {

override def dataType: DataType = dtype

override def nullable: Boolean = false

def eval(input: InternalRow): Any = {
Decimal.throwArithmeticException(msg)
}

override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
ev.copy(code = code"""
|${CodeGenerator.javaType(dataType)} ${ev.value} = ${CodeGenerator.defaultValue(dataType)};
|${ev.value} = Decimal.throwArithmeticException("${msg}");
|""", isNull = FalseLiteral)
}

override def toString: String = "OverflowException"
}
Original file line number Diff line number Diff line change
Expand Up @@ -1450,7 +1450,7 @@ object DecimalAggregates extends Rule[LogicalPlan] {
def apply(plan: LogicalPlan): LogicalPlan = plan transform {
case q: LogicalPlan => q transformExpressionsDown {
case we @ WindowExpression(ae @ AggregateExpression(af, _, _, _, _), _) => af match {
case Sum(e @ DecimalType.Expression(prec, scale)) if prec + 10 <= MAX_LONG_DIGITS =>
case DecimalSum(e @ DecimalType.Expression(prec, scale)) if prec + 10 <= MAX_LONG_DIGITS =>
MakeDecimal(we.copy(windowFunction = ae.copy(aggregateFunction = Sum(UnscaledValue(e)))),
prec + 10, scale)

Expand All @@ -1464,7 +1464,7 @@ object DecimalAggregates extends Rule[LogicalPlan] {
case _ => we
}
case ae @ AggregateExpression(af, _, _, _, _) => af match {
case Sum(e @ DecimalType.Expression(prec, scale)) if prec + 10 <= MAX_LONG_DIGITS =>
case DecimalSum(e @ DecimalType.Expression(prec, scale)) if prec + 10 <= MAX_LONG_DIGITS =>
MakeDecimal(ae.copy(aggregateFunction = Sum(UnscaledValue(e))), prec + 10, scale)

case Average(e @ DecimalType.Expression(prec, scale)) if prec + 4 <= MAX_DOUBLE_DIGITS =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -651,4 +651,9 @@ object Decimal {
override def quot(x: Decimal, y: Decimal): Decimal = x quot y
override def rem(x: Decimal, y: Decimal): Decimal = x % y
}


def throwArithmeticException(msg: String): Decimal = {
throw new ArithmeticException(msg)
}
}
Loading