Apache DataFusion SQL Query Engine
Refactor Expr::BinaryExpr to use a struct (#3835)
Dongyan Zhoud2d8447ed23b
diff --git a/benchmarks/src/bin/tpch.rs b/benchmarks/src/bin/tpch.rsindex d1aa2c8eba..d06487935c 100644--- a/benchmarks/src/bin/tpch.rs+++ b/benchmarks/src/bin/tpch.rs@@ -1248,7 +1248,7 @@ mod tests {.iter().map(|field| {match Field::data_type(field) {- DataType::Decimal128(_,_) => {+ DataType::Decimal128(_, _) => {// if decimal, then round it to 2 decimal places like the answers// round() doesn't support the second argument for decimal places to round to// this can be simplified to remove the mul and div when@@ -1256,12 +1256,12 @@ mod tests {// cast it back to an over-sized Decimal with 2 precision when done roundinglet round = Box::new(ScalarFunction {fun: datafusion::logical_expr::BuiltinScalarFunction::Round,- args: vec![col(Field::name(field)).mul(lit(100))]+ args: vec![col(Field::name(field)).mul(lit(100))],}.div(lit(100)));Expr::Alias(Box::new(Cast {expr: round,- data_type: DataType::Decimal128(38,2),+ data_type: DataType::Decimal128(38, 2),}),Field::name(field).to_string(),)@@ -1270,7 +1270,7 @@ mod tests {// if string, then trim it like the answers got trimmedExpr::Alias(Box::new(trim(col(Field::name(field)))),- Field::name(field).to_string()+ Field::name(field).to_string(),)}_ => {diff --git a/datafusion-examples/examples/expr_api.rs b/datafusion-examples/examples/expr_api.rsindex 5392e20f26..61228946fd 100644--- a/datafusion-examples/examples/expr_api.rs+++ b/datafusion-examples/examples/expr_api.rs@@ -21,6 +21,7 @@ use datafusion::optimizer::expr_simplifier::{ExprSimplifier, SimplifyContext};use datafusion::physical_expr::execution_props::ExecutionProps;use datafusion::prelude::*;use datafusion_common::{ScalarValue, ToDFSchema};+use datafusion_expr::expr::BinaryExpr;use datafusion_expr::Operator;/// This example demonstrates the DataFusion [`Expr`] API.@@ -28,7 +29,6 @@ use datafusion_expr::Operator;/// DataFusion comes with a powerful and extensive system for/// representing and manipulating expressions such as `A + 5` and `X/// IN ('foo', 'bar', 'baz')` and many other constructs.-#[tokio::main]async fn main() -> Result<()> {// The easiest way to do create expressions is to use the@@ -37,11 +37,11 @@ async fn main() -> Result<()> {// this creates the same expression as the following though with// much less code,- let expr2 = Expr::BinaryExpr {- left: Box::new(col("a")),- op: Operator::Plus,- right: Box::new(Expr::Literal(ScalarValue::Int32(Some(5)))),- };+ let expr2 = Expr::BinaryExpr(BinaryExpr::new(+ Box::new(col("a")),+ Operator::Plus,+ Box::new(Expr::Literal(ScalarValue::Int32(Some(5)))),+ ));assert_eq!(expr, expr2);simplify_demo()?;diff --git a/datafusion/core/src/physical_optimizer/pruning.rs b/datafusion/core/src/physical_optimizer/pruning.rsindex 18ea532ea8..0b309412c0 100644--- a/datafusion/core/src/physical_optimizer/pruning.rs+++ b/datafusion/core/src/physical_optimizer/pruning.rs@@ -46,6 +46,7 @@ use arrow::{record_batch::RecordBatch,};use datafusion_common::{downcast_value, ScalarValue};+use datafusion_expr::expr::BinaryExpr;use datafusion_expr::expr_rewriter::{ExprRewritable, ExprRewriter};use datafusion_expr::utils::expr_to_columns;use datafusion_expr::{binary_expr, cast, try_cast, ExprSchemable};@@ -733,7 +734,7 @@ fn build_predicate_expression(// predicate expression can only be a binary expressionlet (left, op, right) = match expr {- Expr::BinaryExpr { left, op, right } => (left, *op, right),+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => (left, *op, right),Expr::IsNull(expr) => {let expr = build_is_null_column_expr(expr, schema, required_columns).unwrap_or(unhandled);diff --git a/datafusion/core/src/physical_plan/planner.rs b/datafusion/core/src/physical_plan/planner.rsindex c3d28a7a82..2dc1b29ca2 100644--- a/datafusion/core/src/physical_plan/planner.rs+++ b/datafusion/core/src/physical_plan/planner.rs@@ -59,7 +59,7 @@ use arrow::compute::SortOptions;use arrow::datatypes::{Schema, SchemaRef};use async_trait::async_trait;use datafusion_common::{DFSchema, ScalarValue};-use datafusion_expr::expr::{Between, GroupingSet, Like};+use datafusion_expr::expr::{Between, BinaryExpr, GroupingSet, Like};use datafusion_expr::expr_rewriter::unnormalize_cols;use datafusion_expr::utils::{expand_wildcard, expr_to_columns};use datafusion_expr::WindowFrameUnits;@@ -107,7 +107,7 @@ fn create_physical_name(e: &Expr, is_first_expr: bool) -> Result<String> {Expr::Alias(_, name) => Ok(name.clone()),Expr::ScalarVariable(_, variable_names) => Ok(variable_names.join(".")),Expr::Literal(value) => Ok(format!("{:?}", value)),- Expr::BinaryExpr { left, op, right } => {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => {let left = create_physical_name(left, false)?;let right = create_physical_name(right, false)?;Ok(format!("{} {} {}", left, op, right))diff --git a/datafusion/core/tests/provider_filter_pushdown.rs b/datafusion/core/tests/provider_filter_pushdown.rsindex 117b4eb143..672f7ee1a3 100644--- a/datafusion/core/tests/provider_filter_pushdown.rs+++ b/datafusion/core/tests/provider_filter_pushdown.rs@@ -32,6 +32,7 @@ use datafusion::physical_plan::{use datafusion::prelude::*;use datafusion::scalar::ScalarValue;use datafusion_common::DataFusionError;+use datafusion_expr::expr::BinaryExpr;use std::ops::Deref;use std::sync::Arc;@@ -146,7 +147,7 @@ impl TableProvider for CustomProvider {_: Option<usize>,) -> Result<Arc<dyn ExecutionPlan>> {match &filters[0] {- Expr::BinaryExpr { right, .. } => {+ Expr::BinaryExpr(BinaryExpr { right, .. }) => {let int_value = match &**right {Expr::Literal(ScalarValue::Int8(Some(i))) => *i as i64,Expr::Literal(ScalarValue::Int16(Some(i))) => *i as i64,diff --git a/datafusion/expr/src/expr.rs b/datafusion/expr/src/expr.rsindex 82ccbce499..7186ecd3b0 100644--- a/datafusion/expr/src/expr.rs+++ b/datafusion/expr/src/expr.rs@@ -60,10 +60,10 @@ use std::sync::Arc;/// let expr = col("c1") + col("c2");////// assert!(matches!(expr, Expr::BinaryExpr { ..} ));-/// if let Expr::BinaryExpr { left, right, op } = expr {-/// assert_eq!(*left, col("c1"));-/// assert_eq!(*right, col("c2"));-/// assert_eq!(op, Operator::Plus);+/// if let Expr::BinaryExpr(binary_expr) = expr {+/// assert_eq!(*binary_expr.left, col("c1"));+/// assert_eq!(*binary_expr.right, col("c2"));+/// assert_eq!(binary_expr.op, Operator::Plus);/// }/// ```///@@ -74,11 +74,11 @@ use std::sync::Arc;/// let expr = col("c1").eq(lit(42_i32));////// assert!(matches!(expr, Expr::BinaryExpr { .. } ));-/// if let Expr::BinaryExpr { left, right, op } = expr {-/// assert_eq!(*left, col("c1"));+/// if let Expr::BinaryExpr(binary_expr) = expr {+/// assert_eq!(*binary_expr.left, col("c1"));/// let scalar = ScalarValue::Int32(Some(42));-/// assert_eq!(*right, Expr::Literal(scalar));-/// assert_eq!(op, Operator::Eq);+/// assert_eq!(*binary_expr.right, Expr::Literal(scalar));+/// assert_eq!(binary_expr.op, Operator::Eq);/// }/// ```#[derive(Clone, PartialEq, Eq, Hash)]@@ -92,14 +92,7 @@ pub enum Expr {/// A constant value.Literal(ScalarValue),/// A binary expression such as "age > 21"- BinaryExpr {- /// Left-hand side of the expression- left: Box<Expr>,- /// The comparison operator- op: Operator,- /// Right-hand side of the expression- right: Box<Expr>,- },+ BinaryExpr(BinaryExpr),/// LIKE expressionLike(Like),/// Case-insensitive LIKE expression@@ -261,6 +254,24 @@ pub enum Expr {GroupingSet(GroupingSet),}+/// Binary expression+#[derive(Clone, PartialEq, Eq, Hash)]+pub struct BinaryExpr {+ /// Left-hand side of the expression+ pub left: Box<Expr>,+ /// The comparison operator+ pub op: Operator,+ /// Right-hand side of the expression+ pub right: Box<Expr>,+}++impl BinaryExpr {+ /// Create a new binary expression+ pub fn new(left: Box<Expr>, op: Operator, right: Box<Expr>) -> Self {+ Self { left, op, right }+ }+}+/// CASE expression#[derive(Clone, PartialEq, Eq, Hash)]pub struct Case {@@ -695,7 +706,7 @@ impl fmt::Debug for Expr {negated: false,} => write!(f, "{:?} IN ({:?})", expr, subquery),Expr::ScalarSubquery(subquery) => write!(f, "({:?})", subquery),- Expr::BinaryExpr { left, op, right } => {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => {write!(f, "{:?} {} {:?}", left, op, right)}Expr::Sort {@@ -932,10 +943,10 @@ fn create_name(e: &Expr) -> Result<String> {Expr::Column(c) => Ok(c.flat_name()),Expr::ScalarVariable(_, variable_names) => Ok(variable_names.join(".")),Expr::Literal(value) => Ok(format!("{:?}", value)),- Expr::BinaryExpr { left, op, right } => {- let left = create_name(left)?;- let right = create_name(right)?;- Ok(format!("{} {} {}", left, op, right))+ Expr::BinaryExpr(binary_expr) => {+ let left = create_name(binary_expr.left.as_ref())?;+ let right = create_name(binary_expr.right.as_ref())?;+ Ok(format!("{} {} {}", left, binary_expr.op, right))}Expr::Like(Like {negated,diff --git a/datafusion/expr/src/expr_fn.rs b/datafusion/expr/src/expr_fn.rsindex 5ab519dce9..ba5351a850 100644--- a/datafusion/expr/src/expr_fn.rs+++ b/datafusion/expr/src/expr_fn.rs@@ -17,7 +17,7 @@//! Functions for creating logical expressions-use crate::expr::GroupingSet;+use crate::expr::{BinaryExpr, GroupingSet};use crate::{aggregate_function, built_in_function, conditional_expressions::CaseBuilder, lit,logical_plan::Subquery, AccumulatorFunctionImplementation, AggregateUDF,@@ -33,31 +33,27 @@ pub fn col(ident: &str) -> Expr {Expr::Column(ident.into())}-/// Return a new expression l <op> r-pub fn binary_expr(l: Expr, op: Operator, r: Expr) -> Expr {- Expr::BinaryExpr {- left: Box::new(l),- op,- right: Box::new(r),- }+/// Return a new expression left <op> right+pub fn binary_expr(left: Expr, op: Operator, right: Expr) -> Expr {+ Expr::BinaryExpr(BinaryExpr::new(Box::new(left), op, Box::new(right)))}/// Return a new expression with a logical ANDpub fn and(left: Expr, right: Expr) -> Expr {- Expr::BinaryExpr {- left: Box::new(left),- op: Operator::And,- right: Box::new(right),- }+ Expr::BinaryExpr(BinaryExpr::new(+ Box::new(left),+ Operator::And,+ Box::new(right),+ ))}/// Return a new expression with a logical ORpub fn or(left: Expr, right: Expr) -> Expr {- Expr::BinaryExpr {- left: Box::new(left),- op: Operator::Or,- right: Box::new(right),- }+ Expr::BinaryExpr(BinaryExpr::new(+ Box::new(left),+ Operator::Or,+ Box::new(right),+ ))}/// Create an expression to represent the min() aggregate functiondiff --git a/datafusion/expr/src/expr_rewriter.rs b/datafusion/expr/src/expr_rewriter.rsindex 9cfb126c03..d4cfc80676 100644--- a/datafusion/expr/src/expr_rewriter.rs+++ b/datafusion/expr/src/expr_rewriter.rs@@ -17,7 +17,7 @@//! Expression rewriter-use crate::expr::{Between, Case, GroupingSet, Like};+use crate::expr::{Between, BinaryExpr, Case, GroupingSet, Like};use crate::logical_plan::{Aggregate, Projection};use crate::utils::{from_plan, grouping_set_to_exprlist};use crate::{Expr, ExprSchemable, LogicalPlan};@@ -123,11 +123,13 @@ impl ExprRewritable for Expr {Expr::ScalarSubquery(_) => self.clone(),Expr::ScalarVariable(ty, names) => Expr::ScalarVariable(ty, names),Expr::Literal(value) => Expr::Literal(value),- Expr::BinaryExpr { left, op, right } => Expr::BinaryExpr {- left: rewrite_boxed(left, rewriter)?,- op,- right: rewrite_boxed(right, rewriter)?,- },+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => {+ Expr::BinaryExpr(BinaryExpr::new(+ rewrite_boxed(left, rewriter)?,+ op,+ rewrite_boxed(right, rewriter)?,+ ))+ }Expr::Like(Like {negated,expr,diff --git a/datafusion/expr/src/expr_schema.rs b/datafusion/expr/src/expr_schema.rsindex 01cb015963..6c70eac5b1 100644--- a/datafusion/expr/src/expr_schema.rs+++ b/datafusion/expr/src/expr_schema.rs@@ -16,6 +16,7 @@// under the License.use super::{Between, Expr, Like};+use crate::expr::BinaryExpr;use crate::field_util::get_indexed_field;use crate::type_coercion::binary::binary_operator_data_type;use crate::{aggregate_function, function, window_function};@@ -114,11 +115,11 @@ impl ExprSchemable for Expr {Expr::ScalarSubquery(subquery) => {Ok(subquery.subquery.schema().field(0).data_type().clone())}- Expr::BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {ref left,ref right,ref op,- } => binary_operator_data_type(+ }) => binary_operator_data_type(&left.get_type(schema)?,op,&right.get_type(schema)?,@@ -202,11 +203,11 @@ impl ExprSchemable for Expr {Expr::ScalarSubquery(subquery) => {Ok(subquery.subquery.schema().field(0).is_nullable())}- Expr::BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {ref left,ref right,..- } => Ok(left.nullable(input_schema)? || right.nullable(input_schema)?),+ }) => Ok(left.nullable(input_schema)? || right.nullable(input_schema)?),Expr::Like(Like { expr, .. }) => expr.nullable(input_schema),Expr::ILike(Like { expr, .. }) => expr.nullable(input_schema),Expr::SimilarTo(Like { expr, .. }) => expr.nullable(input_schema),diff --git a/datafusion/expr/src/expr_visitor.rs b/datafusion/expr/src/expr_visitor.rsindex 57457cee58..b78ed89db7 100644--- a/datafusion/expr/src/expr_visitor.rs+++ b/datafusion/expr/src/expr_visitor.rs@@ -17,7 +17,10 @@//! Expression visitor-use crate::{expr::GroupingSet, Between, Expr, Like};+use crate::{+ expr::{BinaryExpr, GroupingSet},+ Between, Expr, Like,+};use datafusion_common::Result;/// Controls how the visitor recursion should proceed.@@ -130,7 +133,7 @@ impl ExprVisitable for Expr {| Expr::ScalarSubquery(_)| Expr::Wildcard| Expr::QualifiedWildcard { .. } => Ok(visitor),- Expr::BinaryExpr { left, right, .. } => {+ Expr::BinaryExpr(BinaryExpr { left, right, .. }) => {let visitor = left.accept(visitor)?;right.accept(visitor)}diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rsindex b21076a9d8..cb3f7f97df 100644--- a/datafusion/expr/src/logical_plan/plan.rs+++ b/datafusion/expr/src/logical_plan/plan.rs@@ -15,6 +15,7 @@// specific language governing permissions and limitations// under the License.+use crate::expr::BinaryExpr;///! Logical plan typesuse crate::logical_plan::builder::validate_unique_names;use crate::logical_plan::display::{GraphvizVisitor, IndentVisitor};@@ -499,7 +500,7 @@ impl LogicalPlan {fn collect_subqueries(&self, expr: &Expr, sub: &mut Vec<Arc<LogicalPlan>>) {match expr {- Expr::BinaryExpr { left, right, .. } => {+ Expr::BinaryExpr(BinaryExpr { left, right, .. }) => {self.collect_subqueries(left, sub);self.collect_subqueries(right, sub);}diff --git a/datafusion/jit/src/ast.rs b/datafusion/jit/src/ast.rsindex 55731a6505..5774cee11d 100644--- a/datafusion/jit/src/ast.rs+++ b/datafusion/jit/src/ast.rs@@ -152,7 +152,11 @@ impl TryFrom<(datafusion_expr::Expr, DFSchemaRef)> for Expr {(value, schema): (datafusion_expr::Expr, DFSchemaRef),) -> Result<Self, Self::Error> {match &value {- datafusion_expr::Expr::BinaryExpr { left, op, right } => {+ datafusion_expr::Expr::BinaryExpr(datafusion_expr::expr::BinaryExpr {+ left,+ op,+ right,+ }) => {let op = match op {datafusion_expr::Operator::Eq => BinaryExpr::Eq,datafusion_expr::Operator::NotEq => BinaryExpr::Ne,diff --git a/datafusion/optimizer/src/filter_push_down.rs b/datafusion/optimizer/src/filter_push_down.rsindex 08ba71cda0..6396f1fbfd 100644--- a/datafusion/optimizer/src/filter_push_down.rs+++ b/datafusion/optimizer/src/filter_push_down.rs@@ -18,6 +18,7 @@ use crate::{utils, OptimizerConfig, OptimizerRule};use datafusion_common::{Column, DFSchema, DataFusionError, Result};use datafusion_expr::{and, col,+ expr::BinaryExpr,expr_rewriter::{replace_col, ExprRewritable, ExprRewriter},logical_plan::{Aggregate, CrossJoin, Join, JoinType, Limit, LogicalPlan, Projection, TableScan,@@ -305,11 +306,11 @@ fn extract_or_clauses_for_join(let mut exprs = vec![];let mut expr_columns = vec![];for expr in filters.iter() {- if let Expr::BinaryExpr {+ if let Expr::BinaryExpr(BinaryExpr {left,op: Operator::Or,right,- } = expr+ }) = expr{let left_expr = extract_or_clause(left.as_ref(), &schema_columns);let right_expr = extract_or_clause(right.as_ref(), &schema_columns);@@ -345,11 +346,11 @@ fn extract_or_clause(expr: &Expr, schema_columns: &HashSet<Column>) -> Option<Exlet mut predicate = None;match expr {- Expr::BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left: l_expr,op: Operator::Or,right: r_expr,- } => {+ }) => {let l_expr = extract_or_clause(l_expr, schema_columns);let r_expr = extract_or_clause(r_expr, schema_columns);@@ -357,11 +358,11 @@ fn extract_or_clause(expr: &Expr, schema_columns: &HashSet<Column>) -> Option<Expredicate = Some(or(l_expr, r_expr));}}- Expr::BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left: l_expr,op: Operator::And,right: r_expr,- } => {+ }) => {let l_expr = extract_or_clause(l_expr, schema_columns);let r_expr = extract_or_clause(r_expr, schema_columns);@@ -970,19 +971,19 @@ mod tests {}fn add(left: Expr, right: Expr) -> Expr {- Expr::BinaryExpr {- left: Box::new(left),- op: Operator::Plus,- right: Box::new(right),- }+ Expr::BinaryExpr(BinaryExpr::new(+ Box::new(left),+ Operator::Plus,+ Box::new(right),+ ))}fn multiply(left: Expr, right: Expr) -> Expr {- Expr::BinaryExpr {- left: Box::new(left),- op: Operator::Multiply,- right: Box::new(right),- }+ Expr::BinaryExpr(BinaryExpr::new(+ Box::new(left),+ Operator::Multiply,+ Box::new(right),+ ))}/// verifies that a filter is pushed to before a projection with a complex expression, the filter expression is correctly re-writtendiff --git a/datafusion/optimizer/src/reduce_cross_join.rs b/datafusion/optimizer/src/reduce_cross_join.rsindex e8c2ff9ecd..fa7c18afd3 100644--- a/datafusion/optimizer/src/reduce_cross_join.rs+++ b/datafusion/optimizer/src/reduce_cross_join.rs@@ -20,6 +20,7 @@ use crate::{OptimizerConfig, OptimizerRule};use datafusion_common::{Column, Result};use datafusion_expr::{and,+ expr::BinaryExpr,logical_plan::{CrossJoin, Filter, Join, JoinType, LogicalPlan},or,utils::can_hash,@@ -198,7 +199,7 @@ fn intersect(/// Extract join keys from a WHERE clausefn extract_possible_join_keys(expr: &Expr, accum: &mut Vec<(Column, Column)>) {- if let Expr::BinaryExpr { left, op, right } = expr {+ if let Expr::BinaryExpr(BinaryExpr { left, op, right }) = expr {match op {Operator::Eq => {if let (Expr::Column(l), Expr::Column(r)) =@@ -239,7 +240,7 @@ fn remove_join_expressions(join_columns: &HashSet<(Column, Column)>,) -> Result<Option<Expr>> {match expr {- Expr::BinaryExpr { left, op, right } => match op {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => match op {Operator::Eq => match (left.as_ref(), right.as_ref()) {(Expr::Column(l), Expr::Column(r)) => {if join_columns.contains(&(l.clone(), r.clone()))@@ -321,7 +322,7 @@ mod tests {))?.build()?;- let expected =vec![+ let expected = vec!["Filter: t2.c < UInt32(20) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]",@@ -349,7 +350,7 @@ mod tests {))?.build()?;- let expected =vec![+ let expected = vec!["Filter: t1.a = t2.a OR t2.b = t1.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," CrossJoin: [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]",@@ -376,7 +377,7 @@ mod tests {))?.build()?;- let expected =vec![+ let expected = vec!["Filter: t2.c < UInt32(20) AND t2.c = UInt32(10) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]",@@ -407,7 +408,7 @@ mod tests {))?.build()?;- let expected =vec![+ let expected = vec!["Filter: t2.c < UInt32(15) OR t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]",@@ -437,7 +438,7 @@ mod tests {))?.build()?;- let expected =vec![+ let expected = vec!["Filter: t1.a = t2.a AND t2.c < UInt32(15) OR t1.b = t2.b AND t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," CrossJoin: [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]",@@ -463,7 +464,7 @@ mod tests {))?.build()?;- let expected =vec![+ let expected = vec!["Filter: t1.a = t2.a AND t2.c < UInt32(15) OR t1.a = t2.a OR t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," CrossJoin: [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]",@@ -533,7 +534,7 @@ mod tests {))?.build()?;- let expected =vec![+ let expected = vec!["Filter: t4.c < UInt32(15) OR t4.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Filter: t2.c < UInt32(15) OR t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]",@@ -608,7 +609,7 @@ mod tests {))?.build()?;- let expected =vec![+ let expected = vec!["Filter: t3.a = t1.a AND t4.c < UInt32(15) OR t3.a = t1.a OR t4.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," CrossJoin: [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Filter: t2.c < UInt32(15) OR t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]",@@ -683,7 +684,7 @@ mod tests {))?.build()?;- let expected =vec![+ let expected = vec!["Filter: t4.c < UInt32(15) OR t4.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Filter: t2.c < UInt32(15) OR t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]",@@ -762,7 +763,7 @@ mod tests {))?.build()?;- let expected =vec![+ let expected = vec!["Filter: t4.c < UInt32(15) OR t4.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Filter: t1.a = t2.a OR t2.c < UInt32(15) OR t1.a = t2.a AND t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]",@@ -846,7 +847,7 @@ mod tests {))?.build()?;- let expected =vec![+ let expected = vec!["Filter: t4.c < UInt32(15) OR t4.c = UInt32(688) AND t4.c < UInt32(15) OR t3.c = UInt32(688) OR t3.b = t4.b [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Filter: t2.c < UInt32(15) AND t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]",@@ -934,7 +935,7 @@ mod tests {))?.build()?;- let expected =vec![+ let expected = vec!["Filter: t4.c < UInt32(15) OR t4.c = UInt32(688) AND t4.c < UInt32(15) OR t3.c = UInt32(688) OR t3.b = t4.b AND t2.c < UInt32(15) AND t2.c = UInt32(688) [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Inner Join: t1.a = t3.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]"," Inner Join: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32, b:UInt32, c:UInt32]",diff --git a/datafusion/optimizer/src/reduce_outer_join.rs b/datafusion/optimizer/src/reduce_outer_join.rsindex 93b706afe3..d0016cc191 100644--- a/datafusion/optimizer/src/reduce_outer_join.rs+++ b/datafusion/optimizer/src/reduce_outer_join.rs@@ -19,6 +19,7 @@use crate::{OptimizerConfig, OptimizerRule};use datafusion_common::{Column, DFSchema, Result};use datafusion_expr::{+ expr::BinaryExpr,logical_plan::{Filter, Join, JoinType, LogicalPlan, Projection},utils::from_plan,};@@ -244,7 +245,7 @@ fn extract_nonnullable_columns(nonnullable_cols.push(col.clone());Ok(())}- Expr::BinaryExpr { left, op, right } => match op {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => match op {// If one of the inputs are null for these operators, the results should be false.Operator::Eq| Operator::NotEqdiff --git a/datafusion/optimizer/src/rewrite_disjunctive_predicate.rs b/datafusion/optimizer/src/rewrite_disjunctive_predicate.rsindex a4f051e1c2..79f0d0ec25 100644--- a/datafusion/optimizer/src/rewrite_disjunctive_predicate.rs+++ b/datafusion/optimizer/src/rewrite_disjunctive_predicate.rs@@ -17,9 +17,9 @@use crate::{OptimizerConfig, OptimizerRule};use datafusion_common::Result;+use datafusion_expr::expr::BinaryExpr;use datafusion_expr::logical_plan::Filter;use datafusion_expr::utils::from_plan;-use datafusion_expr::Expr::BinaryExpr;use datafusion_expr::{Expr, LogicalPlan, Operator};use std::sync::Arc;@@ -178,7 +178,7 @@ enum Predicate {fn predicate(expr: &Expr) -> Result<Predicate> {match expr {- BinaryExpr { left, op, right } => match op {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => match op {Operator::And => {let args = vec![predicate(left)?, predicate(right)?];Ok(Predicate::And { args })@@ -188,11 +188,11 @@ fn predicate(expr: &Expr) -> Result<Predicate> {Ok(Predicate::Or { args })}_ => Ok(Predicate::Other {- expr: Box::new(BinaryExpr {- left: left.clone(),- op: *op,- right: right.clone(),- }),+ expr: Box::new(Expr::BinaryExpr(BinaryExpr::new(+ left.clone(),+ *op,+ right.clone(),+ ))),}),},_ => Ok(Predicate::Other {diff --git a/datafusion/optimizer/src/scalar_subquery_to_join.rs b/datafusion/optimizer/src/scalar_subquery_to_join.rsindex 149b2913a4..d8ff6583c8 100644--- a/datafusion/optimizer/src/scalar_subquery_to_join.rs+++ b/datafusion/optimizer/src/scalar_subquery_to_join.rs@@ -21,6 +21,7 @@ use crate::utils::{};use crate::{utils, OptimizerConfig, OptimizerRule};use datafusion_common::{context, plan_err, Column, Result};+use datafusion_expr::expr::BinaryExpr;use datafusion_expr::logical_plan::{Filter, JoinType, Limit, Subquery};use datafusion_expr::{Expr, LogicalPlan, LogicalPlanBuilder, Operator};use log::debug;@@ -54,7 +55,7 @@ impl ScalarSubqueryToJoin {let mut others = vec![];for it in filters.iter() {match it {- Expr::BinaryExpr { left, op, right } => {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => {let l_query = Subquery::try_from_expr(left);let r_query = Subquery::try_from_expr(right);if l_query.is_err() && r_query.is_err() {@@ -299,17 +300,17 @@ fn optimize_scalar(name: "__value".to_string(),}));let filter_expr = if query_info.expr_on_left {- Expr::BinaryExpr {- left: Box::new(query_info.expr.clone()),- op: query_info.op,- right: qry_expr,- }+ Expr::BinaryExpr(BinaryExpr::new(+ Box::new(query_info.expr.clone()),+ query_info.op,+ qry_expr,+ ))} else {- Expr::BinaryExpr {- left: qry_expr,- op: query_info.op,- right: Box::new(query_info.expr.clone()),- }+ Expr::BinaryExpr(BinaryExpr::new(+ qry_expr,+ query_info.op,+ Box::new(query_info.expr.clone()),+ ))};new_plan = new_plan.filter(filter_expr)?;diff --git a/datafusion/optimizer/src/simplify_expressions.rs b/datafusion/optimizer/src/simplify_expressions.rsindex 0499fea9f5..a9970abf6b 100644--- a/datafusion/optimizer/src/simplify_expressions.rs+++ b/datafusion/optimizer/src/simplify_expressions.rs@@ -24,6 +24,7 @@ use arrow::datatypes::{DataType, Field, Schema, DECIMAL128_MAX_PRECISION};use arrow::error::ArrowError;use arrow::record_batch::RecordBatch;use datafusion_common::{DFSchema, DataFusionError, Result, ScalarValue};+use datafusion_expr::expr::BinaryExpr;use datafusion_expr::{expr::Between,expr_fn::{and, or},@@ -95,7 +96,7 @@ pub struct SimplifyExpressions {}/// expressions. Such as: (A AND B) AND Cfn expr_contains(expr: &Expr, needle: &Expr, search_op: Operator) -> bool {match expr {- Expr::BinaryExpr { left, op, right } if *op == search_op => {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) if *op == search_op => {expr_contains(left, needle, search_op)|| expr_contains(right, needle, search_op)}@@ -173,7 +174,7 @@ fn is_false(expr: &Expr) -> bool {/// returns true if `haystack` looks like (needle OP X) or (X OP needle)fn is_op_with(target_op: Operator, haystack: &Expr, needle: &Expr) -> bool {- matches!(haystack, Expr::BinaryExpr { left, op, right } if op == &target_op && (needle == left.as_ref() || needle == right.as_ref()))+ matches!(haystack, Expr::BinaryExpr(BinaryExpr { left, op, right }) if op == &target_op && (needle == left.as_ref() || needle == right.as_ref()))}/// returns the contained boolean value in `expr` as@@ -204,13 +205,9 @@ fn as_bool_lit(expr: Expr) -> Result<Option<bool>> {/// For others, use Not clausefn negate_clause(expr: Expr) -> Expr {match expr {- Expr::BinaryExpr { left, op, right } => {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => {if let Some(negated_op) = op.negate() {- return Expr::BinaryExpr {- left,- op: negated_op,- right,- };+ return Expr::BinaryExpr(BinaryExpr::new(left, negated_op, right));}match op {// not (A and B) ===> (not A) or (not B)@@ -228,7 +225,9 @@ fn negate_clause(expr: Expr) -> Expr {and(left, right)}// use not clause- _ => Expr::Not(Box::new(Expr::BinaryExpr { left, op, right })),+ _ => Expr::Not(Box::new(Expr::BinaryExpr(BinaryExpr::new(+ left, op, right,+ )))),}}// not (not A) ===> A@@ -549,7 +548,6 @@ impl<'a, S> Simplifier<'a, S> {impl<'a, S: SimplifyInfo> ExprRewriter for Simplifier<'a, S> {/// rewrite the expression simplifying any constant expressionsfn mutate(&mut self, expr: Expr) -> Result<Expr> {- use Expr::*;use Operator::{And, Divide, Eq, Modulo, Multiply, NotEq, Or};let info = self.info;@@ -561,28 +559,28 @@ impl<'a, S: SimplifyInfo> ExprRewriter for Simplifier<'a, S> {// true = A --> A// false = A --> !A// null = A --> null- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Eq,right,- } if is_bool_lit(&left) && info.is_boolean_type(&right)? => {+ }) if is_bool_lit(&left) && info.is_boolean_type(&right)? => {match as_bool_lit(*left)? {Some(true) => *right,- Some(false) => Not(right),+ Some(false) => Expr::Not(right),None => lit_bool_null(),}}// A = true --> A// A = false --> !A// A = null --> null- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Eq,right,- } if is_bool_lit(&right) && info.is_boolean_type(&left)? => {+ }) if is_bool_lit(&right) && info.is_boolean_type(&left)? => {match as_bool_lit(*right)? {Some(true) => *left,- Some(false) => Not(left),+ Some(false) => Expr::Not(left),None => lit_bool_null(),}}@@ -594,13 +592,13 @@ impl<'a, S: SimplifyInfo> ExprRewriter for Simplifier<'a, S> {// true != A --> !A// false != A --> A// null != A --> null- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: NotEq,right,- } if is_bool_lit(&left) && info.is_boolean_type(&right)? => {+ }) if is_bool_lit(&left) && info.is_boolean_type(&right)? => {match as_bool_lit(*left)? {- Some(true) => Not(right),+ Some(true) => Expr::Not(right),Some(false) => *right,None => lit_bool_null(),}@@ -608,13 +606,13 @@ impl<'a, S: SimplifyInfo> ExprRewriter for Simplifier<'a, S> {// A != true --> !A// A != false --> A// A != null --> null,- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: NotEq,right,- } if is_bool_lit(&right) && info.is_boolean_type(&left)? => {+ }) if is_bool_lit(&right) && info.is_boolean_type(&left)? => {match as_bool_lit(*right)? {- Some(true) => Not(left),+ Some(true) => Expr::Not(left),Some(false) => *left,None => lit_bool_null(),}@@ -625,213 +623,213 @@ impl<'a, S: SimplifyInfo> ExprRewriter for Simplifier<'a, S> {//// true OR A --> true (even if A is null)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Or,right: _,- } if is_true(&left) => *left,+ }) if is_true(&left) => *left,// false OR A --> A- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Or,right,- } if is_false(&left) => *right,+ }) if is_false(&left) => *right,// A OR true --> true (even if A is null)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left: _,op: Or,right,- } if is_true(&right) => *right,+ }) if is_true(&right) => *right,// A OR false --> A- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Or,right,- } if is_false(&right) => *left,+ }) if is_false(&right) => *left,// (..A..) OR A --> (..A..)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Or,right,- } if expr_contains(&left, &right, Or) => *left,+ }) if expr_contains(&left, &right, Or) => *left,// A OR (..A..) --> (..A..)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Or,right,- } if expr_contains(&right, &left, Or) => *right,+ }) if expr_contains(&right, &left, Or) => *right,// A OR (A AND B) --> A (if B not null)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Or,right,- } if !info.nullable(&right)? && is_op_with(And, &right, &left) => *left,+ }) if !info.nullable(&right)? && is_op_with(And, &right, &left) => *left,// (A AND B) OR A --> A (if B not null)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Or,right,- } if !info.nullable(&left)? && is_op_with(And, &left, &right) => *right,+ }) if !info.nullable(&left)? && is_op_with(And, &left, &right) => *right,//// Rules for AND//// true AND A --> A- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: And,right,- } if is_true(&left) => *right,+ }) if is_true(&left) => *right,// false AND A --> false (even if A is null)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: And,right: _,- } if is_false(&left) => *left,+ }) if is_false(&left) => *left,// A AND true --> A- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: And,right,- } if is_true(&right) => *left,+ }) if is_true(&right) => *left,// A AND false --> false (even if A is null)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left: _,op: And,right,- } if is_false(&right) => *right,+ }) if is_false(&right) => *right,// (..A..) AND A --> (..A..)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: And,right,- } if expr_contains(&left, &right, And) => *left,+ }) if expr_contains(&left, &right, And) => *left,// A AND (..A..) --> (..A..)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: And,right,- } if expr_contains(&right, &left, And) => *right,+ }) if expr_contains(&right, &left, And) => *right,// A AND (A OR B) --> A (if B not null)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: And,right,- } if !info.nullable(&right)? && is_op_with(Or, &right, &left) => *left,+ }) if !info.nullable(&right)? && is_op_with(Or, &right, &left) => *left,// (A OR B) AND A --> A (if B not null)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: And,right,- } if !info.nullable(&left)? && is_op_with(Or, &left, &right) => *right,+ }) if !info.nullable(&left)? && is_op_with(Or, &left, &right) => *right,//// Rules for Multiply//// A * 1 --> A- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Multiply,right,- } if is_one(&right) => *left,+ }) if is_one(&right) => *left,// 1 * A --> A- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Multiply,right,- } if is_one(&left) => *right,+ }) if is_one(&left) => *right,// A * null --> null- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left: _,op: Multiply,right,- } if is_null(&right) => *right,+ }) if is_null(&right) => *right,// null * A --> null- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Multiply,right: _,- } if is_null(&left) => *left,+ }) if is_null(&left) => *left,// A * 0 --> 0 (if A is not null)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Multiply,right,- } if !info.nullable(&left)? && is_zero(&right) => *right,+ }) if !info.nullable(&left)? && is_zero(&right) => *right,// 0 * A --> 0 (if A is not null)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Multiply,right,- } if !info.nullable(&right)? && is_zero(&left) => *left,+ }) if !info.nullable(&right)? && is_zero(&left) => *left,//// Rules for Divide//// A / 1 --> A- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Divide,right,- } if is_one(&right) => *left,+ }) if is_one(&right) => *left,// null / A --> null- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Divide,right: _,- } if is_null(&left) => *left,+ }) if is_null(&left) => *left,// A / null --> null- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left: _,op: Divide,right,- } if is_null(&right) => *right,+ }) if is_null(&right) => *right,// A / A --> 1 (if a is not nullable)- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Divide,right,- } if !info.nullable(&left)? && left == right => lit(1),+ }) if !info.nullable(&left)? && left == right => lit(1),//// Rules for Modulo//// A % null --> null- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left: _,op: Modulo,right,- } if is_null(&right) => *right,+ }) if is_null(&right) => *right,// null % A --> null- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Modulo,right: _,- } if is_null(&left) => *left,+ }) if is_null(&left) => *left,// A % 1 --> 0- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Modulo,right,- } if !info.nullable(&left)? && is_one(&right) => lit(0),+ }) if !info.nullable(&left)? && is_one(&right) => lit(0),// A % 0 --> DivideByZero Error- BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left,op: Modulo,right,- } if !info.nullable(&left)? && is_zero(&right) => {+ }) if !info.nullable(&left)? && is_zero(&right) => {return Err(DataFusionError::ArrowError(ArrowError::DivideByZero))}//// Rules for Not//- Not(inner) => negate_clause(*inner),+ Expr::Not(inner) => negate_clause(*inner),//// Rules for Case@@ -848,7 +846,7 @@ impl<'a, S: SimplifyInfo> ExprRewriter for Simplifier<'a, S> {//// Note: the rationale for this rewrite is that the expr can then be further// simplified using the existing rules for AND/OR- Case(case)+ Expr::Case(case)if !case.when_then_expr.is_empty()&& case.when_then_expr.len() < 3 // The rewrite is O(n!) so limit to small number&& info.is_boolean_type(&case.when_then_expr[0].1)? =>@@ -879,7 +877,7 @@ impl<'a, S: SimplifyInfo> ExprRewriter for Simplifier<'a, S> {}// concat- ScalarFunction {+ Expr::ScalarFunction {fun: BuiltinScalarFunction::Concat,args,} => {@@ -915,14 +913,14 @@ impl<'a, S: SimplifyInfo> ExprRewriter for Simplifier<'a, S> {.push(Expr::Literal(ScalarValue::Utf8(Some(contiguous_scalar))));}- ScalarFunction {+ Expr::ScalarFunction {fun: BuiltinScalarFunction::Concat,args: new_args,}}// concat_ws- ScalarFunction {+ Expr::ScalarFunction {fun: BuiltinScalarFunction::ConcatWithSeparator,args,} => {@@ -932,7 +930,7 @@ impl<'a, S: SimplifyInfo> ExprRewriter for Simplifier<'a, S> {Expr::Literal(ScalarValue::Utf8(None))}// TODO https://github.com/apache/arrow-datafusion/issues/3599- _ => ScalarFunction {+ _ => Expr::ScalarFunction {fun: BuiltinScalarFunction::ConcatWithSeparator,args,},@@ -945,7 +943,7 @@ impl<'a, S: SimplifyInfo> ExprRewriter for Simplifier<'a, S> {// a between 3 and 5 --> a >= 3 AND a <=5// a not between 3 and 5 --> a < 3 OR a > 5- Between(between) => {+ Expr::Between(between) => {if between.negated {let l = *between.expr.clone();let r = *between.expr;@@ -2201,16 +2199,16 @@ mod tests {#[test]fn test_simplity_optimized_plan_support_values() {- let expr1 = Expr::BinaryExpr {- left: Box::new(lit(1)),- op: Operator::Plus,- right: Box::new(lit(2)),- };- let expr2 = Expr::BinaryExpr {- left: Box::new(lit(2)),- op: Operator::Minus,- right: Box::new(lit(1)),- };+ let expr1 = Expr::BinaryExpr(BinaryExpr::new(+ Box::new(lit(1)),+ Operator::Plus,+ Box::new(lit(2)),+ ));+ let expr2 = Expr::BinaryExpr(BinaryExpr::new(+ Box::new(lit(2)),+ Operator::Minus,+ Box::new(lit(1)),+ ));let values = vec![vec![expr1, expr2]];let plan = LogicalPlanBuilder::values(values).unwrap().build().unwrap();diff --git a/datafusion/optimizer/src/type_coercion.rs b/datafusion/optimizer/src/type_coercion.rsindex d698f3354b..6c80a4df50 100644--- a/datafusion/optimizer/src/type_coercion.rs+++ b/datafusion/optimizer/src/type_coercion.rs@@ -21,7 +21,7 @@ use crate::utils::rewrite_preserving_name;use crate::{OptimizerConfig, OptimizerRule};use arrow::datatypes::DataType;use datafusion_common::{DFSchema, DFSchemaRef, DataFusionError, Result};-use datafusion_expr::expr::{Between, Case, Like};+use datafusion_expr::expr::{Between, BinaryExpr, Case, Like};use datafusion_expr::expr_rewriter::{ExprRewriter, RewriteRecursion};use datafusion_expr::logical_plan::Subquery;use datafusion_expr::type_coercion::binary::{coerce_types, comparison_coercion};@@ -216,11 +216,11 @@ impl ExprRewriter for TypeCoercionRewriter {let expr = is_not_unknown(expr.cast_to(&coerced_type, &self.schema)?);Ok(expr)}- Expr::BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {ref left,op,ref right,- } => {+ }) => {let left_type = left.get_type(&self.schema)?;let right_type = right.get_type(&self.schema)?;match (&left_type, &right_type) {@@ -233,15 +233,11 @@ impl ExprRewriter for TypeCoercionRewriter {}_ => {let coerced_type = coerce_types(&left_type, &op, &right_type)?;- let expr = Expr::BinaryExpr {- left: Box::new(- left.clone().cast_to(&coerced_type, &self.schema)?,- ),+ let expr = Expr::BinaryExpr(BinaryExpr::new(+ Box::new(left.clone().cast_to(&coerced_type, &self.schema)?),op,- right: Box::new(- right.clone().cast_to(&coerced_type, &self.schema)?,- ),- };+ Box::new(right.clone().cast_to(&coerced_type, &self.schema)?),+ ));Ok(expr)}}diff --git a/datafusion/optimizer/src/unwrap_cast_in_comparison.rs b/datafusion/optimizer/src/unwrap_cast_in_comparison.rsindex 8d04357ade..93b8b71d6e 100644--- a/datafusion/optimizer/src/unwrap_cast_in_comparison.rs+++ b/datafusion/optimizer/src/unwrap_cast_in_comparison.rs@@ -24,6 +24,7 @@ use arrow::datatypes::{DataType, MAX_DECIMAL_FOR_EACH_PRECISION, MIN_DECIMAL_FOR_EACH_PRECISION,};use datafusion_common::{DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue};+use datafusion_expr::expr::BinaryExpr;use datafusion_expr::expr_rewriter::{ExprRewriter, RewriteRecursion};use datafusion_expr::utils::from_plan;use datafusion_expr::{@@ -118,7 +119,7 @@ impl ExprRewriter for UnwrapCastExprRewriter {// For case:// try_cast/cast(expr as data_type) op literal// literal op try_cast/cast(expr as data_type)- Expr::BinaryExpr { left, op, right } => {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => {let left = left.as_ref().clone();let right = right.as_ref().clone();let left_type = left.get_type(&self.schema)?;diff --git a/datafusion/optimizer/src/utils.rs b/datafusion/optimizer/src/utils.rsindex 57702a71f8..130df3e0e6 100644--- a/datafusion/optimizer/src/utils.rs+++ b/datafusion/optimizer/src/utils.rs@@ -20,6 +20,7 @@use crate::{OptimizerConfig, OptimizerRule};use datafusion_common::Result;use datafusion_common::{plan_err, Column, DFSchemaRef};+use datafusion_expr::expr::BinaryExpr;use datafusion_expr::expr_rewriter::{ExprRewritable, ExprRewriter};use datafusion_expr::expr_visitor::{ExprVisitable, ExpressionVisitor, Recursion};use datafusion_expr::{@@ -60,11 +61,11 @@ pub fn split_conjunction(expr: &Expr) -> Vec<&Expr> {fn split_conjunction_impl<'a>(expr: &'a Expr, mut exprs: Vec<&'a Expr>) -> Vec<&'a Expr> {match expr {- Expr::BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {right,op: Operator::And,left,- } => {+ }) => {let exprs = split_conjunction_impl(left, exprs);split_conjunction_impl(right, exprs)}@@ -103,11 +104,11 @@ pub fn split_conjunction_owned(expr: Expr) -> Vec<Expr> {fn split_conjunction_owned_impl(expr: Expr, mut exprs: Vec<Expr>) -> Vec<Expr> {match expr {- Expr::BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {right,op: Operator::And,left,- } => {+ }) => {let exprs = split_conjunction_owned_impl(*left, exprs);split_conjunction_owned_impl(*right, exprs)}@@ -178,11 +179,11 @@ pub fn verify_not_disjunction(predicates: &[&Expr]) -> Result<()> {impl ExpressionVisitor for DisjunctionVisitor {fn pre_visit(self, expr: &Expr) -> Result<Recursion<Self>> {match expr {- Expr::BinaryExpr {+ Expr::BinaryExpr(BinaryExpr {left: _,op: Operator::Or,right: _,- } => {+ }) => {plan_err!("Optimizing disjunctions not supported!")}_ => Ok(Recursion::Continue(self)),@@ -239,7 +240,9 @@ pub fn find_join_exprs(let mut others = vec![];for filter in exprs.iter() {let (left, op, right) = match filter {- Expr::BinaryExpr { left, op, right } => (*left.clone(), *op, *right.clone()),+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => {+ (*left.clone(), *op, *right.clone())+ }_ => {others.push((*filter).clone());continue;@@ -307,7 +310,9 @@ pub fn exprs_to_join_cols(let mut others: Vec<Expr> = vec![];for filter in exprs.iter() {let (left, op, right) = match filter {- Expr::BinaryExpr { left, op, right } => (*left.clone(), *op, *right.clone()),+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => {+ (*left.clone(), *op, *right.clone())+ }_ => plan_err!("Invalid correlation expression!")?,};match op {diff --git a/datafusion/physical-expr/src/planner.rs b/datafusion/physical-expr/src/planner.rsindex 742e10ec2c..d08448ef28 100644--- a/datafusion/physical-expr/src/planner.rs+++ b/datafusion/physical-expr/src/planner.rs@@ -27,6 +27,7 @@ use crate::{};use arrow::datatypes::{DataType, Schema};use datafusion_common::{DFSchema, DataFusionError, Result, ScalarValue};+use datafusion_expr::expr::BinaryExpr;use datafusion_expr::{binary_expr, Between, Expr, Like, Operator};use std::sync::Arc;@@ -166,7 +167,7 @@ pub fn create_physical_expr(execution_props,)}- Expr::BinaryExpr { left, op, right } => {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => {let lhs = create_physical_expr(left,input_dfschema,diff --git a/datafusion/proto/src/from_proto.rs b/datafusion/proto/src/from_proto.rsindex ef640889dc..feb78630d2 100644--- a/datafusion/proto/src/from_proto.rs+++ b/datafusion/proto/src/from_proto.rs@@ -31,6 +31,7 @@ use datafusion::execution::registry::FunctionRegistry;use datafusion_common::{Column, DFField, DFSchema, DFSchemaRef, DataFusionError, ScalarValue,};+use datafusion_expr::expr::BinaryExpr;use datafusion_expr::{abs, acos, array, ascii, asin, atan, atan2, bit_length, btrim, ceil,character_length, chr, coalesce, concat_expr, concat_ws_expr, cos, date_bin,@@ -785,11 +786,11 @@ pub fn parse_expr(.ok_or_else(|| Error::required("expr_type"))?;match expr_type {- ExprType::BinaryExpr(binary_expr) => Ok(Expr::BinaryExpr {- left: Box::new(parse_required_expr(&binary_expr.l, registry, "l")?),- op: from_proto_binary_op(&binary_expr.op)?,- right: Box::new(parse_required_expr(&binary_expr.r, registry, "r")?),- }),+ ExprType::BinaryExpr(binary_expr) => Ok(Expr::BinaryExpr(BinaryExpr::new(+ Box::new(parse_required_expr(&binary_expr.l, registry, "l")?),+ from_proto_binary_op(&binary_expr.op)?,+ Box::new(parse_required_expr(&binary_expr.r, registry, "r")?),+ ))),ExprType::GetIndexedField(field) => {let key = field.key.as_ref().ok_or_else(|| Error::required("value"))?;diff --git a/datafusion/proto/src/lib.rs b/datafusion/proto/src/lib.rsindex bb9298c8fd..5f366b561c 100644--- a/datafusion/proto/src/lib.rs+++ b/datafusion/proto/src/lib.rs@@ -63,7 +63,7 @@ mod roundtrip_tests {use datafusion::prelude::{create_udf, CsvReadOptions, SessionContext};use datafusion_common::{DFSchemaRef, DataFusionError, ScalarValue};use datafusion_expr::create_udaf;- use datafusion_expr::expr::{Between, Case, GroupingSet, Like};+ use datafusion_expr::expr::{Between, BinaryExpr, Case, GroupingSet, Like};use datafusion_expr::logical_plan::{Extension, UserDefinedLogicalNode};use datafusion_expr::{col, lit, Accumulator, AggregateFunction, AggregateState,@@ -812,11 +812,11 @@ mod roundtrip_tests {#[test]fn roundtrip_binary_op() {fn test(op: Operator) {- let test_expr = Expr::BinaryExpr {- left: Box::new(lit(1.0_f32)),+ let test_expr = Expr::BinaryExpr(BinaryExpr::new(+ Box::new(lit(1.0_f32)),op,- right: Box::new(lit(2.0_f32)),- };+ Box::new(lit(2.0_f32)),+ ));let ctx = SessionContext::new();roundtrip_expr_test(test_expr, ctx);}diff --git a/datafusion/proto/src/to_proto.rs b/datafusion/proto/src/to_proto.rsindex 279a6575f1..931779ab39 100644--- a/datafusion/proto/src/to_proto.rs+++ b/datafusion/proto/src/to_proto.rs@@ -34,7 +34,7 @@ use arrow::datatypes::{UnionMode,};use datafusion_common::{Column, DFField, DFSchemaRef, ScalarValue};-use datafusion_expr::expr::{Between, GroupingSet, Like};+use datafusion_expr::expr::{Between, BinaryExpr, GroupingSet, Like};use datafusion_expr::{logical_plan::PlanType, logical_plan::StringifiedPlan, AggregateFunction,BuiltInWindowFunction, BuiltinScalarFunction, Expr, WindowFrame, WindowFrameBound,@@ -446,7 +446,7 @@ impl TryFrom<&Expr> for protobuf::LogicalExprNode {expr_type: Some(ExprType::Literal(pb_value)),}}- Expr::BinaryExpr { left, op, right } => {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => {let binary_expr = Box::new(protobuf::BinaryExprNode {l: Some(Box::new(left.as_ref().try_into()?)),r: Some(Box::new(right.as_ref().try_into()?)),diff --git a/datafusion/sql/src/planner.rs b/datafusion/sql/src/planner.rsindex e47e987f35..7cff840daa 100644--- a/datafusion/sql/src/planner.rs+++ b/datafusion/sql/src/planner.rs@@ -51,7 +51,7 @@ use crate::utils::{make_decimal_type, normalize_ident, resolve_columns};use datafusion_common::{field_not_found, Column, DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue,};-use datafusion_expr::expr::{Between, Case, GroupingSet, Like};+use datafusion_expr::expr::{Between, BinaryExpr, Case, GroupingSet, Like};use datafusion_expr::logical_plan::builder::project_with_alias;use datafusion_expr::logical_plan::{Filter, Subquery};use datafusion_expr::Expr::Alias;@@ -1631,11 +1631,11 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {))),}?;- Ok(Expr::BinaryExpr {- left: Box::new(self.sql_expr_to_logical_expr(left, schema, ctes)?),- op: operator,- right: Box::new(self.sql_expr_to_logical_expr(right, schema, ctes)?),- })+ Ok(Expr::BinaryExpr(BinaryExpr::new(+ Box::new(self.sql_expr_to_logical_expr(left, schema, ctes)?),+ operator,+ Box::new(self.sql_expr_to_logical_expr(right, schema, ctes)?),+ )))}fn parse_sql_unary_op(@@ -1924,17 +1924,17 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {self.sql_expr_to_logical_expr(*expr, schema, ctes)?,))),- SQLExpr::IsDistinctFrom(left, right) => Ok(Expr::BinaryExpr {- left: Box::new(self.sql_expr_to_logical_expr(*left, schema, ctes)?),- op: Operator::IsDistinctFrom,- right: Box::new(self.sql_expr_to_logical_expr(*right, schema, ctes)?),- }),+ SQLExpr::IsDistinctFrom(left, right) => Ok(Expr::BinaryExpr(BinaryExpr::new(+ Box::new(self.sql_expr_to_logical_expr(*left, schema, ctes)?),+ Operator::IsDistinctFrom,+ Box::new(self.sql_expr_to_logical_expr(*right, schema, ctes)?),+ ))),- SQLExpr::IsNotDistinctFrom(left, right) => Ok(Expr::BinaryExpr {- left: Box::new(self.sql_expr_to_logical_expr(*left, schema, ctes)?),- op: Operator::IsNotDistinctFrom,- right: Box::new(self.sql_expr_to_logical_expr(*right, schema, ctes)?),- }),+ SQLExpr::IsNotDistinctFrom(left, right) => Ok(Expr::BinaryExpr(BinaryExpr::new(+ Box::new(self.sql_expr_to_logical_expr(*left, schema, ctes)?),+ Operator::IsNotDistinctFrom,+ Box::new(self.sql_expr_to_logical_expr(*right, schema, ctes)?),+ ))),SQLExpr::IsTrue(expr) => Ok(Expr::IsTrue(Box::new(self.sql_expr_to_logical_expr(*expr, schema, ctes)?))),@@ -2592,7 +2592,7 @@ fn remove_join_expressions(join_columns: &HashSet<(Column, Column)>,) -> Result<Option<Expr>> {match expr {- Expr::BinaryExpr { left, op, right } => match op {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => match op {Operator::Eq => match (left.as_ref(), right.as_ref()) {(Expr::Column(l), Expr::Column(r)) => {if join_columns.contains(&(l.clone(), r.clone()))@@ -2638,7 +2638,7 @@ fn extract_join_keys(right_schema: &Arc<DFSchema>,) {match &expr {- Expr::BinaryExpr { left, op, right } => match op {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => match op {Operator::Eq => match (left.as_ref(), right.as_ref()) {(Expr::Column(l), Expr::Column(r)) => {if left_schema.field_from_column(l).is_ok()@@ -2660,7 +2660,7 @@ fn extract_join_keys(}},Operator::And => {- if let Expr::BinaryExpr { left, op: _, right } = expr {+ if let Expr::BinaryExpr(BinaryExpr { left, op: _, right }) = expr {extract_join_keys(*left,accum,@@ -2693,7 +2693,7 @@ fn extract_possible_join_keys(accum: &mut Vec<(Column, Column)>,) -> Result<()> {match expr {- Expr::BinaryExpr { left, op, right } => match op {+ Expr::BinaryExpr(BinaryExpr { left, op, right }) => match op {Operator::Eq => match (left.as_ref(), right.as_ref()) {(Expr::Column(l), Expr::Column(r)) => {accum.push((l.clone(), r.clone()));diff --git a/datafusion/sql/src/utils.rs b/datafusion/sql/src/utils.rsindex e7909f6cc6..5b25753230 100644--- a/datafusion/sql/src/utils.rs+++ b/datafusion/sql/src/utils.rs@@ -21,7 +21,7 @@ use arrow::datatypes::{DataType, DECIMAL128_MAX_PRECISION, DECIMAL_DEFAULT_SCALEuse sqlparser::ast::Ident;use datafusion_common::{DataFusionError, Result, ScalarValue};-use datafusion_expr::expr::{Between, Case, GroupingSet, Like};+use datafusion_expr::expr::{Between, BinaryExpr, Case, GroupingSet, Like};use datafusion_expr::utils::{expr_as_column_expr, find_column_exprs};use datafusion_expr::{Expr, LogicalPlan};use std::collections::HashMap;@@ -230,11 +230,13 @@ where.collect::<Result<Vec<Expr>>>()?,negated: *negated,}),- Expr::BinaryExpr { left, right, op } => Ok(Expr::BinaryExpr {- left: Box::new(clone_with_replacement(left, replacement_fn)?),- op: *op,- right: Box::new(clone_with_replacement(right, replacement_fn)?),- }),+ Expr::BinaryExpr(BinaryExpr { left, right, op }) => {+ Ok(Expr::BinaryExpr(BinaryExpr::new(+ Box::new(clone_with_replacement(left, replacement_fn)?),+ *op,+ Box::new(clone_with_replacement(right, replacement_fn)?),+ )))+ }Expr::Like(Like {negated,expr,