Apache DataFusion SQL Query Engine
ARROW-10688: [Rust] [DataFusion] Implement CASE WHEN logical plan
Andy Groveaa7ee02ddffc
diff --git a/rust/benchmarks/src/bin/tpch.rs b/rust/benchmarks/src/bin/tpch.rsindex 337eb9b159..36c4e6e2e7 100644--- a/rust/benchmarks/src/bin/tpch.rs+++ b/rust/benchmarks/src/bin/tpch.rs@@ -26,7 +26,7 @@ use arrow::util::pretty;use datafusion::datasource::parquet::ParquetTable;use datafusion::datasource::{CsvFile, MemTable, TableProvider};use datafusion::error::{DataFusionError, Result};-use datafusion::logical_plan::LogicalPlan;+use datafusion::logical_plan::{and, or, when, LogicalPlan};use datafusion::physical_plan::csv::CsvExec;use datafusion::prelude::*;@@ -222,9 +222,24 @@ fn create_logical_plan(ctx: &mut ExecutionContext, query: usize) -> Result<Logic.aggregate(vec![col("l_shipmode")],vec![- // we do not support CASE WHEN yet, so faking this part- sum(lit(1)).alias("high_line_count"),- sum(lit(0)).alias("low_line_count"),+ sum(when(+ or(+ col("o_orderpriority").eq(lit("1-URGENT")),+ col("o_orderpriority").eq(lit("2-HIGH")),+ ),+ lit(1),+ )+ .otherwise(lit(0))?)+ .alias("high_line_count"),+ sum(when(+ and(+ col("o_orderpriority").not_eq(lit("1-URGENT")),+ col("o_orderpriority").not_eq(lit("2-HIGH")),+ ),+ lit(1),+ )+ .otherwise(lit(0))?)+ .alias("low_line_count"),],)?.to_logical_plan())diff --git a/rust/datafusion/src/logical_plan/expr.rs b/rust/datafusion/src/logical_plan/expr.rsindex 8fd01ffc01..39c7ea8db9 100644--- a/rust/datafusion/src/logical_plan/expr.rs+++ b/rust/datafusion/src/logical_plan/expr.rs@@ -34,6 +34,7 @@ use crate::physical_plan::{};use crate::{physical_plan::udaf::AggregateUDF, scalar::ScalarValue};use functions::{ReturnTypeFunction, ScalarFunctionImplementation, Signature};+use std::collections::HashSet;/// `Expr` is a logical expression. A logical expression is something like `1 + 1`, or `CAST(c1 AS int)`./// Logical expressions know how to compute its [arrow::datatypes::DataType] and nullability.@@ -77,6 +78,31 @@ pub enum Expr {IsNotNull(Box<Expr>),/// Whether an expression is Null. This expression is never null.IsNull(Box<Expr>),+ /// The CASE expression is similar to a series of nested if/else and there are two forms that+ /// can be used. The first form consists of a series of boolean "when" expressions with+ /// corresponding "then" expressions, and an optional "else" expression.+ ///+ /// CASE WHEN condition THEN result+ /// [WHEN ...]+ /// [ELSE result]+ /// END+ ///+ /// The second form uses a base expression and then a series of "when" clauses that match on a+ /// literal value.+ ///+ /// CASE expression+ /// WHEN value THEN result+ /// [WHEN ...]+ /// [ELSE result]+ /// END+ Case {+ /// Optional base expression that can be compared to literal values in the "when" expressions+ expr: Option<Box<Expr>>,+ /// One or more when/then expressions+ when_then_expr: Vec<(Box<Expr>, Box<Expr>)>,+ /// Optional "else" expression+ else_expr: Option<Box<Expr>>,+ },/// Casts the expression to a given type. This expression is guaranteed to have a fixed type.Cast {/// The expression being cast@@ -141,6 +167,7 @@ impl Expr {Expr::Column(name) => Ok(schema.field_with_name(name)?.data_type().clone()),Expr::ScalarVariable(_) => Ok(DataType::Utf8),Expr::Literal(l) => Ok(l.get_datatype()),+ Expr::Case { when_then_expr, .. } => when_then_expr[0].1.get_type(schema),Expr::Cast { data_type, .. } => Ok(data_type.clone()),Expr::ScalarUDF { fun, args } => {let data_types = args@@ -202,6 +229,24 @@ impl Expr {Expr::Column(name) => Ok(input_schema.field_with_name(name)?.is_nullable()),Expr::Literal(value) => Ok(value.is_null()),Expr::ScalarVariable(_) => Ok(true),+ Expr::Case {+ when_then_expr,+ else_expr,+ ..+ } => {+ // this expression is nullable if any of the input expressions are nullable+ let then_nullable = when_then_expr+ .iter()+ .map(|(_, t)| t.nullable(input_schema))+ .collect::<Result<Vec<_>>>()?;+ if then_nullable.contains(&true) {+ Ok(true)+ } else if let Some(e) = else_expr {+ e.nullable(input_schema)+ } else {+ Ok(false)+ }+ }Expr::Cast { expr, .. } => expr.nullable(input_schema),Expr::ScalarFunction { .. } => Ok(true),Expr::ScalarUDF { .. } => Ok(true),@@ -342,6 +387,95 @@ impl Expr {}}+pub struct CaseBuilder {+ expr: Option<Box<Expr>>,+ when_expr: Vec<Expr>,+ then_expr: Vec<Expr>,+ else_expr: Option<Box<Expr>>,+}++impl CaseBuilder {+ pub fn when(&mut self, when: Expr, then: Expr) -> CaseBuilder {+ self.when_expr.push(when);+ self.then_expr.push(then);+ CaseBuilder {+ expr: self.expr.clone(),+ when_expr: self.when_expr.clone(),+ then_expr: self.then_expr.clone(),+ else_expr: self.else_expr.clone(),+ }+ }+ pub fn otherwise(&mut self, else_expr: Expr) -> Result<Expr> {+ self.else_expr = Some(Box::new(else_expr));+ self.build()+ }++ pub fn end(&self) -> Result<Expr> {+ self.build()+ }+}++impl CaseBuilder {+ fn build(&self) -> Result<Expr> {+ // collect all "then" expressions+ let mut then_expr = self.then_expr.clone();+ if let Some(e) = &self.else_expr {+ then_expr.push(e.as_ref().to_owned());+ }++ let then_types: Vec<DataType> = then_expr+ .iter()+ .map(|e| match e {+ Expr::Literal(_) => e.get_type(&Schema::empty()),+ _ => Ok(DataType::Null),+ })+ .collect::<Result<Vec<_>>>()?;++ if then_types.contains(&DataType::Null) {+ // cannot verify types until execution type+ } else {+ let unique_types: HashSet<&DataType> = then_types.iter().collect();+ if unique_types.len() != 1 {+ return Err(DataFusionError::Plan(format!(+ "CASE expression 'then' values had multiple data types: {:?}",+ unique_types+ )));+ }+ }++ Ok(Expr::Case {+ expr: self.expr.clone(),+ when_then_expr: self+ .when_expr+ .iter()+ .zip(self.then_expr.iter())+ .map(|(w, t)| (Box::new(w.clone()), Box::new(t.clone())))+ .collect(),+ else_expr: self.else_expr.clone(),+ })+ }+}++/// Create a CASE WHEN statement with literal WHEN expressions for comparison to the base expression.+pub fn case(expr: Expr) -> CaseBuilder {+ CaseBuilder {+ expr: Some(Box::new(expr)),+ when_expr: vec![],+ then_expr: vec![],+ else_expr: None,+ }+}++/// Create a CASE WHEN statement with boolean WHEN expressions and no base expression.+pub fn when(when: Expr, then: Expr) -> CaseBuilder {+ CaseBuilder {+ expr: None,+ when_expr: vec![when],+ then_expr: vec![then],+ else_expr: None,+ }+}+/// return a new expression l <op> rpub fn binary_expr(l: Expr, op: Operator, r: Expr) -> Expr {Expr::BinaryExpr {@@ -352,11 +486,20 @@ pub fn binary_expr(l: Expr, op: Operator, r: Expr) -> Expr {}/// return a new expression with a logical AND-pub fn and(left: &Expr, right: &Expr) -> Expr {+pub fn and(left: Expr, right: Expr) -> Expr {Expr::BinaryExpr {- left: Box::new(left.clone()),+ left: Box::new(left),op: Operator::And,- right: Box::new(right.clone()),+ right: Box::new(right),+ }+}++/// return a new expression with a logical OR+pub fn or(left: Expr, right: Expr) -> Expr {+ Expr::BinaryExpr {+ left: Box::new(left),+ op: Operator::Or,+ right: Box::new(right),}}@@ -568,6 +711,24 @@ impl fmt::Debug for Expr {Expr::Column(name) => write!(f, "#{}", name),Expr::ScalarVariable(var_names) => write!(f, "{}", var_names.join(".")),Expr::Literal(v) => write!(f, "{:?}", v),+ Expr::Case {+ expr,+ when_then_expr,+ else_expr,+ ..+ } => {+ write!(f, "CASE ")?;+ if let Some(e) = expr {+ write!(f, "{:?} ", e)?;+ }+ for (w, t) in when_then_expr {+ write!(f, "WHEN {:?} THEN {:?} ", w, t)?;+ }+ if let Some(e) = else_expr {+ write!(f, "ELSE {:?} ", e)?;+ }+ write!(f, "END")+ }Expr::Cast { expr, data_type } => {write!(f, "CAST({:?} AS {:?})", expr, data_type)}@@ -690,3 +851,26 @@ fn create_name(e: &Expr, input_schema: &Schema) -> Result<String> {pub fn exprlist_to_fields(expr: &[Expr], input_schema: &Schema) -> Result<Vec<Field>> {expr.iter().map(|e| e.to_field(input_schema)).collect()}++#[cfg(test)]+mod tests {+ use super::super::{col, lit, when};+ use super::*;++ #[test]+ fn case_when_same_literal_then_types() -> Result<()> {+ let _ = when(col("state").eq(lit("CO")), lit(303))+ .when(col("state").eq(lit("NY")), lit(212))+ .end()?;+ Ok(())+ }++ #[test]+ fn case_when_different_literal_then_types() -> Result<()> {+ let maybe_expr = when(col("state").eq(lit("CO")), lit(303))+ .when(col("state").eq(lit("NY")), lit("212"))+ .end();+ assert!(maybe_expr.is_err());+ Ok(())+ }+}diff --git a/rust/datafusion/src/logical_plan/mod.rs b/rust/datafusion/src/logical_plan/mod.rsindex a3a44d5341..ea8df14835 100644--- a/rust/datafusion/src/logical_plan/mod.rs+++ b/rust/datafusion/src/logical_plan/mod.rs@@ -32,9 +32,10 @@ mod registry;pub use builder::LogicalPlanBuilder;pub use display::display_schema;pub use expr::{- abs, acos, and, array, asin, atan, avg, binary_expr, ceil, col, concat, cos, count,- create_udaf, create_udf, exp, exprlist_to_fields, floor, length, lit, ln, log10,- log2, max, min, round, signum, sin, sqrt, sum, tan, trunc, Expr, Literal,+ abs, acos, and, array, asin, atan, avg, binary_expr, case, ceil, col, concat, cos,+ count, create_udaf, create_udf, exp, exprlist_to_fields, floor, length, lit, ln,+ log10, log2, max, min, or, round, signum, sin, sqrt, sum, tan, trunc, when, Expr,+ Literal,};pub use extension::UserDefinedLogicalNode;pub use operators::Operator;diff --git a/rust/datafusion/src/optimizer/filter_push_down.rs b/rust/datafusion/src/optimizer/filter_push_down.rsindex 37573e6547..f1b7fc31ea 100644--- a/rust/datafusion/src/optimizer/filter_push_down.rs+++ b/rust/datafusion/src/optimizer/filter_push_down.rs@@ -93,7 +93,9 @@ fn issue_filters(let predicate = predicates.iter().skip(1)- .fold(predicates[0].clone(), |acc, predicate| and(&acc, predicate));+ .fold(predicates[0].clone(), |acc, predicate| {+ and(acc, (*predicate).to_owned())+ });// add a new filter node with the predicateslet plan = LogicalPlan::Filter {diff --git a/rust/datafusion/src/optimizer/projection_push_down.rs b/rust/datafusion/src/optimizer/projection_push_down.rsindex aabdbda829..e06a605e55 100644--- a/rust/datafusion/src/optimizer/projection_push_down.rs+++ b/rust/datafusion/src/optimizer/projection_push_down.rs@@ -113,6 +113,7 @@ fn optimize_plan(required_columns: &HashSet<String>, // set of columns required up to this stephas_projection: bool,) -> Result<LogicalPlan> {+ let mut new_required_columns = required_columns.clone();match plan {LogicalPlan::Projection {input,@@ -125,7 +126,6 @@ fn optimize_plan(let mut new_expr = Vec::new();let mut new_fields = Vec::new();- let mut new_required_columns = HashSet::new();// Gather all columns needed for expressions in this Projectionschema@@ -165,7 +165,6 @@ fn optimize_plan(join_type,schema,} => {- let mut new_required_columns = HashSet::new();for (l, r) in on {new_required_columns.insert(l.to_owned());new_required_columns.insert(r.to_owned());@@ -200,7 +199,6 @@ fn optimize_plan(// * remove any aggregate expression that is not required// * construct the new set of required columns- let mut new_required_columns = HashSet::new();utils::exprlist_to_column_names(group_expr, &mut new_required_columns)?;// Gather all columns needed for expressions in this Aggregate@@ -347,7 +345,6 @@ fn optimize_plan(| LogicalPlan::Extension { .. } => {let expr = utils::expressions(plan);// collect all required columns by this plan- let mut new_required_columns = required_columns.clone();utils::exprlist_to_column_names(&expr, &mut new_required_columns)?;// apply the optimization to all inputs of the plandiff --git a/rust/datafusion/src/optimizer/utils.rs b/rust/datafusion/src/optimizer/utils.rsindex 43222c9881..c50c59d363 100644--- a/rust/datafusion/src/optimizer/utils.rs+++ b/rust/datafusion/src/optimizer/utils.rs@@ -24,7 +24,11 @@ use arrow::datatypes::{Schema, SchemaRef};use super::optimizer::OptimizerRule;use crate::error::{DataFusionError, Result};use crate::logical_plan::{Expr, LogicalPlan, PlanType, StringifiedPlan};-use crate::prelude::col;+use crate::prelude::{col, lit};+use crate::scalar::ScalarValue;++const CASE_EXPR_MARKER: &str = "__DATAFUSION_CASE_EXPR__";+const CASE_ELSE_MARKER: &str = "__DATAFUSION_CASE_ELSE__";/// Recursively walk a list of expression trees, collecting the unique set of column/// names referenced in the expression@@ -63,6 +67,24 @@ pub fn expr_to_column_names(expr: &Expr, accum: &mut HashSet<String>) -> Result<expr_to_column_names(right, accum)?;Ok(())}+ Expr::Case {+ expr,+ when_then_expr,+ else_expr,+ ..+ } => {+ if let Some(e) = expr {+ expr_to_column_names(e, accum)?;+ }+ for (w, t) in when_then_expr {+ expr_to_column_names(w, accum)?;+ expr_to_column_names(t, accum)?;+ }+ if let Some(e) = else_expr {+ expr_to_column_names(e, accum)?+ }+ Ok(())+ }Expr::Cast { expr, .. } => expr_to_column_names(expr, accum),Expr::Sort { expr, .. } => expr_to_column_names(expr, accum),Expr::AggregateFunction { args, .. } => exprlist_to_column_names(args, accum),@@ -216,26 +238,51 @@ pub fn from_plan(/// Returns all direct children `Expression`s of `expr`./// E.g. if the expression is "(a + 1) + 1", it returns ["a + 1", "1"] (as Expr objects)-pub fn expr_sub_expressions(expr: &Expr) -> Result<Vec<&Expr>> {+pub fn expr_sub_expressions(expr: &Expr) -> Result<Vec<Expr>> {match expr {- Expr::BinaryExpr { left, right, .. } => Ok(vec![left, right]),- Expr::IsNull(e) => Ok(vec![e]),- Expr::IsNotNull(e) => Ok(vec![e]),- Expr::ScalarFunction { args, .. } => Ok(args.iter().collect()),- Expr::ScalarUDF { args, .. } => Ok(args.iter().collect()),- Expr::AggregateFunction { args, .. } => Ok(args.iter().collect()),- Expr::AggregateUDF { args, .. } => Ok(args.iter().collect()),- Expr::Cast { expr, .. } => Ok(vec![expr]),+ Expr::BinaryExpr { left, right, .. } => {+ Ok(vec![left.as_ref().to_owned(), right.as_ref().to_owned()])+ }+ Expr::IsNull(e) => Ok(vec![e.as_ref().to_owned()]),+ Expr::IsNotNull(e) => Ok(vec![e.as_ref().to_owned()]),+ Expr::ScalarFunction { args, .. } => Ok(args.iter().map(|e| e.clone()).collect()),+ Expr::ScalarUDF { args, .. } => Ok(args.iter().map(|e| e.clone()).collect()),+ Expr::AggregateFunction { args, .. } => {+ Ok(args.iter().map(|e| e.clone()).collect())+ }+ Expr::AggregateUDF { args, .. } => Ok(args.iter().map(|e| e.clone()).collect()),+ Expr::Case {+ expr,+ when_then_expr,+ else_expr,+ ..+ } => {+ let mut expr_list: Vec<Expr> = vec![];+ if let Some(e) = expr {+ expr_list.push(lit(CASE_EXPR_MARKER));+ expr_list.push(e.as_ref().to_owned());+ }+ for (w, t) in when_then_expr {+ expr_list.push(w.as_ref().to_owned());+ expr_list.push(t.as_ref().to_owned());+ }+ if let Some(e) = else_expr {+ expr_list.push(lit(CASE_ELSE_MARKER));+ expr_list.push(e.as_ref().to_owned());+ }+ Ok(expr_list)+ }+ Expr::Cast { expr, .. } => Ok(vec![expr.as_ref().to_owned()]),Expr::Column(_) => Ok(vec![]),- Expr::Alias(expr, ..) => Ok(vec![expr]),+ Expr::Alias(expr, ..) => Ok(vec![expr.as_ref().to_owned()]),Expr::Literal(_) => Ok(vec![]),Expr::ScalarVariable(_) => Ok(vec![]),- Expr::Not(expr) => Ok(vec![expr]),- Expr::Sort { expr, .. } => Ok(vec![expr]),+ Expr::Not(expr) => Ok(vec![expr.as_ref().to_owned()]),+ Expr::Sort { expr, .. } => Ok(vec![expr.as_ref().to_owned()]),Expr::Wildcard { .. } => Err(DataFusionError::Internal("Wildcard expressions are not valid in a logical query plan".to_owned(),)),- Expr::Nested(expr) => Ok(vec![expr]),+ Expr::Nested(expr) => Ok(vec![expr.as_ref().to_owned()]),}}@@ -267,6 +314,42 @@ pub fn rewrite_expression(expr: &Expr, expressions: &Vec<Expr>) -> Result<Expr>fun: fun.clone(),args: expressions.clone(),}),+ Expr::Case { .. } => {+ let mut base_expr: Option<Box<Expr>> = None;+ let mut when_then: Vec<(Box<Expr>, Box<Expr>)> = vec![];+ let mut else_expr: Option<Box<Expr>> = None;+ let mut i = 0;++ while i < expressions.len() {+ match &expressions[i] {+ Expr::Literal(ScalarValue::Utf8(Some(str)))+ if str == CASE_EXPR_MARKER =>+ {+ base_expr = Some(Box::new(expressions[i + 1].clone()));+ i += 2;+ }+ Expr::Literal(ScalarValue::Utf8(Some(str)))+ if str == CASE_ELSE_MARKER =>+ {+ else_expr = Some(Box::new(expressions[i + 1].clone()));+ i += 2;+ }+ _ => {+ when_then.push((+ Box::new(expressions[i].clone()),+ Box::new(expressions[i + 1].clone()),+ ));+ i += 2;+ }+ }+ }++ Ok(Expr::Case {+ expr: base_expr,+ when_then_expr: when_then,+ else_expr,+ })+ }Expr::Cast { data_type, .. } => Ok(Expr::Cast {expr: Box::new(expressions[0].clone()),data_type: data_type.clone(),diff --git a/rust/datafusion/src/physical_plan/expressions.rs b/rust/datafusion/src/physical_plan/expressions.rsindex 4247cf0a75..f642da7ab5 100644--- a/rust/datafusion/src/physical_plan/expressions.rs+++ b/rust/datafusion/src/physical_plan/expressions.rs@@ -1718,7 +1718,7 @@ pub fn is_not_null(arg: Arc<dyn PhysicalExpr>) -> Result<Arc<dyn PhysicalExpr>>/// [ELSE result]/// END#[derive(Debug)]-struct CaseExpr {+pub struct CaseExpr {/// Optional base expression that can be compared to literal values in the "when" expressionsexpr: Option<Arc<dyn PhysicalExpr>>,/// One or more when/then expressions@@ -1744,6 +1744,7 @@ impl fmt::Display for CaseExpr {}impl CaseExpr {+ /// Create a new CASE WHEN expressionpub fn try_new(expr: Option<Arc<dyn PhysicalExpr>>,when_then_expr: &[(Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>)],diff --git a/rust/datafusion/src/physical_plan/planner.rs b/rust/datafusion/src/physical_plan/planner.rsindex 036da6624e..f329971a47 100644--- a/rust/datafusion/src/physical_plan/planner.rs+++ b/rust/datafusion/src/physical_plan/planner.rs@@ -27,7 +27,7 @@ use crate::logical_plan::{};use crate::physical_plan::csv::{CsvExec, CsvReadOptions};use crate::physical_plan::explain::ExplainExec;-use crate::physical_plan::expressions::{Column, Literal, PhysicalSortExpr};+use crate::physical_plan::expressions::{CaseExpr, Column, Literal, PhysicalSortExpr};use crate::physical_plan::filter::FilterExec;use crate::physical_plan::hash_aggregate::{AggregateMode, HashAggregateExec};use crate::physical_plan::hash_join::HashJoinExec;@@ -444,6 +444,55 @@ impl DefaultPhysicalPlanner {let rhs = self.create_physical_expr(right, input_schema, ctx_state)?;binary(lhs, op.clone(), rhs, input_schema)}+ Expr::Case {+ expr,+ when_then_expr,+ else_expr,+ ..+ } => {+ let expr: Option<Arc<dyn PhysicalExpr>> = if let Some(e) = expr {+ Some(self.create_physical_expr(+ e.as_ref(),+ input_schema,+ ctx_state,+ )?)+ } else {+ None+ };+ let when_expr = when_then_expr+ .iter()+ .map(|(w, _)| {+ self.create_physical_expr(w.as_ref(), input_schema, ctx_state)+ })+ .collect::<Result<Vec<_>>>()?;+ let then_expr = when_then_expr+ .iter()+ .map(|(_, t)| {+ self.create_physical_expr(t.as_ref(), input_schema, ctx_state)+ })+ .collect::<Result<Vec<_>>>()?;+ let when_then_expr: Vec<(Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>)> =+ when_expr+ .iter()+ .zip(then_expr.iter())+ .map(|(w, t)| (w.clone(), t.clone()))+ .collect();+ let else_expr: Option<Arc<dyn PhysicalExpr>> = if let Some(e) = else_expr+ {+ Some(self.create_physical_expr(+ e.as_ref(),+ input_schema,+ ctx_state,+ )?)+ } else {+ None+ };+ Ok(Arc::new(CaseExpr::try_new(+ expr,+ &when_then_expr,+ else_expr,+ )?))+ }Expr::Cast { expr, data_type } => expressions::cast(self.create_physical_expr(expr, input_schema, ctx_state)?,input_schema,