-
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
fix: move coercion of union from builder to TypeCoercion
#11961
Merged
Merged
Changes from 10 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
e019ccc
Improve type coercion for `UNION`
jonahgao 9fca957
fix clippy
jonahgao e69a1a1
fix test
jonahgao 6c3edd3
Merge branch 'main' into union_coercion
jonahgao b67f11c
fix sqllogictests
jonahgao 5ad7243
fix EliminateNestedUnion tests
jonahgao d96892c
Move tests to slt
jonahgao d672bbf
Merge branch 'main' into union_coercion
jonahgao 6c05d17
Move union_coercion to type_coercion.rs
jonahgao 21f93dc
fix tests
jonahgao c2235df
fix cargo doc
jonahgao 364ba12
Merge branch 'main' into union_coercion
jonahgao e5c2dc9
Improve error msg
jonahgao 723fd43
As static member
jonahgao 7e8b3f4
Avoid clone
jonahgao d42486e
Fix clippy
jonahgao 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -20,7 +20,6 @@ | |
use std::any::Any; | ||
use std::cmp::Ordering; | ||
use std::collections::{HashMap, HashSet}; | ||
use std::iter::zip; | ||
use std::sync::Arc; | ||
|
||
use crate::dml::CopyTo; | ||
|
@@ -36,7 +35,7 @@ use crate::logical_plan::{ | |
Projection, Repartition, Sort, SubqueryAlias, TableScan, Union, Unnest, Values, | ||
Window, | ||
}; | ||
use crate::type_coercion::binary::{comparison_coercion, values_coercion}; | ||
use crate::type_coercion::binary::values_coercion; | ||
use crate::utils::{ | ||
can_hash, columnize_expr, compare_sort_expr, expand_qualified_wildcard, | ||
expand_wildcard, expr_to_columns, find_valid_equijoin_key_pair, | ||
|
@@ -1339,95 +1338,14 @@ pub(crate) fn validate_unique_names<'a>( | |
}) | ||
} | ||
|
||
pub fn project_with_column_index( | ||
expr: Vec<Expr>, | ||
input: Arc<LogicalPlan>, | ||
schema: DFSchemaRef, | ||
) -> Result<LogicalPlan> { | ||
let alias_expr = expr | ||
.into_iter() | ||
.enumerate() | ||
.map(|(i, e)| match e { | ||
Expr::Alias(Alias { ref name, .. }) if name != schema.field(i).name() => { | ||
e.unalias().alias(schema.field(i).name()) | ||
} | ||
Expr::Column(Column { | ||
relation: _, | ||
ref name, | ||
}) if name != schema.field(i).name() => e.alias(schema.field(i).name()), | ||
Expr::Alias { .. } | Expr::Column { .. } => e, | ||
_ => e.alias(schema.field(i).name()), | ||
}) | ||
.collect::<Vec<_>>(); | ||
|
||
Projection::try_new_with_schema(alias_expr, input, schema) | ||
.map(LogicalPlan::Projection) | ||
} | ||
|
||
/// Union two logical plans. | ||
pub fn union(left_plan: LogicalPlan, right_plan: LogicalPlan) -> Result<LogicalPlan> { | ||
let left_col_num = left_plan.schema().fields().len(); | ||
|
||
// check union plan length same. | ||
let right_col_num = right_plan.schema().fields().len(); | ||
if right_col_num != left_col_num { | ||
return plan_err!( | ||
"Union queries must have the same number of columns, (left is {left_col_num}, right is {right_col_num})"); | ||
} | ||
|
||
// create union schema | ||
let union_qualified_fields = | ||
zip(left_plan.schema().iter(), right_plan.schema().iter()) | ||
.map( | ||
|((left_qualifier, left_field), (_right_qualifier, right_field))| { | ||
let nullable = left_field.is_nullable() || right_field.is_nullable(); | ||
let data_type = comparison_coercion( | ||
left_field.data_type(), | ||
right_field.data_type(), | ||
) | ||
.ok_or_else(|| { | ||
plan_datafusion_err!( | ||
"UNION Column {} (type: {}) is not compatible with column {} (type: {})", | ||
right_field.name(), | ||
right_field.data_type(), | ||
left_field.name(), | ||
left_field.data_type() | ||
) | ||
})?; | ||
Ok(( | ||
left_qualifier.cloned(), | ||
Arc::new(Field::new(left_field.name(), data_type, nullable)), | ||
)) | ||
}, | ||
) | ||
.collect::<Result<Vec<_>>>()?; | ||
let union_schema = | ||
DFSchema::new_with_metadata(union_qualified_fields, HashMap::new())?; | ||
|
||
let inputs = vec![left_plan, right_plan] | ||
.into_iter() | ||
.map(|p| { | ||
let plan = coerce_plan_expr_for_schema(&p, &union_schema)?; | ||
match plan { | ||
LogicalPlan::Projection(Projection { expr, input, .. }) => { | ||
Ok(Arc::new(project_with_column_index( | ||
expr, | ||
input, | ||
Arc::new(union_schema.clone()), | ||
)?)) | ||
} | ||
other_plan => Ok(Arc::new(other_plan)), | ||
} | ||
}) | ||
.collect::<Result<Vec<_>>>()?; | ||
|
||
if inputs.is_empty() { | ||
return plan_err!("Empty UNION"); | ||
} | ||
|
||
// Temporarily use the schema from the left input and later rely on the analyzer to | ||
// coerce the two schemas into a common one. | ||
let schema = Arc::clone(left_plan.schema()); | ||
Ok(LogicalPlan::Union(Union { | ||
inputs, | ||
schema: Arc::new(union_schema), | ||
inputs: vec![Arc::new(left_plan), Arc::new(right_plan)], | ||
schema, | ||
})) | ||
} | ||
|
||
|
@@ -1881,23 +1799,6 @@ mod tests { | |
Ok(()) | ||
} | ||
|
||
#[test] | ||
fn plan_builder_union_different_num_columns_error() -> Result<()> { | ||
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. Moved to slt. |
||
let plan1 = | ||
table_scan(TableReference::none(), &employee_schema(), Some(vec![3]))?; | ||
let plan2 = | ||
table_scan(TableReference::none(), &employee_schema(), Some(vec![3, 4]))?; | ||
|
||
let expected = "Error during planning: Union queries must have the same number of columns, (left is 1, right is 2)"; | ||
let err_msg1 = plan1.clone().union(plan2.clone().build()?).unwrap_err(); | ||
let err_msg2 = plan1.union_distinct(plan2.build()?).unwrap_err(); | ||
|
||
assert_eq!(err_msg1.strip_backtrace(), expected); | ||
assert_eq!(err_msg2.strip_backtrace(), expected); | ||
|
||
Ok(()) | ||
} | ||
|
||
#[test] | ||
fn plan_builder_simple_distinct() -> Result<()> { | ||
let plan = | ||
|
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 |
---|---|---|
|
@@ -114,8 +114,11 @@ fn extract_plan_from_distinct(plan: Arc<LogicalPlan>) -> Arc<LogicalPlan> { | |
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
use crate::analyzer::type_coercion::TypeCoercion; | ||
use crate::analyzer::Analyzer; | ||
use crate::test::*; | ||
use arrow::datatypes::{DataType, Field, Schema}; | ||
use datafusion_common::config::ConfigOptions; | ||
use datafusion_expr::{col, logical_plan::table_scan}; | ||
|
||
fn schema() -> Schema { | ||
|
@@ -127,7 +130,14 @@ mod tests { | |
} | ||
|
||
fn assert_optimized_plan_equal(plan: LogicalPlan, expected: &str) -> Result<()> { | ||
assert_optimized_plan_eq(Arc::new(EliminateNestedUnion::new()), plan, expected) | ||
let options = ConfigOptions::default(); | ||
let analyzed_plan = Analyzer::with_rules(vec![Arc::new(TypeCoercion::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. Add TypeCoercion to avoid breaking the tests. |
||
.execute_and_check(plan, &options, |_, _| {})?; | ||
assert_optimized_plan_eq( | ||
Arc::new(EliminateNestedUnion::new()), | ||
analyzed_plan, | ||
expected, | ||
) | ||
} | ||
|
||
#[test] | ||
|
Oops, something went wrong.
Oops, something went wrong.
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.
👍