Skip to content
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 @@ -1036,12 +1036,8 @@ object SimplifyCasts extends Rule[LogicalPlan] {

// Returns whether the from DataType can be safely casted to the to DataType without losing
// any precision or range.
private def isWiderCast(from: DataType, to: NumericType): Boolean = (from, to) match {
case (from: NumericType, to: DecimalType) if to.isWiderThan(from) => true
case (from: DecimalType, to: NumericType) if from.isTighterThan(to) => true
case (from: IntegralType, to: IntegralType) => Cast.canUpCast(from, to)
case _ => from == to

@xkrogen xkrogen Aug 3, 2022

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This refactor changes the behavior when from is non-numeric and from == to. Previously returns true, now false. Is this intentional?

To preserve behavior, and be more Scala-idiomatic by using pattern matching instead of isInstanceOf, I would suggest:

  private def isWiderCast(from: DataType, to: NumericType): Boolean = from match {
    case NumericType => Cast.canUpCast(from, to)
    case _ => from == to
  }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Previously, when from is non-numeric, from == to must be false.

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.

Do we have an existing test coverage for the case discussed in this thread?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Previously, the existing test cases does't cover the case discussed above.
So, let's add one.

}
private def isWiderCast(from: DataType, to: NumericType): Boolean =
from.isInstanceOf[NumericType] && Cast.canUpCast(from, to)
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ class SimplifyCastsSuite extends PlanTest {
Optimize.execute(
input.select($"b".cast(DecimalType(10, 2)).cast(DecimalType(24, 2)).as("casted")).analyze),
input.select($"b".cast(DecimalType(10, 2)).cast(DecimalType(24, 2)).as("casted")).analyze)
comparePlans(
Optimize.execute(
input.select($"c".cast(DecimalType(10, 2)).cast(DecimalType(24, 2)).as("casted")).analyze),
input.select($"c".cast(DecimalType(10, 2)).cast(DecimalType(24, 2)).as("casted")).analyze)

comparePlans(
Optimize.execute(
Expand Down