-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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
Support inlining view / dataframes logical plan #3923
Merged
Merged
Changes from 13 commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
268b3c9
Inline TableScans for views and dataframes
Dandandan eec7294
Inline TableScans for views and dataframes
Dandandan f8405f4
Inline TableScans for views and dataframes
Dandandan d0b540f
WIP
Dandandan 55ddffc
WIP
Dandandan a4288c9
WIP
Dandandan 5548d5e
WIP
Dandandan ffdd1ec
Merge branch 'master' into inline_table_provider
Dandandan f775a8c
WIP
Dandandan 265b7a6
WIP
Dandandan cca1c90
fmt
Dandandan 0254c92
doc
Dandandan 0912a84
Fix test
Dandandan ffc9c36
Simplify
Dandandan 420a2f4
Fix
Dandandan f61feb2
Rename test source
Dandandan 4de241e
Use plan instead of projected schema
Dandandan f17be35
Docs
Dandandan 207c2a9
Use SubqueryAlias
Dandandan c487c0a
Revert "Use SubqueryAlias"
Dandandan 5871a79
WIP
Dandandan 275ef8e
Fix issue
Dandandan fd70f3e
Clippy
Dandandan 12fd431
Format
Dandandan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,188 @@ | ||
// 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. | ||
|
||
//! Optimizer rule to replace TableScan references | ||
//! such as DataFrames and Views and inlines the LogicalPlan | ||
//! to support further optimization | ||
use crate::{OptimizerConfig, OptimizerRule}; | ||
use datafusion_common::Result; | ||
use datafusion_expr::{ | ||
col, logical_plan::LogicalPlan, utils::from_plan, LogicalPlanBuilder, TableScan, | ||
}; | ||
|
||
/// Optimization rule that inlines TableScan that provide a [LogicalPlan] | ||
/// ([DataFrame] / [ViewTable]) | ||
#[derive(Default)] | ||
pub struct InlineTableScan; | ||
|
||
impl InlineTableScan { | ||
#[allow(missing_docs)] | ||
pub fn new() -> Self { | ||
Self {} | ||
} | ||
} | ||
|
||
/// Inline | ||
fn inline_table_scan(plan: &LogicalPlan) -> Result<LogicalPlan> { | ||
match plan { | ||
LogicalPlan::TableScan(TableScan { | ||
source, | ||
table_name, | ||
filters, | ||
fetch, | ||
projected_schema, | ||
.. | ||
}) => { | ||
if let Some(sub_plan) = source.get_logical_plan() { | ||
// Recurse into scan | ||
let plan = inline_table_scan(sub_plan)?; | ||
let mut plan = LogicalPlanBuilder::from(plan).project_with_alias( | ||
projected_schema | ||
.fields() | ||
.iter() | ||
.map(|field| col(field.name())), | ||
Some(table_name.clone()), | ||
)?; | ||
for filter in filters { | ||
Dandandan marked this conversation as resolved.
Show resolved
Hide resolved
|
||
plan = plan.filter(filter.clone())?; | ||
} | ||
if let Some(fetch) = fetch { | ||
plan = plan.limit(0, Some(*fetch))?; | ||
} | ||
plan.build() | ||
} else { | ||
// No plan available, return with table scan as is | ||
Ok(plan.clone()) | ||
} | ||
} | ||
|
||
// Rest: Recurse | ||
_ => { | ||
// apply the optimization to all inputs of the plan | ||
let inputs = plan.inputs(); | ||
let new_inputs = inputs | ||
.iter() | ||
.map(|plan| inline_table_scan(plan)) | ||
.collect::<Result<Vec<_>>>()?; | ||
|
||
from_plan(plan, &plan.expressions(), &new_inputs) | ||
} | ||
} | ||
} | ||
|
||
impl OptimizerRule for InlineTableScan { | ||
fn optimize( | ||
&self, | ||
plan: &LogicalPlan, | ||
_optimizer_config: &mut OptimizerConfig, | ||
) -> Result<LogicalPlan> { | ||
inline_table_scan(plan) | ||
} | ||
|
||
fn name(&self) -> &str { | ||
"inline_table_scan" | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use std::{sync::Arc, vec}; | ||
|
||
use arrow::datatypes::{DataType, Field, Schema}; | ||
use datafusion_expr::{col, lit, LogicalPlan, LogicalPlanBuilder, TableSource}; | ||
|
||
use crate::{inline_table_scan::InlineTableScan, OptimizerConfig, OptimizerRule}; | ||
|
||
pub struct CustomSource2 {} | ||
|
||
impl TableSource for CustomSource2 { | ||
fn as_any(&self) -> &dyn std::any::Any { | ||
self | ||
} | ||
|
||
fn schema(&self) -> arrow::datatypes::SchemaRef { | ||
Arc::new(Schema::new(vec![Field::new("a", DataType::Int64, false)])) | ||
} | ||
|
||
fn supports_filter_pushdown( | ||
&self, | ||
_filter: &datafusion_expr::Expr, | ||
) -> datafusion_common::Result<datafusion_expr::TableProviderFilterPushDown> | ||
{ | ||
Ok(datafusion_expr::TableProviderFilterPushDown::Inexact) | ||
} | ||
} | ||
|
||
pub struct CustomSource { | ||
plan: LogicalPlan, | ||
} | ||
impl CustomSource { | ||
fn new() -> Self { | ||
Self { | ||
plan: LogicalPlanBuilder::scan("y", Arc::new(CustomSource2 {}), None) | ||
.unwrap() | ||
.build() | ||
.unwrap(), | ||
} | ||
} | ||
} | ||
impl TableSource for CustomSource { | ||
fn as_any(&self) -> &dyn std::any::Any { | ||
self | ||
} | ||
|
||
fn supports_filter_pushdown( | ||
&self, | ||
_filter: &datafusion_expr::Expr, | ||
) -> datafusion_common::Result<datafusion_expr::TableProviderFilterPushDown> | ||
{ | ||
Ok(datafusion_expr::TableProviderFilterPushDown::Exact) | ||
} | ||
|
||
fn schema(&self) -> arrow::datatypes::SchemaRef { | ||
Arc::new(Schema::new(vec![Field::new("a", DataType::Int64, false)])) | ||
} | ||
|
||
fn get_logical_plan(&self) -> Option<&LogicalPlan> { | ||
Some(&self.plan) | ||
} | ||
} | ||
|
||
#[test] | ||
fn inline_table_scan() { | ||
let rule = InlineTableScan::new(); | ||
|
||
let source = Arc::new(CustomSource::new()); | ||
|
||
let scan = | ||
LogicalPlanBuilder::scan("x".to_string(), source.clone(), None).unwrap(); | ||
|
||
let plan = scan.filter(col("x.a").eq(lit(1))).unwrap().build().unwrap(); | ||
|
||
let optimized_plan = rule | ||
.optimize(&plan, &mut OptimizerConfig::new()) | ||
.expect("failed to optimize plan"); | ||
let formatted_plan = format!("{:?}", optimized_plan); | ||
let expected = "\ | ||
Filter: x.a = Int32(1)\ | ||
\n Projection: y.a, alias=x\ | ||
\n TableScan: y"; | ||
|
||
assert_eq!(formatted_plan, expected); | ||
assert_eq!(plan.schema(), optimized_plan.schema()); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -24,6 +24,7 @@ use crate::eliminate_filter::EliminateFilter; | |
use crate::eliminate_limit::EliminateLimit; | ||
use crate::filter_null_join_keys::FilterNullJoinKeys; | ||
use crate::filter_push_down::FilterPushDown; | ||
use crate::inline_table_scan::InlineTableScan; | ||
use crate::limit_push_down::LimitPushDown; | ||
use crate::projection_push_down::ProjectionPushDown; | ||
use crate::reduce_cross_join::ReduceCrossJoin; | ||
|
@@ -148,6 +149,7 @@ impl Optimizer { | |
/// Create a new optimizer using the recommended list of rules | ||
pub fn new(config: &OptimizerConfig) -> Self { | ||
let mut rules: Vec<Arc<dyn OptimizerRule + Sync + Send>> = vec![ | ||
Arc::new(InlineTableScan::new()), | ||
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. @alamb @andygrove this might be a good candidate as well to an 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 agree |
||
Arc::new(TypeCoercion::new()), | ||
Arc::new(SimplifyExpressions::new()), | ||
Arc::new(UnwrapCastInComparison::new()), | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
👍