-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Transform scalar correlated subqueries in Where to DependentJoin #16174
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,171 @@ | ||
// 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 datafusion_common::tree_node::Transformed; | ||
use datafusion_common::{Result, ScalarValue}; | ||
use datafusion_expr::{Expr, JoinType, LogicalPlan, LogicalPlanBuilder, Subquery}; | ||
|
||
use crate::{ApplyOrder, OptimizerConfig, OptimizerRule}; | ||
|
||
/// (temporary) OPtimizer rule for rewriting current plan with | ||
/// DependentJoin to jj | ||
#[derive(Default, Debug)] | ||
pub struct CreateDependentJoin {} | ||
|
||
impl CreateDependentJoin { | ||
#[allow(missing_docs)] | ||
pub fn new() -> Self { | ||
Self::default() | ||
} | ||
} | ||
|
||
impl OptimizerRule for CreateDependentJoin { | ||
fn supports_rewrite(&self) -> bool { | ||
true | ||
} | ||
|
||
fn name(&self) -> &str { | ||
"create_dependent_join" | ||
} | ||
|
||
fn apply_order(&self) -> Option<ApplyOrder> { | ||
Some(ApplyOrder::TopDown) | ||
} | ||
|
||
fn rewrite( | ||
&self, | ||
plan: LogicalPlan, | ||
_config: &dyn OptimizerConfig, | ||
) -> Result<Transformed<LogicalPlan>> { | ||
if let LogicalPlan::Filter(ref filter) = plan { | ||
match &filter.predicate { | ||
Expr::BinaryExpr(binary) => { | ||
// Check if right hand side is a scalar subquery | ||
if let Expr::ScalarSubquery(subquery) = binary.right.as_ref() { | ||
let new_plan = build_dependent_join( | ||
subquery, | ||
filter.input.as_ref().clone(), | ||
JoinType::Left, | ||
)?; | ||
return Ok(Transformed::yes(new_plan)); | ||
} | ||
// Continue searching in children if no subquery found | ||
return Ok(Transformed::no(plan)); | ||
} | ||
_ => { | ||
// TODO: add other type of subqueries. | ||
return Ok(Transformed::no(plan)); | ||
} | ||
} | ||
} | ||
|
||
// No Filter found, continue searching in children | ||
Ok(Transformed::no(plan)) | ||
} | ||
} | ||
|
||
fn build_dependent_join( | ||
subquery: &Subquery, | ||
root: LogicalPlan, | ||
join_type: JoinType, | ||
) -> Result<LogicalPlan> { | ||
let subquery_plan = (subquery.subquery).as_ref().clone(); | ||
|
||
let new_plan = LogicalPlanBuilder::from(root) | ||
.dependent_join_on( | ||
subquery_plan, | ||
join_type, | ||
vec![Expr::Literal(ScalarValue::Boolean(Some(true)))], | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: we have shorter syntax:
|
||
subquery.outer_ref_columns.clone(), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. if the subquery has some nested subquery underneath, i believe this function won't be able to return the outer_ref_columns from lower level.
In this case, the calls to There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For cases where depth > 1, DataFusion doesn't support it at the planner stage. The reason is that each time parse_subquery is called, it uses the outer_query_schema, which is the schema from the previous layer of the query: pub(super) fn parse_scalar_subquery(
&self,
subquery: Query,
input_schema: &DFSchema,
planner_context: &mut PlannerContext,
) -> Result<Expr> {
let old_outer_query_schema =
planner_context.set_outer_query_schema(Some(input_schema.clone().into()));
... In #16060, I attempted to layer the schemas of query blocks at different depths within the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. i wonder would it be more simple to let the decorrelation optimizor aware of the depth and handle recursion itself 🤔 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Since there are multiple optimizer rules, I'm wondering if the depth will change because of other priority rules rewrite.🤔 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
In the final stage of this epic we only let one optimizor handle the decorrelation right? Also in the middle of the implementation, even if we maintain multiple decorrelating rules, if existing rule such as There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I also implemented something like this, but inside an optimizor (still alot of details need to be added, but at least it is capable of detect the correlated columns (including the ones with depth > 1), correlated exprs, the depth of the dependent join node) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks @duongcongtoai, I've seen your pr, It's much more comprehensive than mine. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Maybe we could implement an initial version first, then list some pending work as tracking issues? I'm actually quite eager to contribute and help out as well. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yep, i'll try to wrap up with some basic usecase and ask for review soon |
||
)? | ||
.build()?; | ||
|
||
Ok(new_plan) | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use std::sync::Arc; | ||
|
||
use datafusion_common::{Result, Spans}; | ||
use datafusion_expr::{col, Expr, LogicalPlanBuilder, Subquery}; | ||
use datafusion_functions_aggregate::expr_fn::avg; | ||
|
||
use crate::assert_optimized_plan_eq_display_indent_snapshot; | ||
use crate::create_dependent_join::CreateDependentJoin; | ||
use crate::test::test_table_scan_with_name; | ||
|
||
macro_rules! assert_optimized_plan_equal { | ||
( | ||
$plan:expr, | ||
@ $expected:literal $(,)? | ||
) => {{ | ||
let rule: Arc<dyn crate::OptimizerRule + Send + Sync> = Arc::new(CreateDependentJoin::new()); | ||
assert_optimized_plan_eq_display_indent_snapshot!( | ||
rule, | ||
$plan, | ||
@ $expected, | ||
) | ||
}}; | ||
} | ||
|
||
#[test] | ||
fn test_correlated_scalar_subquery() -> Result<()> { | ||
// outer table | ||
let employees = test_table_scan_with_name("employees")?; | ||
// inner table | ||
let salary = test_table_scan_with_name("salary")?; | ||
|
||
// SELECT employees.a | ||
// FROM employees | ||
// WHERE employees.b > ( | ||
// SELECT avg(salary.a) | ||
// FROM salary | ||
// WHERE salary.c = employees.c | ||
// ); | ||
|
||
// SELECT AVG(salary.a) FROM salary WHERE salary.c = employees.c | ||
let subquery = Arc::new( | ||
LogicalPlanBuilder::from(salary) | ||
.filter(col("salary.c").eq(col("employees.c")))? | ||
.aggregate(Vec::<Expr>::new(), vec![avg(col("salary.a"))])? | ||
.build()?, | ||
); | ||
|
||
// SELECT employees.a FROM employees WHERE employees.b > (subquery) | ||
let plan = LogicalPlanBuilder::from(employees) | ||
.filter(col("employees.a").gt(Expr::ScalarSubquery(Subquery { | ||
subquery, | ||
outer_ref_columns: vec![col("employees.c")], | ||
spans: Spans::new(), | ||
})))? | ||
.project(vec![col("employees.a")])? | ||
.build()?; | ||
|
||
assert_optimized_plan_equal!( | ||
plan, | ||
@r" | ||
Projection: employees.a [a:UInt32] | ||
Left Join: Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32, avg(salary.a):Float64;N] | ||
TableScan: employees [a:UInt32, b:UInt32, c:UInt32] | ||
Aggregate: groupBy=[[]], aggr=[[avg(salary.a)]] [avg(salary.a):Float64;N] | ||
Filter: salary.c = employees.c [a:UInt32, b:UInt32, c:UInt32] | ||
TableScan: salary [a:UInt32, b:UInt32, c:UInt32] | ||
" | ||
) | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -329,6 +329,8 @@ fn find_inner_join( | |
filter: None, | ||
schema: join_schema, | ||
null_equals_null: false, | ||
dependent_join: false, | ||
outer_ref_columns: vec![], | ||
})); | ||
} | ||
} | ||
|
@@ -351,6 +353,8 @@ fn find_inner_join( | |
join_type: JoinType::Inner, | ||
join_constraint: JoinConstraint::On, | ||
null_equals_null: false, | ||
dependent_join: false, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can't we use something like There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Using a bool is a little strange, so I comment There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I thought |
||
outer_ref_columns: vec![], | ||
})) | ||
} | ||
|
||
|
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
here are more cases i can think of:
In this case 2 nested dependent join will be generated