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 @@ -937,8 +937,12 @@ object SimplifyConditionals extends Rule[LogicalPlan] with PredicateHelper {
*/
case class OptimizeCodegen(conf: CatalystConf) extends Rule[LogicalPlan] {
def apply(plan: LogicalPlan): LogicalPlan = plan transformAllExpressions {
case e @ CaseWhen(branches, _) if branches.size < conf.maxCaseBranchesForCodegen =>
e.toCodegen()
case e: CaseWhen if canCodegen(e) => e.toCodegen()
}

private def canCodegen(e: CaseWhen): Boolean = {
val numBranches = e.branches.size + e.elseValue.size
numBranches <= conf.maxCaseBranchesForCodegen
}
}

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

import org.apache.spark.sql.{QueryTest, Row, SparkSession, SQLContext}
import org.apache.spark.sql.execution.WholeStageCodegenExec
import org.apache.spark.sql.test.{SharedSQLContext, TestSQLContext}

class SQLConfSuite extends QueryTest with SharedSQLContext {
Expand Down Expand Up @@ -219,4 +220,32 @@ class SQLConfSuite extends QueryTest with SharedSQLContext {
}
}

test("MAX_CASES_BRANCHES") {
withTable("tab1") {
spark.range(10).write.saveAsTable("tab1")
val sql_one_branch_caseWhen = "SELECT CASE WHEN id = 1 THEN 1 END FROM tab1"
val sql_two_branch_caseWhen = "SELECT CASE WHEN id = 1 THEN 1 ELSE 0 END FROM tab1"

withSQLConf(SQLConf.MAX_CASES_BRANCHES.key -> "0") {
assert(!sql(sql_one_branch_caseWhen)
.queryExecution.executedPlan.isInstanceOf[WholeStageCodegenExec])
assert(!sql(sql_two_branch_caseWhen)
.queryExecution.executedPlan.isInstanceOf[WholeStageCodegenExec])
}

withSQLConf(SQLConf.MAX_CASES_BRANCHES.key -> "1") {
assert(sql(sql_one_branch_caseWhen)
.queryExecution.executedPlan.isInstanceOf[WholeStageCodegenExec])
assert(!sql(sql_two_branch_caseWhen)
.queryExecution.executedPlan.isInstanceOf[WholeStageCodegenExec])
}

withSQLConf(SQLConf.MAX_CASES_BRANCHES.key -> "2") {
assert(sql(sql_one_branch_caseWhen)
.queryExecution.executedPlan.isInstanceOf[WholeStageCodegenExec])
assert(sql(sql_two_branch_caseWhen)
.queryExecution.executedPlan.isInstanceOf[WholeStageCodegenExec])
}
}
}
}