Apache DataFusion SQL Query Engine
reimplement `eliminate_outer_join` (#4272)
jakevin502b7e3cae16
diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rsindex ae4cdd3638..68bfaa378a 100644--- a/datafusion/expr/src/logical_plan/plan.rs+++ b/datafusion/expr/src/logical_plan/plan.rs@@ -999,6 +999,12 @@ pub enum JoinType {RightAnti,}+impl JoinType {+ pub fn is_outer(self) -> bool {+ self == JoinType::Left || self == JoinType::Right || self == JoinType::Full+ }+}+impl Display for JoinType {fn fmt(&self, f: &mut Formatter) -> fmt::Result {let join_type = match self {diff --git a/datafusion/optimizer/src/reduce_outer_join.rs b/datafusion/optimizer/src/eliminate_outer_join.rssimilarity index 50%rename from datafusion/optimizer/src/reduce_outer_join.rsrename to datafusion/optimizer/src/eliminate_outer_join.rsindex 8e61c4283b..7d25993e6d 100644--- a/datafusion/optimizer/src/reduce_outer_join.rs+++ b/datafusion/optimizer/src/eliminate_outer_join.rs@@ -15,235 +15,141 @@// specific language governing permissions and limitations// under the License.-//! Optimizer rule to reduce left/right/full join to inner join if possible.-use crate::{OptimizerConfig, OptimizerRule};+//! Optimizer rule to eliminate left/right/full join to inner join if possible.+use crate::{utils, OptimizerConfig, OptimizerRule};use datafusion_common::{Column, DFSchema, Result};use datafusion_expr::{expr::BinaryExpr,- logical_plan::{Filter, Join, JoinType, LogicalPlan, Projection},+ logical_plan::{Join, JoinType, LogicalPlan},utils::from_plan,};use datafusion_expr::{Expr, Operator};use datafusion_expr::expr::Cast;-use std::collections::HashMap;use std::sync::Arc;#[derive(Default)]-pub struct ReduceOuterJoin;+pub struct EliminateOuterJoin;-impl ReduceOuterJoin {+impl EliminateOuterJoin {#[allow(missing_docs)]pub fn new() -> Self {Self {}}}-impl OptimizerRule for ReduceOuterJoin {+/// Attempt to eliminate outer joins.+impl OptimizerRule for EliminateOuterJoin {fn optimize(&self,plan: &LogicalPlan,optimizer_config: &mut OptimizerConfig,) -> Result<LogicalPlan> {- let mut nonnullable_cols: Vec<Column> = vec![];+ match plan {+ LogicalPlan::Filter(filter) => match filter.input().as_ref() {+ LogicalPlan::Join(join) => {+ let mut non_nullable_cols: Vec<Column> = vec![];++ extract_non_nullable_columns(+ filter.predicate(),+ &mut non_nullable_cols,+ join.left.schema(),+ join.right.schema(),+ true,+ )?;- reduce_outer_join(self, plan, &mut nonnullable_cols, optimizer_config)+ let new_join_type = if join.join_type.is_outer() {+ let mut left_non_nullable = false;+ let mut right_non_nullable = false;+ for col in non_nullable_cols.iter() {+ if join.left.schema().field_from_column(col).is_ok() {+ left_non_nullable = true;+ }+ if join.right.schema().field_from_column(col).is_ok() {+ right_non_nullable = true;+ }+ }+ eliminate_outer(+ join.join_type,+ left_non_nullable,+ right_non_nullable,+ )+ } else {+ join.join_type+ };+ let new_join = LogicalPlan::Join(Join {+ left: Arc::new((*join.left).clone()),+ right: Arc::new((*join.right).clone()),+ join_type: new_join_type,+ join_constraint: join.join_constraint,+ on: join.on.clone(),+ filter: join.filter.clone(),+ schema: join.schema.clone(),+ null_equals_null: join.null_equals_null,+ });+ let new_plan = from_plan(plan, &plan.expressions(), &[new_join])?;+ utils::optimize_children(self, &new_plan, optimizer_config)+ }+ _ => utils::optimize_children(self, plan, optimizer_config),+ },+ _ => utils::optimize_children(self, plan, optimizer_config),+ }}fn name(&self) -> &str {- "reduce_outer_join"+ "eliminate_outer_join"}}-/// Attempt to reduce outer joins to inner joins.-/// for query: select ... from a left join b on ... where b.xx = 100;-/// if b.xx is null, and b.xx = 100 returns false, filterd those null rows.-/// Therefore, there is no need to produce null rows for output, we can use-/// inner join instead of left join.-///-/// Generally, an outer join can be reduced to inner join if quals from where-/// return false while any inputs are null and columns of those quals are come from-/// nullable side of outer join.-fn reduce_outer_join(- _optimizer: &ReduceOuterJoin,- plan: &LogicalPlan,- nonnullable_cols: &mut Vec<Column>,- _optimizer_config: &OptimizerConfig,-) -> Result<LogicalPlan> {- match plan {- LogicalPlan::Filter(filter) => match filter.input().as_ref() {- LogicalPlan::Join(join) => {- extract_nonnullable_columns(- filter.predicate(),- nonnullable_cols,- join.left.schema(),- join.right.schema(),- true,- )?;- Ok(LogicalPlan::Filter(Filter::try_new(- filter.predicate().clone(),- Arc::new(reduce_outer_join(- _optimizer,- filter.input(),- nonnullable_cols,- _optimizer_config,- )?),- )?))+pub fn eliminate_outer(+ join_type: JoinType,+ left_non_nullable: bool,+ right_non_nullable: bool,+) -> JoinType {+ let mut new_join_type = join_type;+ match join_type {+ JoinType::Left => {+ if right_non_nullable {+ new_join_type = JoinType::Inner;}- _ => Ok(LogicalPlan::Filter(Filter::try_new(- filter.predicate().clone(),- Arc::new(reduce_outer_join(- _optimizer,- filter.input(),- nonnullable_cols,- _optimizer_config,- )?),- )?)),- },- LogicalPlan::Join(join) => {- let mut new_join_type = join.join_type;-- if join.join_type == JoinType::Left- || join.join_type == JoinType::Right- || join.join_type == JoinType::Full- {- let mut left_nonnullable = false;- let mut right_nonnullable = false;- for col in nonnullable_cols.iter() {- if join.left.schema().field_from_column(col).is_ok() {- left_nonnullable = true;- }- if join.right.schema().field_from_column(col).is_ok() {- right_nonnullable = true;- }- }-- match join.join_type {- JoinType::Left => {- if right_nonnullable {- new_join_type = JoinType::Inner;- }- }- JoinType::Right => {- if left_nonnullable {- new_join_type = JoinType::Inner;- }- }- JoinType::Full => {- if left_nonnullable && right_nonnullable {- new_join_type = JoinType::Inner;- } else if left_nonnullable {- new_join_type = JoinType::Left;- } else if right_nonnullable {- new_join_type = JoinType::Right;- }- }- _ => {}- };- }-- let left_plan = reduce_outer_join(- _optimizer,- &join.left,- &mut nonnullable_cols.clone(),- _optimizer_config,- )?;- let right_plan = reduce_outer_join(- _optimizer,- &join.right,- &mut nonnullable_cols.clone(),- _optimizer_config,- )?;-- Ok(LogicalPlan::Join(Join {- left: Arc::new(left_plan),- right: Arc::new(right_plan),- join_type: new_join_type,- join_constraint: join.join_constraint,- on: join.on.clone(),- filter: join.filter.clone(),- schema: join.schema.clone(),- null_equals_null: join.null_equals_null,- }))}- LogicalPlan::Projection(Projection {- input,- expr,- schema,- alias: _,- }) => {- let projection = schema- .fields()- .iter()- .enumerate()- .map(|(i, field)| {- // strip alias, as they should not be part of filters- let expr = match &expr[i] {- Expr::Alias(expr, _) => expr.as_ref().clone(),- expr => expr.clone(),- };-- (field.qualified_name(), expr)- })- .collect::<HashMap<_, _>>();-- // re-write all Columns based on this projection- for col in nonnullable_cols.iter_mut() {- if let Some(Expr::Column(column)) = projection.get(&col.flat_name()) {- *col = column.clone();- }+ JoinType::Right => {+ if left_non_nullable {+ new_join_type = JoinType::Inner;}-- // optimize inner- let new_input = reduce_outer_join(- _optimizer,- input,- nonnullable_cols,- _optimizer_config,- )?;-- from_plan(plan, expr, &[new_input])}- _ => {- let expr = plan.expressions();-- // apply the optimization to all inputs of the plan- let inputs = plan.inputs();- let new_inputs = inputs- .iter()- .map(|plan| {- reduce_outer_join(- _optimizer,- plan,- nonnullable_cols,- _optimizer_config,- )- })- .collect::<Result<Vec<_>>>()?;-- from_plan(plan, &expr, &new_inputs)+ JoinType::Full => {+ if left_non_nullable && right_non_nullable {+ new_join_type = JoinType::Inner;+ } else if left_non_nullable {+ new_join_type = JoinType::Left;+ } else if right_non_nullable {+ new_join_type = JoinType::Right;+ }}+ _ => {}}+ new_join_type}/// Recursively traverses expr, if expr returns false when-/// any inputs are null, treats columns of both sides as nonnullable columns.+/// any inputs are null, treats columns of both sides as non_nullable columns.////// For and/or expr, extracts from all sub exprs and merges the columns./// For or expr, if one of sub exprs returns true, discards all columns from or expr./// For IS NOT NULL/NOT expr, always returns false for NULL input./// extracts columns from these exprs./// For all other exprs, fall through-fn extract_nonnullable_columns(+fn extract_non_nullable_columns(expr: &Expr,- nonnullable_cols: &mut Vec<Column>,+ non_nullable_cols: &mut Vec<Column>,left_schema: &Arc<DFSchema>,right_schema: &Arc<DFSchema>,top_level: bool,) -> Result<()> {match expr {Expr::Column(col) => {- nonnullable_cols.push(col.clone());+ non_nullable_cols.push(col.clone());Ok(())}Expr::BinaryExpr(BinaryExpr { left, op, right }) => match op {@@ -254,16 +160,16 @@ fn extract_nonnullable_columns(| Operator::LtEq| Operator::Gt| Operator::GtEq => {- extract_nonnullable_columns(+ extract_non_nullable_columns(left,- nonnullable_cols,+ non_nullable_cols,left_schema,right_schema,false,)?;- extract_nonnullable_columns(+ extract_non_nullable_columns(right,- nonnullable_cols,+ non_nullable_cols,left_schema,right_schema,false,@@ -273,16 +179,16 @@ fn extract_nonnullable_columns(// treat And as Or if does not from top level, such as// not (c1 < 10 and c2 > 100)if top_level && *op == Operator::And {- extract_nonnullable_columns(+ extract_non_nullable_columns(left,- nonnullable_cols,+ non_nullable_cols,left_schema,right_schema,top_level,)?;- extract_nonnullable_columns(+ extract_non_nullable_columns(right,- nonnullable_cols,+ non_nullable_cols,left_schema,right_schema,top_level,@@ -290,40 +196,41 @@ fn extract_nonnullable_columns(return Ok(());}- let mut left_nonnullable_cols: Vec<Column> = vec![];- let mut right_nonnullable_cols: Vec<Column> = vec![];+ let mut left_non_nullable_cols: Vec<Column> = vec![];+ let mut right_non_nullable_cols: Vec<Column> = vec![];- extract_nonnullable_columns(+ extract_non_nullable_columns(left,- &mut left_nonnullable_cols,+ &mut left_non_nullable_cols,left_schema,right_schema,top_level,)?;- extract_nonnullable_columns(+ extract_non_nullable_columns(right,- &mut right_nonnullable_cols,+ &mut right_non_nullable_cols,left_schema,right_schema,top_level,)?;// for query: select *** from a left join b where b.c1 ... or b.c2 ...- // this can be reduced to inner join.+ // this can be eliminated to inner join.// for query: select *** from a left join b where a.c1 ... or b.c2 ...- // this can not be reduced.+ // this can not be eliminated.// If columns of relation exist in both sub exprs, any columns of this relation// can be added to non nullable columns.- if !left_nonnullable_cols.is_empty() && !right_nonnullable_cols.is_empty()+ if !left_non_nullable_cols.is_empty()+ && !right_non_nullable_cols.is_empty(){- for left_col in &left_nonnullable_cols {- for right_col in &right_nonnullable_cols {+ for left_col in &left_non_nullable_cols {+ for right_col in &right_non_nullable_cols {if (left_schema.field_from_column(left_col).is_ok()&& left_schema.field_from_column(right_col).is_ok())|| (right_schema.field_from_column(left_col).is_ok()&& right_schema.field_from_column(right_col).is_ok()){- nonnullable_cols.push(left_col.clone());+ non_nullable_cols.push(left_col.clone());break;}}@@ -333,9 +240,9 @@ fn extract_nonnullable_columns(}_ => Ok(()),},- Expr::Not(arg) => extract_nonnullable_columns(+ Expr::Not(arg) => extract_non_nullable_columns(arg,- nonnullable_cols,+ non_nullable_cols,left_schema,right_schema,false,@@ -344,18 +251,18 @@ fn extract_nonnullable_columns(if !top_level {return Ok(());}- extract_nonnullable_columns(+ extract_non_nullable_columns(arg,- nonnullable_cols,+ non_nullable_cols,left_schema,right_schema,false,)}Expr::Cast(Cast { expr, data_type: _ })- | Expr::TryCast { expr, data_type: _ } => extract_nonnullable_columns(+ | Expr::TryCast { expr, data_type: _ } => extract_non_nullable_columns(expr,- nonnullable_cols,+ non_nullable_cols,left_schema,right_schema,false,@@ -376,22 +283,23 @@ mod tests {Operator::{And, Or},};- fn assert_optimized_plan_eq(plan: &LogicalPlan, expected: &str) {- let rule = ReduceOuterJoin::new();+ fn assert_optimized_plan_eq(plan: &LogicalPlan, expected: &str) -> Result<()> {+ let rule = EliminateOuterJoin::new();let optimized_plan = rule.optimize(plan, &mut OptimizerConfig::new()).expect("failed to optimize plan");let formatted_plan = format!("{:?}", optimized_plan);assert_eq!(formatted_plan, expected);assert_eq!(plan.schema(), optimized_plan.schema());+ Ok(())}#[test]- fn reduce_left_with_null() -> Result<()> {+ fn eliminate_left_with_null() -> Result<()> {let t1 = test_table_scan_with_name("t1")?;let t2 = test_table_scan_with_name("t2")?;- // could not reduce to inner join+ // could not eliminate to inner joinlet plan = LogicalPlanBuilder::from(t1).join(&t2,@@ -406,17 +314,15 @@ mod tests {\n Left Join: t1.a = t2.a\\n TableScan: t1\\n TableScan: t2";- assert_optimized_plan_eq(&plan, expected);-- Ok(())+ assert_optimized_plan_eq(&plan, expected)}#[test]- fn reduce_left_with_not_null() -> Result<()> {+ fn eliminate_left_with_not_null() -> Result<()> {let t1 = test_table_scan_with_name("t1")?;let t2 = test_table_scan_with_name("t2")?;- // reduce to inner join+ // eliminate to inner joinlet plan = LogicalPlanBuilder::from(t1).join(&t2,@@ -431,17 +337,15 @@ mod tests {\n Inner Join: t1.a = t2.a\\n TableScan: t1\\n TableScan: t2";- assert_optimized_plan_eq(&plan, expected);-- Ok(())+ assert_optimized_plan_eq(&plan, expected)}#[test]- fn reduce_right_with_or() -> Result<()> {+ fn eliminate_right_with_or() -> Result<()> {let t1 = test_table_scan_with_name("t1")?;let t2 = test_table_scan_with_name("t2")?;- // reduce to inner join+ // eliminate to inner joinlet plan = LogicalPlanBuilder::from(t1).join(&t2,@@ -460,17 +364,15 @@ mod tests {\n Inner Join: t1.a = t2.a\\n TableScan: t1\\n TableScan: t2";- assert_optimized_plan_eq(&plan, expected);-- Ok(())+ assert_optimized_plan_eq(&plan, expected)}#[test]- fn reduce_full_with_and() -> Result<()> {+ fn eliminate_full_with_and() -> Result<()> {let t1 = test_table_scan_with_name("t1")?;let t2 = test_table_scan_with_name("t2")?;- // reduce to inner join+ // eliminate to inner joinlet plan = LogicalPlanBuilder::from(t1).join(&t2,@@ -489,17 +391,15 @@ mod tests {\n Inner Join: t1.a = t2.a\\n TableScan: t1\\n TableScan: t2";- assert_optimized_plan_eq(&plan, expected);-- Ok(())+ assert_optimized_plan_eq(&plan, expected)}#[test]- fn reduce_full_with_type_cast() -> Result<()> {+ fn eliminate_full_with_type_cast() -> Result<()> {let t1 = test_table_scan_with_name("t1")?;let t2 = test_table_scan_with_name("t2")?;- // reduce to inner join+ // eliminate to inner joinlet plan = LogicalPlanBuilder::from(t1).join(&t2,@@ -518,8 +418,6 @@ mod tests {\n Inner Join: t1.a = t2.a\\n TableScan: t1\\n TableScan: t2";- assert_optimized_plan_eq(&plan, expected);-- Ok(())+ assert_optimized_plan_eq(&plan, expected)}}diff --git a/datafusion/optimizer/src/lib.rs b/datafusion/optimizer/src/lib.rsindex 467ec3b240..cdfe7fc9b3 100644--- a/datafusion/optimizer/src/lib.rs+++ b/datafusion/optimizer/src/lib.rs@@ -21,6 +21,7 @@ pub mod decorrelate_where_in;pub mod eliminate_cross_join;pub mod eliminate_filter;pub mod eliminate_limit;+pub mod eliminate_outer_join;pub mod filter_null_join_keys;pub mod filter_push_down;pub mod inline_table_scan;@@ -28,7 +29,6 @@ pub mod limit_push_down;pub mod optimizer;pub mod projection_push_down;pub mod propagate_empty_relation;-pub mod reduce_outer_join;pub mod scalar_subquery_to_join;pub mod simplify_expressions;pub mod single_distinct_to_groupby;diff --git a/datafusion/optimizer/src/optimizer.rs b/datafusion/optimizer/src/optimizer.rsindex 3614c8a4f4..1dfd103466 100644--- a/datafusion/optimizer/src/optimizer.rs+++ b/datafusion/optimizer/src/optimizer.rs@@ -23,13 +23,13 @@ use crate::decorrelate_where_in::DecorrelateWhereIn;use crate::eliminate_cross_join::ReduceCrossJoin;use crate::eliminate_filter::EliminateFilter;use crate::eliminate_limit::EliminateLimit;+use crate::eliminate_outer_join::EliminateOuterJoin;use crate::filter_null_join_keys::FilterNullJoinKeys;use crate::filter_push_down::FilterPushDown;use crate::inline_table_scan::InlineTableScan;use crate::limit_push_down::LimitPushDown;use crate::projection_push_down::ProjectionPushDown;use crate::propagate_empty_relation::PropagateEmptyRelation;-use crate::reduce_outer_join::ReduceOuterJoin;use crate::rewrite_disjunctive_predicate::RewriteDisjunctivePredicate;use crate::scalar_subquery_to_join::ScalarSubqueryToJoin;use crate::simplify_expressions::SimplifyExpressions;@@ -183,7 +183,7 @@ impl Optimizer {if config.filter_null_keys {rules.push(Arc::new(FilterNullJoinKeys::default()));}- rules.push(Arc::new(ReduceOuterJoin::new()));+ rules.push(Arc::new(EliminateOuterJoin::new()));rules.push(Arc::new(FilterPushDown::new()));rules.push(Arc::new(LimitPushDown::new()));rules.push(Arc::new(SingleDistinctToGroupBy::new()));