Skip to content

[SPARK-24892] [SQL] Simplify CaseWhen to If when there is only one branch #21850

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 2 commits 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 @@ -505,6 +505,9 @@ object SimplifyConditionals extends Rule[LogicalPlan] with PredicateHelper {
} else {
e.copy(branches = branches.take(i).map(branch => (branch._1, elseValue)))
}

case CaseWhen(Seq((cond, trueValue)), elseValue) =>
Copy link
Member

Choose a reason for hiding this comment

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

Is it better we limit to BooleanType case? I.e.,

case cw @ CaseWhen(Seq((cond, trueValue)), elseValue) if cw.dataType == BooleanType =>

The reason is because mostly the further optimization comes from #29567, and it is for boolean type case only.

Or just rewrite it similarly like #29567?

case CaseWhen(Seq((cond, l @ Literal(null, _))), FalseLiteral) if !cond.nullable => ...
case CaseWhen(Seq((cond, l @ Literal(null, _))), TrueLiteral) if !cond.nullable => ...

If(cond, trueValue, elseValue.getOrElse(Literal(null, trueValue.dataType)))
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 If is faster than CaseWhen, can you explain more about "further optimization"?

Copy link
Member Author

Choose a reason for hiding this comment

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

The generated Java code is slightly simpler, but I agree there should not have any performance gain. Being said that, once CaseWhen is converted into If, this condition expression will be benefited from the optimization rules in If which may not be implemented for CaseWhen case.

Copy link
Contributor

Choose a reason for hiding this comment

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

optimization rules in If which may not be implemented for CaseWhen case.

shall we just implement more optimizer rules for CASE WHEN to cover all the cases?

Copy link
Member Author

Choose a reason for hiding this comment

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

Let's revisit this PR later, and we should always try to add CASE WHEN version for parity.

Here is the one for case when.
#21852

}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,13 +200,15 @@ class ReplaceNullWithFalseInPredicateSuite extends PlanTest {

test("inability to replace null in non-boolean values of CaseWhen") {
val nestedCaseWhen = CaseWhen(
Copy link
Member Author

Choose a reason for hiding this comment

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

Those tests are modified and one branch is added in CaseWhen to avoid new rule converting CaseWhen to If for better test coverage.

Seq((UnresolvedAttribute("i") > Literal(20)) -> Literal(2)),
Seq((UnresolvedAttribute("i") > Literal(20)) -> Literal(2),
(UnresolvedAttribute("i") > Literal(25)) -> Literal(3)),
Literal(null, IntegerType))
val branchValue = If(
Literal(2) === nestedCaseWhen,
TrueLiteral,
FalseLiteral)
val branches = Seq((UnresolvedAttribute("i") > Literal(10)) -> branchValue)
val branches = Seq((UnresolvedAttribute("i") > Literal(10)) -> branchValue,
UnresolvedAttribute("b").isNull -> TrueLiteral)
val condition = CaseWhen(branches)
testFilter(originalCond = condition, expectedCond = condition)
testJoin(originalCond = condition, expectedCond = condition)
Expand Down Expand Up @@ -304,7 +306,8 @@ class ReplaceNullWithFalseInPredicateSuite extends PlanTest {
val condition = GreaterThan(
UnresolvedAttribute("i"),
If(UnresolvedAttribute("b"), Literal(null, IntegerType), Literal(4)))
val column = CaseWhen(Seq(condition -> Literal(5)), Literal(2)).as("out")
val column = CaseWhen(Seq(condition -> Literal(5),
UnresolvedAttribute("b").isNotNull -> Literal(5)), Literal(2)).as("out")
testProjection(originalExpr = column, expectedExpr = column)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ class SimplifyConditionalSuite extends PlanTest with PredicateHelper {
}

private val trueBranch = (TrueLiteral, Literal(5))
private val normalBranch = (NonFoldableLiteral(true), Literal(10))
private val normalBranch1 = (NonFoldableLiteral(true), Literal(10))
private val normalBranch2 = (NonFoldableLiteral(false), Literal(3))
private val unreachableBranch = (FalseLiteral, Literal(20))
private val nullBranch = (Literal.create(null, BooleanType), Literal(30))

Expand Down Expand Up @@ -82,8 +83,23 @@ class SimplifyConditionalSuite extends PlanTest with PredicateHelper {
test("remove unreachable branches") {
// i.e. removing branches whose conditions are always false
assertEquivalent(
CaseWhen(unreachableBranch :: normalBranch :: unreachableBranch :: nullBranch :: Nil, None),
CaseWhen(normalBranch :: Nil, None))
CaseWhen(unreachableBranch :: normalBranch1 :: unreachableBranch ::
normalBranch2 :: nullBranch :: Nil, None),
CaseWhen(normalBranch1 :: normalBranch2 :: Nil, None))
}

test("simplify CaseWhen to If when there is only one branch") {
assertEquivalent(
CaseWhen(normalBranch1 :: Nil, Some(Literal(30))),
If(normalBranch1._1, normalBranch1._2, Literal(30)))

assertEquivalent(
CaseWhen(normalBranch1 :: Nil, None),
If(normalBranch1._1, normalBranch1._2, Literal(null, normalBranch1._2.dataType)))

assertEquivalent(
CaseWhen(unreachableBranch :: normalBranch1 :: unreachableBranch :: nullBranch :: Nil, None),
If(normalBranch1._1, normalBranch1._2, Literal(null, normalBranch1._2.dataType)))
}

test("remove entire CaseWhen if only the else branch is reachable") {
Expand All @@ -98,29 +114,29 @@ class SimplifyConditionalSuite extends PlanTest with PredicateHelper {

test("remove entire CaseWhen if the first branch is always true") {
assertEquivalent(
CaseWhen(trueBranch :: normalBranch :: nullBranch :: Nil, None),
CaseWhen(trueBranch :: normalBranch1 :: nullBranch :: Nil, None),
Literal(5))

// Test branch elimination and simplification in combination
assertEquivalent(
CaseWhen(unreachableBranch :: unreachableBranch :: nullBranch :: trueBranch :: normalBranch
CaseWhen(unreachableBranch :: unreachableBranch :: nullBranch :: trueBranch :: normalBranch1
:: Nil, None),
Literal(5))

// Make sure this doesn't trigger if there is a non-foldable branch before the true branch
assertEquivalent(
CaseWhen(normalBranch :: trueBranch :: normalBranch :: Nil, None),
CaseWhen(normalBranch :: trueBranch :: Nil, None))
CaseWhen(normalBranch1 :: trueBranch :: normalBranch1 :: Nil, None),
CaseWhen(normalBranch1 :: trueBranch :: Nil, None))
}

test("simplify CaseWhen, prune branches following a definite true") {
assertEquivalent(
CaseWhen(normalBranch :: unreachableBranch ::
CaseWhen(normalBranch1 :: unreachableBranch ::
unreachableBranch :: nullBranch ::
trueBranch :: normalBranch ::
trueBranch :: normalBranch1 ::
Nil,
None),
CaseWhen(normalBranch :: trueBranch :: Nil, None))
CaseWhen(normalBranch1 :: trueBranch :: Nil, None))
}

test("simplify CaseWhen if all the outputs are semantic equivalence") {
Expand Down
12 changes: 12 additions & 0 deletions sql/core/src/test/scala/org/apache/spark/sql/SQLQuerySuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3582,6 +3582,18 @@ class SQLQuerySuite extends QueryTest with SharedSparkSession with AdaptiveSpark
checkAnswer(sql("SELECT 0 FROM ( SELECT * FROM B JOIN C USING (id)) " +
"JOIN ( SELECT * FROM B JOIN C USING (id)) USING (id)"), Row(0))
}

test("SPARK-24892: simplify `CaseWhen` to `If` when there is only one branch") {
withTable("t") {
Seq(Some(1), null, Some(3)).toDF("a").write.saveAsTable("t")

val plan1 = sql("select case when a is null then 1 end col1 from t")
val plan2 = sql("select if(a is null, 1, null) col1 from t")

checkAnswer(plan1, Row(null) :: Row(1) :: Row(null) :: Nil)
comparePlans(plan1.queryExecution.optimizedPlan, plan2.queryExecution.optimizedPlan)
}
Copy link
Member

Choose a reason for hiding this comment

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

Thank you for adding this higher level test, too.

}
}

case class Foo(bar: Option[String])