Apache DataFusion SQL Query Engine
Move Scalar Subquery validation logic to the Analyzer (#6084)
Ken, Wang99bc3938e87a
diff --git a/benchmarks/expected-plans/q2.txt b/benchmarks/expected-plans/q2.txtindex ad99c3f1e8..2bc3f732bf 100644--- a/benchmarks/expected-plans/q2.txt+++ b/benchmarks/expected-plans/q2.txt@@ -3,7 +3,7 @@+---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+| logical_plan | Sort: supplier.s_acctbal DESC NULLS FIRST, nation.n_name ASC NULLS LAST, supplier.s_name ASC NULLS LAST, part.p_partkey ASC NULLS LAST || | Projection: supplier.s_acctbal, supplier.s_name, nation.n_name, part.p_partkey, part.p_mfgr, supplier.s_address, supplier.s_phone, supplier.s_comment |-| | Inner Join: part.p_partkey = __scalar_sq_1.ps_partkey, partsupp.ps_supplycost = __scalar_sq_1.__value |+| | Inner Join: partsupp.ps_supplycost = __scalar_sq_1.__value, part.p_partkey = __scalar_sq_1.ps_partkey || | Projection: part.p_partkey, part.p_mfgr, partsupp.ps_supplycost, supplier.s_name, supplier.s_address, supplier.s_phone, supplier.s_acctbal, supplier.s_comment, nation.n_name || | Inner Join: nation.n_regionkey = region.r_regionkey || | Projection: part.p_partkey, part.p_mfgr, partsupp.ps_supplycost, supplier.s_name, supplier.s_address, supplier.s_phone, supplier.s_acctbal, supplier.s_comment, nation.n_name, nation.n_regionkey |@@ -40,9 +40,9 @@| | SortExec: expr=[s_acctbal@0 DESC,n_name@2 ASC NULLS LAST,s_name@1 ASC NULLS LAST,p_partkey@3 ASC NULLS LAST] || | ProjectionExec: expr=[s_acctbal@6 as s_acctbal, s_name@3 as s_name, n_name@8 as n_name, p_partkey@0 as p_partkey, p_mfgr@1 as p_mfgr, s_address@4 as s_address, s_phone@5 as s_phone, s_comment@7 as s_comment] || | CoalesceBatchesExec: target_batch_size=8192 |-| | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(Column { name: "p_partkey", index: 0 }, Column { name: "ps_partkey", index: 0 }), (Column { name: "ps_supplycost", index: 2 }, Column { name: "__value", index: 1 })] |+| | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(Column { name: "ps_supplycost", index: 2 }, Column { name: "__value", index: 1 }), (Column { name: "p_partkey", index: 0 }, Column { name: "ps_partkey", index: 0 })] || | CoalesceBatchesExec: target_batch_size=8192 |-| | RepartitionExec: partitioning=Hash([Column { name: "p_partkey", index: 0 }, Column { name: "ps_supplycost", index: 2 }], 2), input_partitions=2 |+| | RepartitionExec: partitioning=Hash([Column { name: "ps_supplycost", index: 2 }, Column { name: "p_partkey", index: 0 }], 2), input_partitions=2 || | ProjectionExec: expr=[p_partkey@0 as p_partkey, p_mfgr@1 as p_mfgr, ps_supplycost@2 as ps_supplycost, s_name@3 as s_name, s_address@4 as s_address, s_phone@5 as s_phone, s_acctbal@6 as s_acctbal, s_comment@7 as s_comment, n_name@8 as n_name] || | CoalesceBatchesExec: target_batch_size=8192 || | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(Column { name: "n_regionkey", index: 9 }, Column { name: "r_regionkey", index: 0 })] |@@ -85,7 +85,7 @@| | FilterExec: r_name@1 = EUROPE || | MemoryExec: partitions=0, partition_sizes=[] || | CoalesceBatchesExec: target_batch_size=8192 |-| | RepartitionExec: partitioning=Hash([Column { name: "ps_partkey", index: 0 }, Column { name: "__value", index: 1 }], 2), input_partitions=2 |+| | RepartitionExec: partitioning=Hash([Column { name: "__value", index: 1 }, Column { name: "ps_partkey", index: 0 }], 2), input_partitions=2 || | ProjectionExec: expr=[ps_partkey@0 as ps_partkey, MIN(partsupp.ps_supplycost)@1 as __value] || | AggregateExec: mode=FinalPartitioned, gby=[ps_partkey@0 as ps_partkey], aggr=[MIN(partsupp.ps_supplycost)] || | CoalesceBatchesExec: target_batch_size=8192 |diff --git a/datafusion/core/tests/dataframe.rs b/datafusion/core/tests/dataframe.rsindex 82c5a35b7f..93a35f21f4 100644--- a/datafusion/core/tests/dataframe.rs+++ b/datafusion/core/tests/dataframe.rs@@ -39,8 +39,8 @@ use datafusion_expr::expr::{GroupingSet, Sort};use datafusion_expr::utils::COUNT_STAR_EXPANSION;use datafusion_expr::Expr::Wildcard;use datafusion_expr::{- avg, col, count, exists, expr, in_subquery, lit, max, scalar_subquery, sum,- AggregateFunction, Expr, ExprSchemable, WindowFrame, WindowFrameBound,+ avg, col, count, exists, expr, in_subquery, lit, max, out_ref_col, scalar_subquery,+ sum, AggregateFunction, Expr, ExprSchemable, WindowFrame, WindowFrameBound,WindowFrameUnits, WindowFunction,};@@ -241,7 +241,7 @@ async fn test_count_wildcard_on_where_scalar_subquery() -> Result<()> {scalar_subquery(Arc::new(ctx.table("t2").await?- .filter(col("t1.a").eq(col("t2.a")))?+ .filter(out_ref_col(DataType::UInt32, "t1.a").eq(col("t2.a")))?.aggregate(vec![], vec![count(lit(COUNT_STAR_EXPANSION))])?.select(vec![count(lit(COUNT_STAR_EXPANSION))])?.into_unoptimized_plan(),diff --git a/datafusion/core/tests/sql/subqueries.rs b/datafusion/core/tests/sql/subqueries.rsindex eb7a12045c..60ed0c0f6d 100644--- a/datafusion/core/tests/sql/subqueries.rs+++ b/datafusion/core/tests/sql/subqueries.rs@@ -185,7 +185,7 @@ async fn invalid_scalar_subquery() -> Result<()> {let dataframe = ctx.sql(sql).await.expect(&msg);let err = dataframe.into_optimized_plan().err().unwrap();assert_eq!(- r#"Context("check_analyzed_plan", Plan("Scalar subquery should only return one column"))"#,+ r#"Context("check_analyzed_plan", Plan("Scalar subquery should only return one column, but found 2: t2.t2_id, t2.t2_name"))"#,&format!("{err:?}"));@@ -203,7 +203,231 @@ async fn subquery_not_allowed() -> Result<()> {let err = dataframe.into_optimized_plan().err().unwrap();assert_eq!(- r#"Context("check_analyzed_plan", Plan("In/Exist subquery can not be used in Sort plan nodes"))"#,+ r#"Context("check_analyzed_plan", Plan("In/Exist subquery can only be used in Projection, Filter, Window functions, Aggregate and Join plan nodes"))"#,+ &format!("{err:?}")+ );++ Ok(())+}++#[tokio::test]+async fn non_aggregated_correlated_scalar_subquery() -> Result<()> {+ let ctx = create_join_context("t1_id", "t2_id", true)?;++ let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int) as t2_int from t1";+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let err = dataframe.into_optimized_plan().err().unwrap();++ assert_eq!(+ r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery must be aggregated to return at most one row"))"#,+ &format!("{err:?}")+ );++ let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1_int group by t2_int) as t2_int from t1";+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let err = dataframe.into_optimized_plan().err().unwrap();++ assert_eq!(+ r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery must be aggregated to return at most one row"))"#,+ &format!("{err:?}")+ );++ Ok(())+}++#[tokio::test]+async fn non_aggregated_correlated_scalar_subquery_with_limit() -> Result<()> {+ let ctx = create_join_context("t1_id", "t2_id", true)?;++ let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int limit 2) as t2_int from t1";+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let err = dataframe.into_optimized_plan().err().unwrap();++ assert_eq!(+ r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery must be aggregated to return at most one row"))"#,+ &format!("{err:?}")+ );++ Ok(())+}++#[tokio::test]+async fn non_aggregated_correlated_scalar_subquery_with_single_row() -> Result<()> {+ let ctx = create_join_context("t1_id", "t2_id", true)?;++ let sql = "SELECT t1_id, (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int limit 1) as t2_int from t1";+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let plan = dataframe.into_optimized_plan()?;++ let expected = vec![+ "Projection: t1.t1_id, (<subquery>) AS t2_int [t1_id:UInt32;N, t2_int:UInt32;N]",+ " Subquery: [t2_int:UInt32;N]",+ " Limit: skip=0, fetch=1 [t2_int:UInt32;N]",+ " Projection: t2.t2_int [t2_int:UInt32;N]",+ " Filter: t2.t2_int = outer_ref(t1.t1_int) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",+ " TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",+ " TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",+ ];+ let formatted = plan.display_indent_schema().to_string();+ let actual: Vec<&str> = formatted.trim().lines().collect();+ assert_eq!(+ expected, actual,+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"+ );++ let sql = "SELECT t1_id from t1 where t1_int = (SELECT t2_int FROM t2 WHERE t2.t2_int = t1.t1_int limit 1)";+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let plan = dataframe.into_optimized_plan()?;++ let expected = vec![+ "Projection: t1.t1_id [t1_id:UInt32;N]",+ " Filter: t1.t1_int = (<subquery>) [t1_id:UInt32;N, t1_int:UInt32;N]",+ " Subquery: [t2_int:UInt32;N]",+ " Limit: skip=0, fetch=1 [t2_int:UInt32;N]",+ " Projection: t2.t2_int [t2_int:UInt32;N]",+ " Filter: t2.t2_int = outer_ref(t1.t1_int) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",+ " TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",+ " TableScan: t1 projection=[t1_id, t1_int] [t1_id:UInt32;N, t1_int:UInt32;N]",+ ];+ let formatted = plan.display_indent_schema().to_string();+ let actual: Vec<&str> = formatted.trim().lines().collect();+ assert_eq!(+ expected, actual,+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"+ );++ let sql = "SELECT t1_id, (SELECT a FROM (select 1 as a) WHERE a = t1.t1_int) as t2_int from t1";+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let plan = dataframe.into_optimized_plan()?;++ let expected = vec![+ "Projection: t1.t1_id, (<subquery>) AS t2_int [t1_id:UInt32;N, t2_int:Int64]",+ " Subquery: [a:Int64]",+ " Projection: a [a:Int64]",+ " Filter: a = CAST(outer_ref(t1.t1_int) AS Int64) [a:Int64]",+ " Projection: Int64(1) AS a [a:Int64]",+ " EmptyRelation []",+ " TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",+ ];+ let formatted = plan.display_indent_schema().to_string();+ let actual: Vec<&str> = formatted.trim().lines().collect();+ assert_eq!(+ expected, actual,+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"+ );++ Ok(())+}++#[tokio::test]+async fn non_equal_correlated_scalar_subquery() -> Result<()> {+ let ctx = create_join_context("t1_id", "t2_id", true)?;++ let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id < t1.t1_id) as t2_sum from t1";+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let err = dataframe.into_optimized_plan().err().unwrap();++ assert_eq!(+ r#"Context("check_analyzed_plan", Plan("Correlated column is not allowed in predicate: t2.t2_id < outer_ref(t1.t1_id)"))"#,+ &format!("{err:?}")+ );++ Ok(())+}++#[tokio::test]+async fn aggregated_correlated_scalar_subquery() -> Result<()> {+ let ctx = create_join_context("t1_id", "t2_id", true)?;++ let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id) as t2_sum from t1";+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let plan = dataframe.into_optimized_plan()?;++ let expected = vec![+ "Projection: t1.t1_id, (<subquery>) AS t2_sum [t1_id:UInt32;N, t2_sum:UInt64;N]",+ " Subquery: [SUM(t2.t2_int):UInt64;N]",+ " Projection: SUM(t2.t2_int) [SUM(t2.t2_int):UInt64;N]",+ " Aggregate: groupBy=[[]], aggr=[[SUM(t2.t2_int)]] [SUM(t2.t2_int):UInt64;N]",+ " Filter: t2.t2_id = outer_ref(t1.t1_id) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",+ " TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",+ " TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",+ ];+ let formatted = plan.display_indent_schema().to_string();+ let actual: Vec<&str> = formatted.trim().lines().collect();+ assert_eq!(+ expected, actual,+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"+ );++ Ok(())+}++#[tokio::test]+async fn aggregated_correlated_scalar_subquery_with_extra_group_by_columns() -> Result<()>+{+ let ctx = create_join_context("t1_id", "t2_id", true)?;++ let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id group by t2_name) as t2_sum from t1";+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let err = dataframe.into_optimized_plan().err().unwrap();++ assert_eq!(+ r#"Context("check_analyzed_plan", Plan("A GROUP BY clause in a scalar correlated subquery cannot contain non-correlated columns"))"#,+ &format!("{err:?}")+ );++ Ok(())+}++#[tokio::test]+async fn aggregated_correlated_scalar_subquery_with_extra_group_by_constant() -> Result<()>+{+ let ctx = create_join_context("t1_id", "t2_id", true)?;++ let sql = "SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id group by t2_id, 'a') as t2_sum from t1";+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let plan = dataframe.into_optimized_plan()?;++ let expected = vec![+ "Projection: t1.t1_id, (<subquery>) AS t2_sum [t1_id:UInt32;N, t2_sum:UInt64;N]",+ " Subquery: [SUM(t2.t2_int):UInt64;N]",+ " Projection: SUM(t2.t2_int) [SUM(t2.t2_int):UInt64;N]",+ " Aggregate: groupBy=[[t2.t2_id, Utf8(\"a\")]], aggr=[[SUM(t2.t2_int)]] [t2_id:UInt32;N, Utf8(\"a\"):Utf8, SUM(t2.t2_int):UInt64;N]",+ " Filter: t2.t2_id = outer_ref(t1.t1_id) [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",+ " TableScan: t2 [t2_id:UInt32;N, t2_name:Utf8;N, t2_int:UInt32;N]",+ " TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",+ ];+ let formatted = plan.display_indent_schema().to_string();+ let actual: Vec<&str> = formatted.trim().lines().collect();+ assert_eq!(+ expected, actual,+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"+ );++ Ok(())+}++#[tokio::test]+async fn group_by_correlated_scalar_subquery() -> Result<()> {+ let ctx = create_join_context("t1_id", "t2_id", true)?;+ let sql = "SELECT sum(t1_int) from t1 GROUP BY (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id)";++ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let err = dataframe.into_optimized_plan().err().unwrap();++ assert_eq!(+ r#"Context("check_analyzed_plan", Plan("Correlated scalar subquery in the GROUP BY clause must also be in the aggregate expressions"))"#,&format!("{err:?}"));diff --git a/datafusion/expr/src/expr_fn.rs b/datafusion/expr/src/expr_fn.rsindex 99ecfd4abe..a233ce8260 100644--- a/datafusion/expr/src/expr_fn.rs+++ b/datafusion/expr/src/expr_fn.rs@@ -47,6 +47,12 @@ pub fn col(ident: impl Into<Column>) -> Expr {Expr::Column(ident.into())}+/// Create an out reference column which hold a reference that has been resolved to a field+/// outside of the current plan.+pub fn out_ref_col(dt: DataType, ident: impl Into<Column>) -> Expr {+ Expr::OuterReferenceColumn(dt, ident.into())+}+/// Create an unqualified column expression from the provided name, without normalizing/// the column.///@@ -304,10 +310,11 @@ pub fn approx_percentile_cont_with_weight(/// Create an EXISTS subquery expressionpub fn exists(subquery: Arc<LogicalPlan>) -> Expr {+ let outer_ref_columns = subquery.all_out_ref_exprs();Expr::Exists {subquery: Subquery {subquery,- outer_ref_columns: vec![],+ outer_ref_columns,},negated: false,}@@ -315,10 +322,11 @@ pub fn exists(subquery: Arc<LogicalPlan>) -> Expr {/// Create a NOT EXISTS subquery expressionpub fn not_exists(subquery: Arc<LogicalPlan>) -> Expr {+ let outer_ref_columns = subquery.all_out_ref_exprs();Expr::Exists {subquery: Subquery {subquery,- outer_ref_columns: vec![],+ outer_ref_columns,},negated: true,}@@ -326,11 +334,12 @@ pub fn not_exists(subquery: Arc<LogicalPlan>) -> Expr {/// Create an IN subquery expressionpub fn in_subquery(expr: Expr, subquery: Arc<LogicalPlan>) -> Expr {+ let outer_ref_columns = subquery.all_out_ref_exprs();Expr::InSubquery {expr: Box::new(expr),subquery: Subquery {subquery,- outer_ref_columns: vec![],+ outer_ref_columns,},negated: false,}@@ -338,11 +347,12 @@ pub fn in_subquery(expr: Expr, subquery: Arc<LogicalPlan>) -> Expr {/// Create a NOT IN subquery expressionpub fn not_in_subquery(expr: Expr, subquery: Arc<LogicalPlan>) -> Expr {+ let outer_ref_columns = subquery.all_out_ref_exprs();Expr::InSubquery {expr: Box::new(expr),subquery: Subquery {subquery,- outer_ref_columns: vec![],+ outer_ref_columns,},negated: true,}@@ -350,9 +360,10 @@ pub fn not_in_subquery(expr: Expr, subquery: Arc<LogicalPlan>) -> Expr {/// Create a scalar subquery expressionpub fn scalar_subquery(subquery: Arc<LogicalPlan>) -> Expr {+ let outer_ref_columns = subquery.all_out_ref_exprs();Expr::ScalarSubquery(Subquery {subquery,- outer_ref_columns: vec![],+ outer_ref_columns,})}diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rsindex b04a8d59a8..3dcd61667a 100644--- a/datafusion/expr/src/logical_plan/plan.rs+++ b/datafusion/expr/src/logical_plan/plan.rs@@ -484,6 +484,104 @@ impl LogicalPlan {_ => Ok(self),}}++ /// Returns the maximum number of rows that this plan can output, if known.+ ///+ /// If `None`, the plan can return any number of rows.+ /// If `Some(n)` then the plan can return at most `n` rows but may return fewer.+ pub fn max_rows(self: &LogicalPlan) -> Option<usize> {+ match self {+ LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),+ LogicalPlan::Filter(Filter { input, .. }) => input.max_rows(),+ LogicalPlan::Window(Window { input, .. }) => input.max_rows(),+ LogicalPlan::Aggregate(Aggregate {+ input, group_expr, ..+ }) => {+ // Empty group_expr will return Some(1)+ if group_expr+ .iter()+ .all(|expr| matches!(expr, Expr::Literal(_)))+ {+ Some(1)+ } else {+ input.max_rows()+ }+ }+ LogicalPlan::Sort(Sort { input, fetch, .. }) => {+ match (fetch, input.max_rows()) {+ (Some(fetch_limit), Some(input_max)) => {+ Some(input_max.min(*fetch_limit))+ }+ (Some(fetch_limit), None) => Some(*fetch_limit),+ (None, Some(input_max)) => Some(input_max),+ (None, None) => None,+ }+ }+ LogicalPlan::Join(Join {+ left,+ right,+ join_type,+ ..+ }) => match join_type {+ JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {+ match (left.max_rows(), right.max_rows()) {+ (Some(left_max), Some(right_max)) => {+ let min_rows = match join_type {+ JoinType::Left => left_max,+ JoinType::Right => right_max,+ JoinType::Full => left_max + right_max,+ _ => 0,+ };+ Some((left_max * right_max).max(min_rows))+ }+ _ => None,+ }+ }+ JoinType::LeftSemi | JoinType::LeftAnti => left.max_rows(),+ JoinType::RightSemi | JoinType::RightAnti => right.max_rows(),+ },+ LogicalPlan::CrossJoin(CrossJoin { left, right, .. }) => {+ match (left.max_rows(), right.max_rows()) {+ (Some(left_max), Some(right_max)) => Some(left_max * right_max),+ _ => None,+ }+ }+ LogicalPlan::Repartition(Repartition { input, .. }) => input.max_rows(),+ LogicalPlan::Union(Union { inputs, .. }) => inputs+ .iter()+ .map(|plan| plan.max_rows())+ .try_fold(0usize, |mut acc, input_max| {+ if let Some(i_max) = input_max {+ acc += i_max;+ Some(acc)+ } else {+ None+ }+ }),+ LogicalPlan::TableScan(TableScan { fetch, .. }) => *fetch,+ LogicalPlan::EmptyRelation(_) => Some(0),+ LogicalPlan::Subquery(_) => None,+ LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => input.max_rows(),+ LogicalPlan::Limit(Limit { fetch, .. }) => *fetch,+ LogicalPlan::Distinct(Distinct { input }) => input.max_rows(),+ LogicalPlan::Values(v) => Some(v.values.len()),+ LogicalPlan::Unnest(_) => None,+ LogicalPlan::CreateMemoryTable(_)+ | LogicalPlan::CreateExternalTable(_)+ | LogicalPlan::CreateView(_)+ | LogicalPlan::CreateCatalogSchema(_)+ | LogicalPlan::CreateCatalog(_)+ | LogicalPlan::DropTable(_)+ | LogicalPlan::DropView(_)+ | LogicalPlan::Explain(_)+ | LogicalPlan::Analyze(_)+ | LogicalPlan::Dml(_)+ | LogicalPlan::DescribeTable(_)+ | LogicalPlan::Prepare(_)+ | LogicalPlan::Statement(_)+ | LogicalPlan::Extension(_) => None,+ }+ }}impl LogicalPlan {diff --git a/datafusion/optimizer/src/analyzer/count_wildcard_rule.rs b/datafusion/optimizer/src/analyzer/count_wildcard_rule.rsindex a7dc79374e..6fdb6b33f2 100644--- a/datafusion/optimizer/src/analyzer/count_wildcard_rule.rs+++ b/datafusion/optimizer/src/analyzer/count_wildcard_rule.rs@@ -260,12 +260,13 @@ fn rewrite_schema(schema: &DFSchema) -> DFSchemaRef {mod tests {use super::*;use crate::test::*;+ use arrow::datatypes::DataType;use datafusion_common::{Result, ScalarValue};use datafusion_expr::expr::Sort;use datafusion_expr::{col, count, exists, expr, in_subquery, lit, logical_plan::LogicalPlanBuilder,- max, scalar_subquery, AggregateFunction, Expr, WindowFrame, WindowFrameBound,- WindowFrameUnits, WindowFunction,+ max, out_ref_col, scalar_subquery, AggregateFunction, Expr, WindowFrame,+ WindowFrameBound, WindowFrameUnits, WindowFunction,};fn assert_plan_eq(plan: &LogicalPlan, expected: &str) -> Result<()> {@@ -349,7 +350,7 @@ mod tests {.filter(scalar_subquery(Arc::new(LogicalPlanBuilder::from(table_scan_t2)- .filter(col("t1.a").eq(col("t2.a")))?+ .filter(out_ref_col(DataType::UInt32, "t1.a").eq(col("t2.a")))?.aggregate(Vec::<Expr>::new(),vec![count(lit(COUNT_STAR_EXPANSION))],@@ -367,7 +368,7 @@ mod tests {\n Subquery: [COUNT(UInt8(1)):Int64;N]\\n Projection: COUNT(UInt8(1)) [COUNT(UInt8(1)):Int64;N]\\n Aggregate: groupBy=[[]], aggr=[[COUNT(UInt8(1))]] [COUNT(UInt8(1)):Int64;N]\- \n Filter: t1.a = t2.a [a:UInt32, b:UInt32, c:UInt32]\+ \n Filter: outer_ref(t1.a) = t2.a [a:UInt32, b:UInt32, c:UInt32]\\n TableScan: t2 [a:UInt32, b:UInt32, c:UInt32]\\n TableScan: t1 [a:UInt32, b:UInt32, c:UInt32]";assert_plan_eq(&plan, expected)diff --git a/datafusion/optimizer/src/analyzer/mod.rs b/datafusion/optimizer/src/analyzer/mod.rsindex dabd331ee1..3ad00c8185 100644--- a/datafusion/optimizer/src/analyzer/mod.rs+++ b/datafusion/optimizer/src/analyzer/mod.rs@@ -17,11 +17,13 @@pub mod count_wildcard_rule;pub mod inline_table_scan;+pub mod subquery;pub mod type_coercion;use crate::analyzer::count_wildcard_rule::CountWildcardRule;use crate::analyzer::inline_table_scan::InlineTableScan;+use crate::analyzer::subquery::check_subquery_expr;use crate::analyzer::type_coercion::TypeCoercion;use crate::utils::log_plan;use datafusion_common::config::ConfigOptions;@@ -131,114 +133,3 @@ fn check_plan(plan: &LogicalPlan) -> Result<()> {Ok(())}--/// Do necessary check on subquery expressions and fail the invalid plan-/// 1) Check whether the outer plan is in the allowed outer plans list to use subquery expressions,-/// the allowed while list: [Projection, Filter, Window, Aggregate, Sort, Join].-/// 2) Check whether the inner plan is in the allowed inner plans list to use correlated(outer) expressions.-/// 3) Check and validate unsupported cases to use the correlated(outer) expressions inside the subquery(inner) plans/inner expressions.-/// For example, we do not want to support to use correlated expressions as the Join conditions in the subquery plan when the Join-/// is a Full Out Join-fn check_subquery_expr(- outer_plan: &LogicalPlan,- inner_plan: &LogicalPlan,- expr: &Expr,-) -> Result<()> {- check_plan(inner_plan)?;-- // Scalar subquery should only return one column- if matches!(expr, Expr::ScalarSubquery(subquery) if subquery.subquery.schema().fields().len() > 1)- {- return Err(DataFusionError::Plan(- "Scalar subquery should only return one column".to_string(),- ));- }-- match outer_plan {- LogicalPlan::Projection(_)- | LogicalPlan::Filter(_)- | LogicalPlan::Window(_)- | LogicalPlan::Aggregate(_)- | LogicalPlan::Join(_) => Ok(()),- LogicalPlan::Sort(_) => match expr {- Expr::InSubquery { .. } | Expr::Exists { .. } => Err(DataFusionError::Plan(- "In/Exist subquery can not be used in Sort plan nodes".to_string(),- )),- Expr::ScalarSubquery(_) => Ok(()),- _ => Ok(()),- },- _ => Err(DataFusionError::Plan(- "Subquery can only be used in Projection, Filter, \- Window functions, Aggregate, Sort and Join plan nodes"- .to_string(),- )),- }?;- check_correlations_in_subquery(outer_plan, inner_plan, expr, true)-}--// Recursively check the unsupported outer references in the sub query plan.-fn check_correlations_in_subquery(- outer_plan: &LogicalPlan,- inner_plan: &LogicalPlan,- expr: &Expr,- can_contain_outer_ref: bool,-) -> Result<()> {- // We want to support as many operators as possible inside the correlated subquery- if !can_contain_outer_ref && contains_outer_reference(outer_plan, inner_plan, expr) {- return Err(DataFusionError::Plan(- "Accessing outer reference column is not allowed in the plan".to_string(),- ));- }- match inner_plan {- LogicalPlan::Projection(_)- | LogicalPlan::Filter(_)- | LogicalPlan::Window(_)- | LogicalPlan::Aggregate(_)- | LogicalPlan::Distinct(_)- | LogicalPlan::Sort(_)- | LogicalPlan::CrossJoin(_)- | LogicalPlan::Union(_)- | LogicalPlan::TableScan(_)- | LogicalPlan::EmptyRelation(_)- | LogicalPlan::Limit(_)- | LogicalPlan::Values(_)- | LogicalPlan::Subquery(_)- | LogicalPlan::SubqueryAlias(_) => {- inner_plan.apply_children(&mut |plan| {- check_correlations_in_subquery(- outer_plan,- plan,- expr,- can_contain_outer_ref,- )?;- Ok(VisitRecursion::Continue)- })?;- Ok(())- }- LogicalPlan::Join(_) => {- // TODO support correlation columns in the subquery join- inner_plan.apply_children(&mut |plan| {- check_correlations_in_subquery(- outer_plan,- plan,- expr,- can_contain_outer_ref,- )?;- Ok(VisitRecursion::Continue)- })?;- Ok(())- }- _ => Err(DataFusionError::Plan(- "Unsupported operator in the subquery plan.".to_string(),- )),- }-}--fn contains_outer_reference(- _outer_plan: &LogicalPlan,- _inner_plan: &LogicalPlan,- _expr: &Expr,-) -> bool {- // TODO check outer references- false-}diff --git a/datafusion/optimizer/src/analyzer/subquery.rs b/datafusion/optimizer/src/analyzer/subquery.rsnew file mode 100644index 0000000000..cdbe3f3050--- /dev/null+++ b/datafusion/optimizer/src/analyzer/subquery.rs@@ -0,0 +1,342 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++use crate::analyzer::check_plan;+use crate::utils::{collect_subquery_cols, split_conjunction};+use datafusion_common::tree_node::{TreeNode, VisitRecursion};+use datafusion_common::{DataFusionError, Result};+use datafusion_expr::expr_rewriter::strip_outer_reference;+use datafusion_expr::{+ Aggregate, BinaryExpr, Cast, Expr, Filter, Join, JoinType, LogicalPlan, Operator,+ Window,+};+use std::ops::Deref;++/// Do necessary check on subquery expressions and fail the invalid plan+/// 1) Check whether the outer plan is in the allowed outer plans list to use subquery expressions,+/// the allowed while list: [Projection, Filter, Window, Aggregate, Join].+/// 2) Check whether the inner plan is in the allowed inner plans list to use correlated(outer) expressions.+/// 3) Check and validate unsupported cases to use the correlated(outer) expressions inside the subquery(inner) plans/inner expressions.+/// For example, we do not want to support to use correlated expressions as the Join conditions in the subquery plan when the Join+/// is a Full Out Join+pub fn check_subquery_expr(+ outer_plan: &LogicalPlan,+ inner_plan: &LogicalPlan,+ expr: &Expr,+) -> Result<()> {+ check_plan(inner_plan)?;+ if let Expr::ScalarSubquery(subquery) = expr {+ // Scalar subquery should only return one column+ if subquery.subquery.schema().fields().len() > 1 {+ return Err(datafusion_common::DataFusionError::Plan(format!(+ "Scalar subquery should only return one column, but found {}: {}",+ subquery.subquery.schema().fields().len(),+ subquery.subquery.schema().field_names().join(", "),+ )));+ }+ // Correlated scalar subquery must be aggregated to return at most one row+ if !subquery.outer_ref_columns.is_empty() {+ match strip_inner_query(inner_plan) {+ LogicalPlan::Aggregate(agg) => {+ check_aggregation_in_scalar_subquery(inner_plan, agg)+ }+ LogicalPlan::Filter(Filter { input, .. })+ if matches!(input.as_ref(), LogicalPlan::Aggregate(_)) =>+ {+ if let LogicalPlan::Aggregate(agg) = input.as_ref() {+ check_aggregation_in_scalar_subquery(inner_plan, agg)+ } else {+ Ok(())+ }+ }+ _ => {+ if inner_plan+ .max_rows()+ .filter(|max_row| *max_row <= 1)+ .is_some()+ {+ Ok(())+ } else {+ Err(DataFusionError::Plan(+ "Correlated scalar subquery must be aggregated to return at most one row"+ .to_string(),+ ))+ }+ }+ }?;+ match outer_plan {+ LogicalPlan::Projection(_)+ | LogicalPlan::Filter(_) => Ok(()),+ LogicalPlan::Aggregate(Aggregate {group_expr, aggr_expr,..}) => {+ if group_expr.contains(expr) && !aggr_expr.contains(expr) {+ // TODO revisit this validation logic+ Err(DataFusionError::Plan(+ "Correlated scalar subquery in the GROUP BY clause must also be in the aggregate expressions"+ .to_string(),+ ))+ } else {+ Ok(())+ }+ },+ _ => Err(DataFusionError::Plan(+ "Correlated scalar subquery can only be used in Projection, Filter, Aggregate plan nodes"+ .to_string(),+ ))+ }?;+ }+ check_correlations_in_subquery(inner_plan, true)+ } else {+ match outer_plan {+ LogicalPlan::Projection(_)+ | LogicalPlan::Filter(_)+ | LogicalPlan::Window(_)+ | LogicalPlan::Aggregate(_)+ | LogicalPlan::Join(_) => Ok(()),+ _ => Err(DataFusionError::Plan(+ "In/Exist subquery can only be used in \+ Projection, Filter, Window functions, Aggregate and Join plan nodes"+ .to_string(),+ )),+ }?;+ check_correlations_in_subquery(inner_plan, false)+ }+}++// Recursively check the unsupported outer references in the sub query plan.+fn check_correlations_in_subquery(+ inner_plan: &LogicalPlan,+ is_scalar: bool,+) -> Result<()> {+ check_inner_plan(inner_plan, is_scalar, false, true)+}++// Recursively check the unsupported outer references in the sub query plan.+fn check_inner_plan(+ inner_plan: &LogicalPlan,+ is_scalar: bool,+ is_aggregate: bool,+ can_contain_outer_ref: bool,+) -> Result<()> {+ if !can_contain_outer_ref && contains_outer_reference(inner_plan) {+ return Err(DataFusionError::Plan(+ "Accessing outer reference columns is not allowed in the plan".to_string(),+ ));+ }+ // We want to support as many operators as possible inside the correlated subquery+ match inner_plan {+ LogicalPlan::Aggregate(_) => {+ inner_plan.apply_children(&mut |plan| {+ check_inner_plan(plan, is_scalar, true, can_contain_outer_ref)?;+ Ok(VisitRecursion::Continue)+ })?;+ Ok(())+ }+ LogicalPlan::Filter(Filter {+ predicate, input, ..+ }) => {+ let (correlated, _): (Vec<_>, Vec<_>) = split_conjunction(predicate)+ .into_iter()+ .partition(|e| e.contains_outer());+ let maybe_unsupport = correlated+ .into_iter()+ .filter(|expr| !can_pullup_over_aggregation(expr))+ .collect::<Vec<_>>();+ if is_aggregate && is_scalar && !maybe_unsupport.is_empty() {+ return Err(DataFusionError::Plan(format!(+ "Correlated column is not allowed in predicate: {:?}",+ predicate+ )));+ }+ check_inner_plan(input, is_scalar, is_aggregate, can_contain_outer_ref)+ }+ LogicalPlan::Window(window) => {+ check_mixed_out_refer_in_window(window)?;+ inner_plan.apply_children(&mut |plan| {+ check_inner_plan(plan, is_scalar, is_aggregate, can_contain_outer_ref)?;+ Ok(VisitRecursion::Continue)+ })?;+ Ok(())+ }+ LogicalPlan::Projection(_)+ | LogicalPlan::Distinct(_)+ | LogicalPlan::Sort(_)+ | LogicalPlan::CrossJoin(_)+ | LogicalPlan::Union(_)+ | LogicalPlan::TableScan(_)+ | LogicalPlan::EmptyRelation(_)+ | LogicalPlan::Limit(_)+ | LogicalPlan::Values(_)+ | LogicalPlan::Subquery(_)+ | LogicalPlan::SubqueryAlias(_) => {+ inner_plan.apply_children(&mut |plan| {+ check_inner_plan(plan, is_scalar, is_aggregate, can_contain_outer_ref)?;+ Ok(VisitRecursion::Continue)+ })?;+ Ok(())+ }+ LogicalPlan::Join(Join {+ left,+ right,+ join_type,+ ..+ }) => match join_type {+ JoinType::Inner => {+ inner_plan.apply_children(&mut |plan| {+ check_inner_plan(+ plan,+ is_scalar,+ is_aggregate,+ can_contain_outer_ref,+ )?;+ Ok(VisitRecursion::Continue)+ })?;+ Ok(())+ }+ JoinType::Left | JoinType::LeftSemi | JoinType::LeftAnti => {+ check_inner_plan(left, is_scalar, is_aggregate, can_contain_outer_ref)?;+ check_inner_plan(right, is_scalar, is_aggregate, false)+ }+ JoinType::Right | JoinType::RightSemi | JoinType::RightAnti => {+ check_inner_plan(left, is_scalar, is_aggregate, false)?;+ check_inner_plan(right, is_scalar, is_aggregate, can_contain_outer_ref)+ }+ JoinType::Full => {+ inner_plan.apply_children(&mut |plan| {+ check_inner_plan(plan, is_scalar, is_aggregate, false)?;+ Ok(VisitRecursion::Continue)+ })?;+ Ok(())+ }+ },+ _ => Err(DataFusionError::Plan(+ "Unsupported operator in the subquery plan.".to_string(),+ )),+ }+}++fn contains_outer_reference(inner_plan: &LogicalPlan) -> bool {+ inner_plan+ .expressions()+ .iter()+ .any(|expr| expr.contains_outer())+}++fn check_aggregation_in_scalar_subquery(+ inner_plan: &LogicalPlan,+ agg: &Aggregate,+) -> Result<()> {+ if agg.aggr_expr.is_empty() {+ return Err(DataFusionError::Plan(+ "Correlated scalar subquery must be aggregated to return at most one row"+ .to_string(),+ ));+ }+ if !agg.group_expr.is_empty() {+ let correlated_exprs = get_correlated_expressions(inner_plan)?;+ let inner_subquery_cols =+ collect_subquery_cols(&correlated_exprs, agg.input.schema().clone())?;+ let mut group_columns = agg+ .group_expr+ .iter()+ .map(|group| Ok(group.to_columns()?.into_iter().collect::<Vec<_>>()))+ .collect::<Result<Vec<_>>>()?+ .into_iter()+ .flatten();++ if !group_columns.all(|group| inner_subquery_cols.contains(&group)) {+ // Group BY columns must be a subset of columns in the correlated expressions+ return Err(DataFusionError::Plan(+ "A GROUP BY clause in a scalar correlated subquery cannot contain non-correlated columns"+ .to_string(),+ ));+ }+ }+ Ok(())+}++fn strip_inner_query(inner_plan: &LogicalPlan) -> &LogicalPlan {+ match inner_plan {+ LogicalPlan::Projection(projection) => {+ strip_inner_query(projection.input.as_ref())+ }+ LogicalPlan::SubqueryAlias(alias) => strip_inner_query(alias.input.as_ref()),+ other => other,+ }+}++fn get_correlated_expressions(inner_plan: &LogicalPlan) -> Result<Vec<Expr>> {+ let mut exprs = vec![];+ inner_plan.apply(&mut |plan| {+ if let LogicalPlan::Filter(Filter { predicate, .. }) = plan {+ let (correlated, _): (Vec<_>, Vec<_>) = split_conjunction(predicate)+ .into_iter()+ .partition(|e| e.contains_outer());++ correlated+ .into_iter()+ .for_each(|expr| exprs.push(strip_outer_reference(expr.clone())));+ return Ok(VisitRecursion::Continue);+ }+ Ok(VisitRecursion::Continue)+ })?;+ Ok(exprs)+}++/// Check whether the expression can pull up over the aggregation without change the result of the query+fn can_pullup_over_aggregation(expr: &Expr) -> bool {+ if let Expr::BinaryExpr(BinaryExpr {+ left,+ op: Operator::Eq,+ right,+ }) = expr+ {+ match (left.deref(), right.deref()) {+ (Expr::Column(_), right) if right.to_columns().unwrap().is_empty() => true,+ (left, Expr::Column(_)) if left.to_columns().unwrap().is_empty() => true,+ (Expr::Cast(Cast { expr, .. }), right)+ if matches!(expr.deref(), Expr::Column(_))+ && right.to_columns().unwrap().is_empty() =>+ {+ true+ }+ (left, Expr::Cast(Cast { expr, .. }))+ if matches!(expr.deref(), Expr::Column(_))+ && left.to_columns().unwrap().is_empty() =>+ {+ true+ }+ (_, _) => false,+ }+ } else {+ false+ }+}++/// Check whether the window expressions contain a mixture of out reference columns and inner columns+fn check_mixed_out_refer_in_window(window: &Window) -> Result<()> {+ let mixed = window.window_expr.iter().any(|win_expr| {+ win_expr.contains_outer() && !win_expr.to_columns().unwrap().is_empty()+ });+ if mixed {+ Err(DataFusionError::Plan(+ "Window expressions should not contain a mixed of outer references and inner columns"+ .to_string(),+ ))+ } else {+ Ok(())+ }+}diff --git a/datafusion/optimizer/src/decorrelate_where_exists.rs b/datafusion/optimizer/src/decorrelate_where_exists.rsindex 88117c6be9..aee38c26a1 100644--- a/datafusion/optimizer/src/decorrelate_where_exists.rs+++ b/datafusion/optimizer/src/decorrelate_where_exists.rs@@ -224,9 +224,10 @@ impl SubqueryInfo {mod tests {use super::*;use crate::test::*;+ use arrow::datatypes::DataType;use datafusion_common::Result;use datafusion_expr::{- col, exists, lit, logical_plan::LogicalPlanBuilder, not_exists,+ col, exists, lit, logical_plan::LogicalPlanBuilder, not_exists, out_ref_col,};use std::ops::Add;@@ -244,7 +245,10 @@ mod tests {fn multiple_subqueries() -> Result<()> {let orders = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("orders.o_custkey").eq(col("customer.c_custkey")))?+ .filter(+ col("orders.o_custkey")+ .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),+ )?.project(vec![col("orders.o_custkey")])?.build()?,);@@ -270,7 +274,10 @@ mod tests {fn recursive_subqueries() -> Result<()> {let lineitem = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("lineitem"))- .filter(col("lineitem.l_orderkey").eq(col("orders.o_orderkey")))?+ .filter(+ col("lineitem.l_orderkey")+ .eq(out_ref_col(DataType::Int64, "orders.o_orderkey")),+ )?.project(vec![col("lineitem.l_orderkey")])?.build()?,);@@ -278,8 +285,10 @@ mod tests {let orders = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders")).filter(- exists(lineitem)- .and(col("orders.o_custkey").eq(col("customer.c_custkey"))),+ exists(lineitem).and(+ col("orders.o_custkey")+ .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),+ ),)?.project(vec![col("orders.o_custkey")])?.build()?,@@ -307,7 +316,7 @@ mod tests {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders")).filter(- col("customer.c_custkey")+ out_ref_col(DataType::Int64, "customer.c_custkey").eq(col("orders.o_custkey")).and(col("o_orderkey").eq(lit(1))),)?@@ -334,7 +343,7 @@ mod tests {fn exists_subquery_no_cols() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(lit(1u32)))?+ .filter(out_ref_col(DataType::Int64, "customer.c_custkey").eq(lit(1u32)))?.project(vec![col("orders.o_custkey")])?.build()?,);@@ -377,7 +386,10 @@ mod tests {fn exists_subquery_where_not_eq() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").not_eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .not_eq(col("orders.o_custkey")),+ )?.project(vec![col("orders.o_custkey")])?.build()?,);@@ -401,7 +413,10 @@ mod tests {fn exists_subquery_where_less_than() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").lt(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .lt(col("orders.o_custkey")),+ )?.project(vec![col("orders.o_custkey")])?.build()?,);@@ -426,7 +441,7 @@ mod tests {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders")).filter(- col("customer.c_custkey")+ out_ref_col(DataType::Int64, "customer.c_custkey").eq(col("orders.o_custkey")).or(col("o_orderkey").eq(lit(1))),)?@@ -470,7 +485,10 @@ mod tests {fn exists_subquery_project_expr() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .eq(col("orders.o_custkey")),+ )?.project(vec![col("orders.o_custkey").add(lit(1))])?.build()?,);@@ -494,7 +512,10 @@ mod tests {fn should_support_additional_filters() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .eq(col("orders.o_custkey")),+ )?.project(vec![col("orders.o_custkey")])?.build()?,);@@ -545,7 +566,7 @@ mod tests {fn exists_subquery_correlated() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)- .filter(col("test.a").eq(col("sq.a")))?+ .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?.project(vec![col("c")])?.build()?,);@@ -595,12 +616,12 @@ mod tests {let subquery_scan2 = test_table_scan_with_name("sq2")?;let subquery1 = LogicalPlanBuilder::from(subquery_scan1)- .filter(col("test.a").eq(col("sq1.a")))?+ .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq1.a")))?.project(vec![col("c")])?.build()?;let subquery2 = LogicalPlanBuilder::from(subquery_scan2)- .filter(col("test.a").eq(col("sq2.a")))?+ .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq2.a")))?.project(vec![col("c")])?.build()?;@@ -630,7 +651,10 @@ mod tests {let table_scan = test_table_scan()?;let subquery_scan = test_table_scan_with_name("sq")?;let subquery = LogicalPlanBuilder::from(subquery_scan)- .filter((lit(1u32) + col("sq.a")).gt(col("test.a") * lit(2u32)))?+ .filter(+ (lit(1u32) + col("sq.a"))+ .gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),+ )?.project(vec![lit(1u32)])?.build()?;let plan = LogicalPlanBuilder::from(table_scan)@@ -678,7 +702,10 @@ mod tests {let table_scan = test_table_scan()?;let subquery_scan = test_table_scan_with_name("sq")?;let subquery = LogicalPlanBuilder::from(subquery_scan)- .filter((lit(1u32) + col("sq.a")).gt(col("test.a") * lit(2u32)))?+ .filter(+ (lit(1u32) + col("sq.a"))+ .gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),+ )?.project(vec![col("sq.c")])?.distinct()?.build()?;@@ -702,7 +729,10 @@ mod tests {let table_scan = test_table_scan()?;let subquery_scan = test_table_scan_with_name("sq")?;let subquery = LogicalPlanBuilder::from(subquery_scan)- .filter((lit(1u32) + col("sq.a")).gt(col("test.a") * lit(2u32)))?+ .filter(+ (lit(1u32) + col("sq.a"))+ .gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),+ )?.project(vec![col("sq.b") + col("sq.c")])?.distinct()?.build()?;@@ -726,7 +756,10 @@ mod tests {let table_scan = test_table_scan()?;let subquery_scan = test_table_scan_with_name("sq")?;let subquery = LogicalPlanBuilder::from(subquery_scan)- .filter((lit(1u32) + col("sq.a")).gt(col("test.a") * lit(2u32)))?+ .filter(+ (lit(1u32) + col("sq.a"))+ .gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),+ )?.project(vec![lit(1u32), col("sq.c")])?.distinct()?.build()?;diff --git a/datafusion/optimizer/src/decorrelate_where_in.rs b/datafusion/optimizer/src/decorrelate_where_in.rsindex c4d46d93c0..6dbbbf9bf9 100644--- a/datafusion/optimizer/src/decorrelate_where_in.rs+++ b/datafusion/optimizer/src/decorrelate_where_in.rs@@ -19,15 +19,14 @@ use crate::alias::AliasGenerator;use crate::optimizer::ApplyOrder;use crate::utils::{collect_subquery_cols, conjunction, extract_join_filters, only_or_err,- split_conjunction,+ replace_qualified_name, split_conjunction,};use crate::{OptimizerConfig, OptimizerRule};use datafusion_common::{context, Column, Result};-use datafusion_expr::expr_rewriter::{replace_col, unnormalize_col};+use datafusion_expr::expr_rewriter::unnormalize_col;use datafusion_expr::logical_plan::{JoinType, Projection, Subquery};use datafusion_expr::{Expr, Filter, LogicalPlan, LogicalPlanBuilder};use log::debug;-use std::collections::{BTreeSet, HashMap};use std::sync::Arc;#[derive(Default)]@@ -234,23 +233,6 @@ fn remove_duplicated_filter(filters: Vec<Expr>, in_predicate: Expr) -> Vec<Expr>.collect::<Vec<_>>()}-fn replace_qualified_name(- expr: Expr,- cols: &BTreeSet<Column>,- subquery_alias: &str,-) -> Result<Expr> {- let alias_cols: Vec<Column> = cols- .iter()- .map(|col| {- Column::from_qualified_name(format!("{}.{}", subquery_alias, col.name))- })- .collect();- let replace_map: HashMap<&Column, &Column> =- cols.iter().zip(alias_cols.iter()).collect();-- replace_col(expr, &replace_map)-}-struct SubqueryInfo {query: Subquery,where_in_expr: Expr,@@ -271,10 +253,11 @@ impl SubqueryInfo {mod tests {use super::*;use crate::test::*;+ use arrow::datatypes::DataType;use datafusion_common::Result;use datafusion_expr::{and, binary_expr, col, in_subquery, lit, logical_plan::LogicalPlanBuilder,- not_in_subquery, or, Operator,+ not_in_subquery, or, out_ref_col, Operator,};use std::ops::Add;@@ -474,7 +457,10 @@ mod tests {fn multiple_subqueries() -> Result<()> {let orders = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("orders.o_custkey").eq(col("customer.c_custkey")))?+ .filter(+ col("orders.o_custkey")+ .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),+ )?.project(vec![col("orders.o_custkey")])?.build()?,);@@ -512,7 +498,10 @@ mod tests {fn recursive_subqueries() -> Result<()> {let lineitem = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("lineitem"))- .filter(col("lineitem.l_orderkey").eq(col("orders.o_orderkey")))?+ .filter(+ col("lineitem.l_orderkey")+ .eq(out_ref_col(DataType::Int64, "orders.o_orderkey")),+ )?.project(vec![col("lineitem.l_orderkey")])?.build()?,);@@ -520,8 +509,10 @@ mod tests {let orders = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders")).filter(- in_subquery(col("orders.o_orderkey"), lineitem)- .and(col("orders.o_custkey").eq(col("customer.c_custkey"))),+ in_subquery(col("orders.o_orderkey"), lineitem).and(+ col("orders.o_custkey")+ .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),+ ),)?.project(vec![col("orders.o_custkey")])?.build()?,@@ -557,7 +548,7 @@ mod tests {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders")).filter(- col("customer.c_custkey")+ out_ref_col(DataType::Int64, "customer.c_custkey").eq(col("orders.o_custkey")).and(col("o_orderkey").eq(lit(1))),)?@@ -591,7 +582,10 @@ mod tests {fn in_subquery_no_cols() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(col("customer.c_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),+ )?.project(vec![col("orders.o_custkey")])?.build()?,);@@ -602,7 +596,7 @@ mod tests {.build()?;let expected = "Projection: customer.c_custkey [c_custkey:Int64]\- \n LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey AND customer.c_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8]\+ \n LeftSemi Join: Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]\\n TableScan: customer [c_custkey:Int64, c_name:Utf8]\\n SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]\\n Projection: orders.o_custkey AS o_custkey [o_custkey:Int64]\@@ -652,7 +646,10 @@ mod tests {fn in_subquery_where_not_eq() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").not_eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .not_eq(col("orders.o_custkey")),+ )?.project(vec![col("orders.o_custkey")])?.build()?,);@@ -682,7 +679,10 @@ mod tests {fn in_subquery_where_less_than() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").lt(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .lt(col("orders.o_custkey")),+ )?.project(vec![col("orders.o_custkey")])?.build()?,);@@ -713,7 +713,7 @@ mod tests {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders")).filter(- col("customer.c_custkey")+ out_ref_col(DataType::Int64, "customer.c_custkey").eq(col("orders.o_custkey")).or(col("o_orderkey").eq(lit(1))),)?@@ -770,7 +770,10 @@ mod tests {fn in_subquery_join_expr() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .eq(col("orders.o_custkey")),+ )?.project(vec![col("orders.o_custkey")])?.build()?,);@@ -800,7 +803,10 @@ mod tests {fn in_subquery_project_expr() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .eq(col("orders.o_custkey")),+ )?.project(vec![col("orders.o_custkey").add(lit(1))])?.build()?,);@@ -830,7 +836,10 @@ mod tests {fn in_subquery_multi_col() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .eq(col("orders.o_custkey")),+ )?.project(vec![col("orders.o_custkey"), col("orders.o_orderkey")])?.build()?,);@@ -856,7 +865,10 @@ mod tests {fn should_support_additional_filters() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .eq(col("orders.o_custkey")),+ )?.project(vec![col("orders.o_custkey")])?.build()?,);@@ -890,7 +902,10 @@ mod tests {fn in_subquery_disjunction() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .eq(col("orders.o_custkey")),+ )?.project(vec![col("orders.o_custkey")])?.build()?,);@@ -908,7 +923,7 @@ mod tests {Filter: customer.c_custkey IN (<subquery>) OR customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8]Subquery: [o_custkey:Int64]Projection: orders.o_custkey [o_custkey:Int64]- Filter: customer.c_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]+ Filter: outer_ref(customer.c_custkey) = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]TableScan: customer [c_custkey:Int64, c_name:Utf8]"#;@@ -925,7 +940,7 @@ mod tests {fn in_subquery_correlated() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)- .filter(col("test.a").eq(col("sq.a")))?+ .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?.project(vec![col("c")])?.build()?,);@@ -1034,7 +1049,7 @@ mod tests {let subquery = LogicalPlanBuilder::from(subquery_scan).filter(- col("test.a")+ out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")).and(col("sq.a").add(lit(1u32)).eq(col("sq.b"))),)?@@ -1069,8 +1084,8 @@ mod tests {let subquery = LogicalPlanBuilder::from(subquery_scan).filter(- col("test.a")- .add(col("test.b"))+ out_ref_col(DataType::UInt32, "test.a")+ .add(out_ref_col(DataType::UInt32, "test.b")).eq(col("sq.a").add(col("sq.b"))).and(col("sq.a").add(lit(1u32)).eq(col("sq.b"))),)?@@ -1105,12 +1120,12 @@ mod tests {let subquery_scan2 = test_table_scan_with_name("sq2")?;let subquery1 = LogicalPlanBuilder::from(subquery_scan1)- .filter(col("test.a").gt(col("sq1.a")))?+ .filter(out_ref_col(DataType::UInt32, "test.a").gt(col("sq1.a")))?.project(vec![col("c") * lit(2u32)])?.build()?;let subquery2 = LogicalPlanBuilder::from(subquery_scan2)- .filter(col("test.a").gt(col("sq2.a")))?+ .filter(out_ref_col(DataType::UInt32, "test.a").gt(col("sq2.a")))?.project(vec![col("c") * lit(2u32)])?.build()?;diff --git a/datafusion/optimizer/src/scalar_subquery_to_join.rs b/datafusion/optimizer/src/scalar_subquery_to_join.rsindex d88aca32cb..dfaa17213b 100644--- a/datafusion/optimizer/src/scalar_subquery_to_join.rs+++ b/datafusion/optimizer/src/scalar_subquery_to_join.rs@@ -18,13 +18,13 @@use crate::alias::AliasGenerator;use crate::optimizer::ApplyOrder;use crate::utils::{- conjunction, exprs_to_join_cols, find_join_exprs, only_or_err, split_conjunction,- verify_not_disjunction,+ collect_subquery_cols, conjunction, extract_join_filters, only_or_err,+ replace_qualified_name, split_conjunction,};use crate::{OptimizerConfig, OptimizerRule};-use datafusion_common::{context, plan_err, Column, Result};+use datafusion_common::{context, Column, Result};use datafusion_expr::expr::BinaryExpr;-use datafusion_expr::logical_plan::{Filter, JoinType, Limit, Subquery};+use datafusion_expr::logical_plan::{JoinType, Subquery};use datafusion_expr::{Expr, LogicalPlan, LogicalPlanBuilder, Operator};use log::debug;use std::sync::Arc;@@ -162,8 +162,7 @@ impl OptimizerRule for ScalarSubqueryToJoin {////// ```text/// select c.id from customers c-/// cross join (select avg(total) as val from orders) a-/// where c.balance > a.val+/// inner join (select avg(total) as val from orders) a on (c.balance > a.val)/// ```////// # Arguments@@ -186,13 +185,9 @@ fn optimize_scalar();let proj = match &subquery {LogicalPlan::Projection(proj) => proj,- LogicalPlan::Limit(Limit {- skip: 0,- fetch: Some(1),- ..- }) => return plan_err!("Scalar subqueries with LIMIT 1 are not yet supported"),_ => {// this rule does not support this type of scalar subquery+ // TODO support more typesdebug!("cannot translate this type of scalar subquery to a join: {}",subquery.display_indent()@@ -211,6 +206,7 @@ fn optimize_scalar(LogicalPlan::Aggregate(aggr) => aggr,_ => {// this rule does not support this type of scalar subquery+ // TODO support more typesdebug!("cannot translate this type of scalar subquery to a join: {}",subquery.display_indent()@@ -218,44 +214,22 @@ fn optimize_scalar(return Ok(None);}};- let filter = Filter::try_from_plan(&aggr.input).ok();-- // if there were filters, we use that logical plan, otherwise the plan from the aggregate- let input = if let Some(filter) = filter {- &filter.input- } else {- &aggr.input- };-- // if there were filters, split and capture them- let subqry_filter_exprs = if let Some(filter) = filter {- split_conjunction(&filter.predicate)- } else {- vec![]- };- verify_not_disjunction(&subqry_filter_exprs)?;-- // Grab column names to join on- let (col_exprs, other_subqry_exprs) =- find_join_exprs(subqry_filter_exprs, input.schema())?;- let (mut outer_cols, subqry_cols, join_filters) =- exprs_to_join_cols(&col_exprs, input.schema(), false)?;- if join_filters.is_some() {- plan_err!("only joins on column equality are presently supported")?;- }+ // extract join filters+ let (join_filters, subquery_input) = extract_join_filters(&aggr.input)?;// Only operate if one column is present and the other closed upon from outside scopelet subqry_alias = alias.next("__scalar_sq");+ let input_schema = subquery_input.schema();+ let subqry_cols = collect_subquery_cols(&join_filters, input_schema.clone())?;+ let join_filter = conjunction(join_filters).map_or(Ok(None), |filter| {+ replace_qualified_name(filter, &subqry_cols, &subqry_alias).map(Option::Some)+ })?;+let group_by: Vec<_> = subqry_cols.iter().map(|it| Expr::Column(it.clone())).collect();-- // build subquery side of join - the thing the subquery was querying- let mut subqry_plan = LogicalPlanBuilder::from((**input).clone());- if let Some(expr) = conjunction(other_subqry_exprs) {- subqry_plan = subqry_plan.filter(expr)? // if the subquery had additional expressions, restore them- }+ let subqry_plan = LogicalPlanBuilder::from(subquery_input);// project the prior projection + any correlated (and now grouped) columnslet proj: Vec<_> = group_by@@ -269,36 +243,30 @@ fn optimize_scalar(.alias(subqry_alias.clone())?.build()?;- // qualify the join columns for outside the subquery- let mut subqry_cols: Vec<_> = subqry_cols- .iter()- .map(|it| Column::new(Some(subqry_alias.clone()), it.name.clone()))- .collect();-let qry_expr = Expr::Column(Column::new(Some(subqry_alias), "__value".to_string()));// if correlated subquery's operation is column equality, put the clause into join on clause.let mut restore_where_clause = true;+ let mut outer_keys = vec![];+ let mut subquery_keys = vec![];if let (Operator::Eq, Expr::Column(column)) = (query_info.op, &query_info.expr) {// only do this optimization for correlated subquery- if !outer_cols.is_empty() {- outer_cols.push(column.clone());- subqry_cols.push(qry_expr.try_into_col().unwrap());+ if !query_info.query.outer_ref_columns.is_empty() {+ outer_keys.push(column.clone());+ subquery_keys.push(qry_expr.try_into_col().unwrap());restore_where_clause = false;}}-- let join_keys = (outer_cols, subqry_cols);-+ let join_keys = (outer_keys, subquery_keys);// join our sub query into the main planlet new_plan = LogicalPlanBuilder::from(filter_input.clone());- let mut new_plan = if join_keys.0.is_empty() {+ let mut new_plan = if join_filter.is_none() && join_keys.0.is_empty() {// if not correlated, group down to 1 row and cross join on that (preserving row count)new_plan.cross_join(subqry_plan)?} else {// inner join if correlated, grouping by the join keys so we don't change row count- new_plan.join(subqry_plan, JoinType::Inner, join_keys, None)?+ new_plan.join(subqry_plan, JoinType::Inner, join_keys, join_filter)?};// restore where in condition@@ -348,10 +316,13 @@ impl SubqueryInfo {#[cfg(test)]mod tests {use super::*;+ use crate::extract_equijoin_predicate::ExtractEquijoinPredicate;use crate::test::*;+ use arrow::datatypes::DataType;use datafusion_common::Result;use datafusion_expr::{- col, lit, logical_plan::LogicalPlanBuilder, max, min, scalar_subquery, sum,+ col, lit, logical_plan::LogicalPlanBuilder, max, min, out_ref_col,+ scalar_subquery, sum,};use std::ops::Add;@@ -366,7 +337,10 @@ mod tests {fn multiple_subqueries() -> Result<()> {let orders = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("orders.o_custkey").eq(col("customer.c_custkey")))?+ .filter(+ col("orders.o_custkey")+ .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),+ )?.aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?.project(vec![max(col("orders.o_custkey"))])?.build()?,@@ -395,8 +369,11 @@ mod tests {\n Projection: orders.o_custkey, MAX(orders.o_custkey) AS __value [o_custkey:Int64, __value:Int64;N]\\n Aggregate: groupBy=[[orders.o_custkey]], aggr=[[MAX(orders.o_custkey)]] [o_custkey:Int64, MAX(orders.o_custkey):Int64;N]\\n TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]";- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);@@ -408,7 +385,10 @@ mod tests {fn recursive_subqueries() -> Result<()> {let lineitem = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("lineitem"))- .filter(col("lineitem.l_orderkey").eq(col("orders.o_orderkey")))?+ .filter(+ col("lineitem.l_orderkey")+ .eq(out_ref_col(DataType::Int64, "orders.o_orderkey")),+ )?.aggregate(Vec::<Expr>::new(),vec![sum(col("lineitem.l_extendedprice"))],@@ -421,7 +401,7 @@ mod tests {LogicalPlanBuilder::from(scan_tpch_table("orders")).filter(col("orders.o_custkey")- .eq(col("customer.c_custkey"))+ .eq(out_ref_col(DataType::Int64, "customer.c_custkey")).and(col("orders.o_totalprice").lt(scalar_subquery(lineitem))),)?.aggregate(Vec::<Expr>::new(), vec![sum(col("orders.o_totalprice"))])?@@ -448,8 +428,11 @@ mod tests {\n Projection: lineitem.l_orderkey, SUM(lineitem.l_extendedprice) AS __value [l_orderkey:Int64, __value:Float64;N]\\n Aggregate: groupBy=[[lineitem.l_orderkey]], aggr=[[SUM(lineitem.l_extendedprice)]] [l_orderkey:Int64, SUM(lineitem.l_extendedprice):Float64;N]\\n TableScan: lineitem [l_orderkey:Int64, l_partkey:Int64, l_suppkey:Int64, l_linenumber:Int32, l_quantity:Float64, l_extendedprice:Float64]";- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);@@ -462,7 +445,7 @@ mod tests {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders")).filter(- col("customer.c_custkey")+ out_ref_col(DataType::Int64, "customer.c_custkey").eq(col("orders.o_custkey")).and(col("o_orderkey").eq(lit(1))),)?@@ -477,7 +460,7 @@ mod tests {.build()?;let expected = "Projection: customer.c_custkey [c_custkey:Int64]\- \n Inner Join: customer.c_custkey = __scalar_sq_1.o_custkey, customer.c_custkey = __scalar_sq_1.__value [c_custkey:Int64, c_name:Utf8, o_custkey:Int64, __value:Int64;N]\+ \n Inner Join: customer.c_custkey = __scalar_sq_1.__value, customer.c_custkey = __scalar_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8, o_custkey:Int64, __value:Int64;N]\\n TableScan: customer [c_custkey:Int64, c_name:Utf8]\\n SubqueryAlias: __scalar_sq_1 [o_custkey:Int64, __value:Int64;N]\\n Projection: orders.o_custkey, MAX(orders.o_custkey) AS __value [o_custkey:Int64, __value:Int64;N]\@@ -485,8 +468,11 @@ mod tests {\n Filter: orders.o_orderkey = Int32(1) [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]\\n TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]";- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);@@ -498,7 +484,10 @@ mod tests {fn scalar_subquery_no_cols() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(col("customer.c_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),+ )?.aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?.project(vec![max(col("orders.o_custkey"))])?.build()?,@@ -511,16 +500,17 @@ mod tests {// it will optimize, but fail for the same reason the unoptimized query wouldlet expected = "Projection: customer.c_custkey [c_custkey:Int64]\- \n Filter: customer.c_custkey = __scalar_sq_1.__value [c_custkey:Int64, c_name:Utf8, __value:Int64;N]\- \n CrossJoin: [c_custkey:Int64, c_name:Utf8, __value:Int64;N]\- \n TableScan: customer [c_custkey:Int64, c_name:Utf8]\- \n SubqueryAlias: __scalar_sq_1 [__value:Int64;N]\- \n Projection: MAX(orders.o_custkey) AS __value [__value:Int64;N]\- \n Aggregate: groupBy=[[]], aggr=[[MAX(orders.o_custkey)]] [MAX(orders.o_custkey):Int64;N]\- \n Filter: customer.c_custkey = customer.c_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]\- \n TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]";- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ \n Inner Join: customer.c_custkey = __scalar_sq_1.__value [c_custkey:Int64, c_name:Utf8, __value:Int64;N]\+ \n TableScan: customer [c_custkey:Int64, c_name:Utf8]\+ \n SubqueryAlias: __scalar_sq_1 [__value:Int64;N]\+ \n Projection: MAX(orders.o_custkey) AS __value [__value:Int64;N]\+ \n Aggregate: groupBy=[[]], aggr=[[MAX(orders.o_custkey)]] [MAX(orders.o_custkey):Int64;N]\+ \n TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]";+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);@@ -553,8 +543,11 @@ mod tests {\n Filter: orders.o_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]\\n TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]";- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);@@ -566,7 +559,10 @@ mod tests {fn scalar_subquery_where_not_eq() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").not_eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .not_eq(col("orders.o_custkey")),+ )?.aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?.project(vec![max(col("orders.o_custkey"))])?.build()?,@@ -577,9 +573,11 @@ mod tests {.project(vec![col("customer.c_custkey")])?.build()?;- let expected = r#"only joins on column equality are presently supported"#;+ let expected = "check_analyzed_plan\+ \ncaused by\+ \nError during planning: Correlated column is not allowed in predicate: outer_ref(customer.c_custkey) != orders.o_custkey";- assert_optimizer_err(Arc::new(ScalarSubqueryToJoin::new()), &plan, expected);+ assert_analyzer_check_err(vec![], &plan, expected);Ok(())}@@ -588,7 +586,10 @@ mod tests {fn scalar_subquery_where_less_than() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").lt(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .lt(col("orders.o_custkey")),+ )?.aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?.project(vec![max(col("orders.o_custkey"))])?.build()?,@@ -599,8 +600,11 @@ mod tests {.project(vec![col("customer.c_custkey")])?.build()?;- let expected = r#"can't optimize < column comparison"#;- assert_optimizer_err(Arc::new(ScalarSubqueryToJoin::new()), &plan, expected);+ let expected = "check_analyzed_plan\+ \ncaused by\+ \nError during planning: Correlated column is not allowed in predicate: outer_ref(customer.c_custkey) < orders.o_custkey";++ assert_analyzer_check_err(vec![], &plan, expected);Ok(())}@@ -610,7 +614,7 @@ mod tests {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders")).filter(- col("customer.c_custkey")+ out_ref_col(DataType::Int64, "customer.c_custkey").eq(col("orders.o_custkey")).or(col("o_orderkey").eq(lit(1))),)?@@ -624,8 +628,11 @@ mod tests {.project(vec![col("customer.c_custkey")])?.build()?;- let expected = r#"Optimizing disjunctions not supported!"#;- assert_optimizer_err(Arc::new(ScalarSubqueryToJoin::new()), &plan, expected);+ let expected = "check_analyzed_plan\+ \ncaused by\+ \nError during planning: Correlated column is not allowed in predicate: outer_ref(customer.c_custkey) = orders.o_custkey OR orders.o_orderkey = Int32(1)";++ assert_analyzer_check_err(vec![], &plan, expected);Ok(())}@@ -651,11 +658,19 @@ mod tests {TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]TableScan: customer [c_custkey:Int64, c_name:Utf8]"#;- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);++ let expected = "check_analyzed_plan\+ \ncaused by\+ \nError during planning: Scalar subquery should only return one column";+ assert_analyzer_check_err(vec![], &plan, expected);Ok(())}@@ -664,7 +679,10 @@ mod tests {fn scalar_subquery_project_expr() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .eq(col("orders.o_custkey")),+ )?.aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?.project(vec![col("MAX(orders.o_custkey)").add(lit(1))])?.build()?,@@ -676,15 +694,18 @@ mod tests {.build()?;let expected = "Projection: customer.c_custkey [c_custkey:Int64]\- \n Inner Join: customer.c_custkey = __scalar_sq_1.o_custkey, customer.c_custkey = __scalar_sq_1.__value [c_custkey:Int64, c_name:Utf8, o_custkey:Int64, __value:Int64;N]\+ \n Inner Join: customer.c_custkey = __scalar_sq_1.__value, customer.c_custkey = __scalar_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8, o_custkey:Int64, __value:Int64;N]\\n TableScan: customer [c_custkey:Int64, c_name:Utf8]\\n SubqueryAlias: __scalar_sq_1 [o_custkey:Int64, __value:Int64;N]\\n Projection: orders.o_custkey, MAX(orders.o_custkey) + Int32(1) AS __value [o_custkey:Int64, __value:Int64;N]\\n Aggregate: groupBy=[[orders.o_custkey]], aggr=[[MAX(orders.o_custkey)]] [o_custkey:Int64, MAX(orders.o_custkey):Int64;N]\\n TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]";- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);@@ -710,8 +731,10 @@ mod tests {.project(vec![col("customer.c_custkey")])?.build()?;- let expected = r#"exactly one expression should be projected"#;- assert_optimizer_err(Arc::new(ScalarSubqueryToJoin::new()), &plan, expected);+ let expected = "check_analyzed_plan\+ \ncaused by\+ \nError during planning: Scalar subquery should only return one column";+ assert_analyzer_check_err(vec![], &plan, expected);Ok(())}@@ -720,7 +743,10 @@ mod tests {fn scalar_subquery_additional_filters_with_non_equal_clause() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .eq(col("orders.o_custkey")),+ )?.aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?.project(vec![max(col("orders.o_custkey"))])?.build()?,@@ -745,8 +771,11 @@ mod tests {\n Aggregate: groupBy=[[orders.o_custkey]], aggr=[[MAX(orders.o_custkey)]] [o_custkey:Int64, MAX(orders.o_custkey):Int64;N]\\n TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]";- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);@@ -757,7 +786,10 @@ mod tests {fn scalar_subquery_additional_filters_with_equal_clause() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(scan_tpch_table("orders"))- .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?+ .filter(+ out_ref_col(DataType::Int64, "customer.c_custkey")+ .eq(col("orders.o_custkey")),+ )?.aggregate(Vec::<Expr>::new(), vec![max(col("orders.o_custkey"))])?.project(vec![max(col("orders.o_custkey"))])?.build()?,@@ -774,15 +806,18 @@ mod tests {let expected = "Projection: customer.c_custkey [c_custkey:Int64]\\n Filter: customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8, o_custkey:Int64, __value:Int64;N]\- \n Inner Join: customer.c_custkey = __scalar_sq_1.o_custkey, customer.c_custkey = __scalar_sq_1.__value [c_custkey:Int64, c_name:Utf8, o_custkey:Int64, __value:Int64;N]\+ \n Inner Join: customer.c_custkey = __scalar_sq_1.__value, customer.c_custkey = __scalar_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8, o_custkey:Int64, __value:Int64;N]\\n TableScan: customer [c_custkey:Int64, c_name:Utf8]\\n SubqueryAlias: __scalar_sq_1 [o_custkey:Int64, __value:Int64;N]\\n Projection: orders.o_custkey, MAX(orders.o_custkey) AS __value [o_custkey:Int64, __value:Int64;N]\\n Aggregate: groupBy=[[orders.o_custkey]], aggr=[[MAX(orders.o_custkey)]] [o_custkey:Int64, MAX(orders.o_custkey):Int64;N]\\n TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]";- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);@@ -818,8 +853,11 @@ mod tests {Filter: customer.c_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]TableScan: customer [c_custkey:Int64, c_name:Utf8]"#;- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);@@ -831,7 +869,7 @@ mod tests {fn exists_subquery_correlated() -> Result<()> {let sq = Arc::new(LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)- .filter(col("test.a").eq(col("sq.a")))?+ .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?.aggregate(Vec::<Expr>::new(), vec![min(col("c"))])?.project(vec![min(col("c"))])?.build()?,@@ -851,8 +889,11 @@ mod tests {\n Aggregate: groupBy=[[sq.a]], aggr=[[MIN(sq.c)]] [a:UInt32, MIN(sq.c):UInt32;N]\\n TableScan: sq [a:UInt32, b:UInt32, c:UInt32]";- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);@@ -883,8 +924,11 @@ mod tests {\n Aggregate: groupBy=[[]], aggr=[[MAX(orders.o_custkey)]] [MAX(orders.o_custkey):Int64;N]\\n TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]";- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);@@ -914,8 +958,11 @@ mod tests {\n Aggregate: groupBy=[[]], aggr=[[MAX(orders.o_custkey)]] [MAX(orders.o_custkey):Int64;N]\\n TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]";- assert_optimized_plan_eq_display_indent(- Arc::new(ScalarSubqueryToJoin::new()),+ assert_multi_rules_optimized_plan_eq_display_indent(+ vec![+ Arc::new(ScalarSubqueryToJoin::new()),+ Arc::new(ExtractEquijoinPredicate::new()),+ ],&plan,expected,);diff --git a/datafusion/optimizer/src/test/mod.rs b/datafusion/optimizer/src/test/mod.rsindex 2fc92758f1..7d334a80b6 100644--- a/datafusion/optimizer/src/test/mod.rs+++ b/datafusion/optimizer/src/test/mod.rs@@ -20,7 +20,7 @@ use crate::optimizer::Optimizer;use crate::{OptimizerContext, OptimizerRule};use arrow::datatypes::{DataType, Field, Schema};use datafusion_common::config::ConfigOptions;-use datafusion_common::Result;+use datafusion_common::{assert_contains, Result};use datafusion_expr::{col, logical_plan::table_scan, LogicalPlan, LogicalPlanBuilder};use std::sync::Arc;@@ -129,11 +129,27 @@ pub fn assert_analyzed_plan_eq_display_indent(let options = ConfigOptions::default();let analyzed_plan =Analyzer::with_rules(vec![rule]).execute_and_check(plan, &options, |_, _| {})?;- let formatted_plan = format!("{}", analyzed_plan.display_indent_schema());+ let formatted_plan = analyzed_plan.display_indent_schema().to_string();assert_eq!(formatted_plan, expected);Ok(())}++pub fn assert_analyzer_check_err(+ rules: Vec<Arc<dyn AnalyzerRule + Send + Sync>>,+ plan: &LogicalPlan,+ expected: &str,+) {+ let options = ConfigOptions::default();+ let analyzed_plan =+ Analyzer::with_rules(rules).execute_and_check(plan, &options, |_, _| {});+ match analyzed_plan {+ Ok(plan) => assert_eq!(format!("{}", plan.display_indent()), "An error"),+ Err(e) => {+ assert_contains!(e.to_string(), expected);+ }+ }+}pub fn assert_optimized_plan_eq(rule: Arc<dyn OptimizerRule + Send + Sync>,plan: &LogicalPlan,@@ -167,7 +183,24 @@ pub fn assert_optimized_plan_eq_display_indent().expect("failed to optimize plan").unwrap_or_else(|| plan.clone());- let formatted_plan = format!("{}", optimized_plan.display_indent_schema());+ let formatted_plan = optimized_plan.display_indent_schema().to_string();+ assert_eq!(formatted_plan, expected);+}++pub fn assert_multi_rules_optimized_plan_eq_display_indent(+ rules: Vec<Arc<dyn OptimizerRule + Send + Sync>>,+ plan: &LogicalPlan,+ expected: &str,+) {+ let optimizer = Optimizer::with_rules(rules);+ let mut optimized_plan = plan.clone();+ for rule in &optimizer.rules {+ optimized_plan = optimizer+ .optimize_recursively(rule, &optimized_plan, &OptimizerContext::new())+ .expect("failed to optimize plan")+ .unwrap_or_else(|| optimized_plan.clone());+ }+ let formatted_plan = optimized_plan.display_indent_schema().to_string();assert_eq!(formatted_plan, expected);}diff --git a/datafusion/optimizer/src/utils.rs b/datafusion/optimizer/src/utils.rsindex 4e5fa8cd6a..e8cced59fc 100644--- a/datafusion/optimizer/src/utils.rs+++ b/datafusion/optimizer/src/utils.rs@@ -22,18 +22,16 @@ use datafusion_common::tree_node::{TreeNode, TreeNodeRewriter};use datafusion_common::{plan_err, Column, DFSchemaRef};use datafusion_common::{DFSchema, Result};use datafusion_expr::expr::{BinaryExpr, Sort};-use datafusion_expr::expr_rewriter::strip_outer_reference;+use datafusion_expr::expr_rewriter::{replace_col, strip_outer_reference};use datafusion_expr::logical_plan::LogicalPlanBuilder;-use datafusion_expr::utils::{- check_all_columns_from_schema, from_plan, inspect_expr_pre,-};+use datafusion_expr::utils::from_plan;use datafusion_expr::{and,logical_plan::{Filter, LogicalPlan},Expr, Operator,};use log::{debug, trace};-use std::collections::{BTreeSet, HashSet};+use std::collections::{BTreeSet, HashMap};use std::sync::Arc;/// Convenience rule for writing optimizers: recursively invoke@@ -226,33 +224,6 @@ pub fn unalias(expr: Expr) -> Expr {}}-/// Recursively scans a slice of expressions for any `Or` operators-///-/// # Arguments-///-/// * `predicates` - the expressions to scan-///-/// # Return value-///-/// A PlanError if a disjunction is found-pub fn verify_not_disjunction(predicates: &[&Expr]) -> Result<()> {- // recursively check for unallowed predicates in expr- fn check(expr: &&Expr) -> Result<()> {- inspect_expr_pre(expr, |expr| match expr {- Expr::BinaryExpr(BinaryExpr {- left: _,- op: Operator::Or,- right: _,- }) => {- plan_err!("Optimizing disjunctions not supported!")- }- _ => Ok(()),- })- }-- predicates.iter().try_for_each(check)-}-/// returns a new [LogicalPlan] that wraps `plan` in a [LogicalPlan::Filter] with/// its predicate be all `predicates` ANDed.pub fn add_filter(plan: LogicalPlan, predicates: &[&Expr]) -> Result<LogicalPlan> {@@ -270,141 +241,34 @@ pub fn add_filter(plan: LogicalPlan, predicates: &[&Expr]) -> Result<LogicalPlan)?))}-/// Looks for correlating expressions: equality expressions with one field from the subquery, and+/// Looks for correlating expressions: for example, a binary expression with one field from the subquery, and/// one not in the subquery (closed upon from outer scope)////// # Arguments////// * `exprs` - List of expressions that may or may not be joins-/// * `schema` - HashSet of fully qualified (table.col) fields in subquery schema////// # Return value////// Tuple of (expressions containing joins, remaining non-join expressions)-pub fn find_join_exprs(- exprs: Vec<&Expr>,- schema: &DFSchemaRef,-) -> Result<(Vec<Expr>, Vec<Expr>)> {- let fields: HashSet<_> = schema- .fields()- .iter()- .map(|it| it.qualified_name())- .collect();-+pub fn find_join_exprs(exprs: Vec<&Expr>) -> Result<(Vec<Expr>, Vec<Expr>)> {let mut joins = vec![];let mut others = vec![];- for filter in exprs.iter() {+ for filter in exprs.into_iter() {// If the expression contains correlated predicates, add it to join filtersif filter.contains_outer() {- joins.push(strip_outer_reference((*filter).clone()));- } else {- // TODO remove the logic- let (left, op, right) = match filter {- Expr::BinaryExpr(BinaryExpr { left, op, right }) => {- (*left.clone(), *op, *right.clone())- }- _ => {- others.push((*filter).clone());- continue;- }- };- let left = match left {- Expr::Column(c) => c,- _ => {- others.push((*filter).clone());- continue;- }- };- let right = match right {- Expr::Column(c) => c,- _ => {- others.push((*filter).clone());- continue;- }- };- if fields.contains(&left.flat_name()) && fields.contains(&right.flat_name()) {- others.push((*filter).clone());- continue; // both columns present (none closed-upon)- }- if !fields.contains(&left.flat_name()) && !fields.contains(&right.flat_name())+ if !matches!(filter, Expr::BinaryExpr(BinaryExpr{ left, op: Operator::Eq, right }) if left.eq(right)){- others.push((*filter).clone());- continue; // neither column present (syntax error?)- }- match op {- Operator::Eq => {}- Operator::NotEq => {}- _ => {- plan_err!(format!("can't optimize {op} column comparison"))?;- }+ joins.push(strip_outer_reference((*filter).clone()));}- joins.push((*filter).clone())+ } else {+ others.push((*filter).clone());}}Ok((joins, others))}-/// Extracts correlating columns from expressions-///-/// # Arguments-///-/// * `exprs` - List of expressions that correlate a subquery to an outer scope-/// * `schema` - subquery schema-/// * `include_negated` - true if `NotEq` counts as a join operator-///-/// # Return value-///-/// Tuple of (outer-scope cols, subquery cols, non-correlation expressions)-pub fn exprs_to_join_cols(- exprs: &[Expr],- schema: &DFSchemaRef,- include_negated: bool,-) -> Result<(Vec<Column>, Vec<Column>, Option<Expr>)> {- let fields: HashSet<_> = schema- .fields()- .iter()- .map(|it| it.qualified_name())- .collect();-- let mut joins: Vec<(String, String)> = vec![];- let mut others: Vec<Expr> = vec![];- for filter in exprs.iter() {- let (left, op, right) = match filter {- Expr::BinaryExpr(BinaryExpr { left, op, right }) => {- (*left.clone(), *op, *right.clone())- }- _ => plan_err!("Invalid correlation expression!")?,- };- match op {- Operator::Eq => {}- Operator::NotEq => {- if !include_negated {- others.push((*filter).clone());- continue;- }- }- _ => plan_err!(format!("Correlation operator unsupported: {op}"))?,- }- let left = left.try_into_col()?;- let right = right.try_into_col()?;- let sorted = if fields.contains(&left.flat_name()) {- (right.flat_name(), left.flat_name())- } else {- (left.flat_name(), right.flat_name())- };- joins.push(sorted);- }-- let (left_cols, right_cols): (Vec<_>, Vec<_>) = joins- .into_iter()- .map(|(l, r)| (Column::from(l.as_str()), Column::from(r.as_str())))- .unzip();- let pred = conjunction(others);-- Ok((left_cols, right_cols, pred))-}-/// Returns the first (and only) element in a slice, or an error////// # Arguments@@ -491,25 +355,8 @@ pub(crate) fn extract_join_filters(maybe_filter: &LogicalPlan,) -> Result<(Vec<Expr>, LogicalPlan)> {if let LogicalPlan::Filter(plan_filter) = maybe_filter {- let input_schema = plan_filter.input.schema();let subquery_filter_exprs = split_conjunction(&plan_filter.predicate);-- let mut join_filters: Vec<Expr> = vec![];- let mut subquery_filters: Vec<Expr> = vec![];- for expr in subquery_filter_exprs {- // If the expression contains correlated predicates, add it to join filters- if expr.contains_outer() {- join_filters.push(strip_outer_reference(expr.clone()))- } else {- let cols = expr.to_columns()?;- if check_all_columns_from_schema(&cols, input_schema.clone())? {- subquery_filters.push(expr.clone());- } else {- join_filters.push(expr.clone())- }- }- }-+ let (join_filters, subquery_filters) = find_join_exprs(subquery_filter_exprs)?;// if the subquery still has filter expressions, restore them.let mut plan = LogicalPlanBuilder::from((*plan_filter.input).clone());if let Some(expr) = conjunction(subquery_filters) {@@ -539,6 +386,23 @@ pub(crate) fn collect_subquery_cols(})}+pub(crate) fn replace_qualified_name(+ expr: Expr,+ cols: &BTreeSet<Column>,+ subquery_alias: &str,+) -> Result<Expr> {+ let alias_cols: Vec<Column> = cols+ .iter()+ .map(|col| {+ Column::from_qualified_name(format!("{}.{}", subquery_alias, col.name))+ })+ .collect();+ let replace_map: HashMap<&Column, &Column> =+ cols.iter().zip(alias_cols.iter()).collect();++ replace_col(expr, &replace_map)+}+/// Log the plan in debug/tracing mode after some part of the optimizer runspub fn log_plan(description: &str, plan: &LogicalPlan) {debug!("{description}:\n{}\n", plan.display_indent());