Skip to content
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: alias group_by exprs in single_distinct_to_groupby optimizer #3305

Merged
merged 6 commits into from
Sep 7, 2022
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 84 additions & 46 deletions datafusion/optimizer/src/single_distinct_to_groupby.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@

use crate::{OptimizerConfig, OptimizerRule};
use datafusion_common::{DFSchema, Result};
use datafusion_expr::utils::grouping_set_to_exprlist;
use datafusion_expr::{
col,
logical_plan::{Aggregate, LogicalPlan, Projection},
Expand Down Expand Up @@ -64,20 +63,36 @@ fn optimize(plan: &LogicalPlan) -> Result<LogicalPlan> {
group_expr,
}) => {
if is_single_distinct_agg(plan) && !contains_grouping_set(group_expr) {
let mut group_fields_set = HashSet::new();
let base_group_expr = grouping_set_to_exprlist(group_expr)?;
let mut all_group_args: Vec<Expr> = group_expr.clone();
// alias all original group_by exprs
let mut group_expr_alias = Vec::with_capacity(group_expr.len());
let mut inner_group_exprs = group_expr
.iter()
.enumerate()
.map(|(i, group_expr)| {
let alias_str = format!("group_alias_{}", i);
let alias_expr = group_expr.clone().alias(&alias_str);
group_expr_alias.push((alias_str, schema.fields()[i].clone()));
alias_expr
})
.collect::<Vec<_>>();

// and they can be referenced by the alias in the outer aggr plan
let outer_group_exprs = group_expr_alias
.iter()
.map(|(alias, _)| col(alias))
.collect::<Vec<_>>();

// remove distinct and collection args
let new_aggr_expr = aggr_expr
// replace the distinct arg with alias
let mut group_fields_set = HashSet::new();
let new_aggr_exprs = aggr_expr
.iter()
.map(|agg_expr| match agg_expr {
.map(|aggr_expr| match aggr_expr {
Expr::AggregateFunction { fun, args, .. } => {
// is_single_distinct_agg ensure args.len=1
if group_fields_set
.insert(args[0].name(input.schema()).unwrap())
{
all_group_args
inner_group_exprs
.push(args[0].clone().alias(SINGLE_DISTINCT_ALIAS));
}
Expr::AggregateFunction {
Expand All @@ -86,64 +101,66 @@ fn optimize(plan: &LogicalPlan) -> Result<LogicalPlan> {
distinct: false,
}
}
_ => agg_expr.clone(),
_ => aggr_expr.clone(),
})
.collect::<Vec<_>>();

let all_group_expr = grouping_set_to_exprlist(&all_group_args)?;

let all_field = all_group_expr
// construct the inner AggrPlan
let inner_fields = inner_group_exprs
.iter()
.map(|expr| expr.to_field(input.schema()).unwrap())
.collect::<Vec<_>>();

let grouped_schema = DFSchema::new_with_metadata(
all_field,
let inner_schema = DFSchema::new_with_metadata(
inner_fields,
input.schema().metadata().clone(),
)
.unwrap();
let grouped_agg = LogicalPlan::Aggregate(Aggregate {
let grouped_aggr = LogicalPlan::Aggregate(Aggregate {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use Aggregate::try_new here, once #3286 is merged

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have removed all unwraps

input: input.clone(),
group_expr: all_group_args,
group_expr: inner_group_exprs,
aggr_expr: Vec::new(),
schema: Arc::new(grouped_schema.clone()),
schema: Arc::new(inner_schema.clone()),
});
let grouped_agg = optimize_children(&grouped_agg);
let final_agg_schema = Arc::new(
let inner_agg = optimize_children(&grouped_aggr)?;

let outer_aggr_schema = Arc::new(
DFSchema::new_with_metadata(
base_group_expr
outer_group_exprs
.iter()
.chain(new_aggr_expr.iter())
.map(|expr| expr.to_field(&grouped_schema).unwrap())
.chain(new_aggr_exprs.iter())
.map(|expr| expr.to_field(&inner_schema).unwrap())
.collect::<Vec<_>>(),
input.schema().metadata().clone(),
)
.unwrap(),
);

// so the aggregates are displayed in the same way even after the rewrite
// this optimizer has two kinds of alias:
// - group_by aggr
// - aggr expr
let mut alias_expr: Vec<Expr> = Vec::new();
base_group_expr
.iter()
.chain(new_aggr_expr.iter())
.enumerate()
.for_each(|(i, field)| {
alias_expr.push(columnize_expr(
field.clone().alias(schema.clone().fields()[i].name()),
&final_agg_schema,
));
});

let final_agg = LogicalPlan::Aggregate(Aggregate {
input: Arc::new(grouped_agg.unwrap()),
group_expr: group_expr.clone(),
aggr_expr: new_aggr_expr,
schema: final_agg_schema,
for (alias, original_field) in group_expr_alias {
alias_expr.push(col(&alias).alias(original_field.name()));
}
for (i, expr) in new_aggr_exprs.iter().enumerate() {
alias_expr.push(columnize_expr(
expr.clone()
.alias(schema.clone().fields()[i + group_expr.len()].name()),
&outer_aggr_schema,
));
}

let outer_aggr = LogicalPlan::Aggregate(Aggregate {
input: Arc::new(inner_agg),
group_expr: outer_group_exprs,
aggr_expr: new_aggr_exprs,
schema: outer_aggr_schema,
});

Ok(LogicalPlan::Projection(Projection::try_new_with_schema(
alias_expr,
Arc::new(final_agg),
Arc::new(outer_aggr),
schema.clone(),
None,
)?))
Expand All @@ -165,6 +182,7 @@ fn optimize_children(plan: &LogicalPlan) -> Result<LogicalPlan> {
from_plan(plan, &expr, &new_inputs)
}

/// Check whether all aggregate exprs are distinct on a single field.
fn is_single_distinct_agg(plan: &LogicalPlan) -> bool {
match plan {
LogicalPlan::Aggregate(Aggregate {
Expand All @@ -191,6 +209,7 @@ fn is_single_distinct_agg(plan: &LogicalPlan) -> bool {
}
}

/// Check if the first expr is [Expr::GroupingSet].
fn contains_grouping_set(expr: &[Expr]) -> bool {
matches!(expr.first(), Some(Expr::GroupingSet(_)))
}
Expand Down Expand Up @@ -352,9 +371,9 @@ mod tests {
.build()?;

// Should work
let expected = "Projection: #test.a AS a, #COUNT(alias1) AS COUNT(DISTINCT test.b) [a:UInt32, COUNT(DISTINCT test.b):Int64;N]\
\n Aggregate: groupBy=[[#test.a]], aggr=[[COUNT(#alias1)]] [a:UInt32, COUNT(alias1):Int64;N]\
\n Aggregate: groupBy=[[#test.a, #test.b AS alias1]], aggr=[[]] [a:UInt32, alias1:UInt32]\
let expected = "Projection: #group_alias_0 AS a, #COUNT(alias1) AS COUNT(DISTINCT test.b) [a:UInt32, COUNT(DISTINCT test.b):Int64;N]\
\n Aggregate: groupBy=[[#group_alias_0]], aggr=[[COUNT(#alias1)]] [group_alias_0:UInt32, COUNT(alias1):Int64;N]\
\n Aggregate: groupBy=[[#test.a AS group_alias_0, #test.b AS alias1]], aggr=[[]] [group_alias_0:UInt32, alias1:UInt32]\
\n TableScan: test [a:UInt32, b:UInt32, c:UInt32]";

assert_optimized_plan_eq(&plan, expected);
Expand Down Expand Up @@ -398,9 +417,9 @@ mod tests {
)?
.build()?;
// Should work
let expected = "Projection: #test.a AS a, #COUNT(alias1) AS COUNT(DISTINCT test.b), #MAX(alias1) AS MAX(DISTINCT test.b) [a:UInt32, COUNT(DISTINCT test.b):Int64;N, MAX(DISTINCT test.b):UInt32;N]\
\n Aggregate: groupBy=[[#test.a]], aggr=[[COUNT(#alias1), MAX(#alias1)]] [a:UInt32, COUNT(alias1):Int64;N, MAX(alias1):UInt32;N]\
\n Aggregate: groupBy=[[#test.a, #test.b AS alias1]], aggr=[[]] [a:UInt32, alias1:UInt32]\
let expected = "Projection: #group_alias_0 AS a, #COUNT(alias1) AS COUNT(DISTINCT test.b), #MAX(alias1) AS MAX(DISTINCT test.b) [a:UInt32, COUNT(DISTINCT test.b):Int64;N, MAX(DISTINCT test.b):UInt32;N]\
\n Aggregate: groupBy=[[#group_alias_0]], aggr=[[COUNT(#alias1), MAX(#alias1)]] [group_alias_0:UInt32, COUNT(alias1):Int64;N, MAX(alias1):UInt32;N]\
\n Aggregate: groupBy=[[#test.a AS group_alias_0, #test.b AS alias1]], aggr=[[]] [group_alias_0:UInt32, alias1:UInt32]\
\n TableScan: test [a:UInt32, b:UInt32, c:UInt32]";

assert_optimized_plan_eq(&plan, expected);
Expand All @@ -425,4 +444,23 @@ mod tests {
assert_optimized_plan_eq(&plan, expected);
Ok(())
}

#[test]
fn group_by_with_expr() {
let table_scan = test_table_scan().unwrap();

let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(vec![col("a") + lit(1)], vec![count_distinct(col("c"))])
.unwrap()
.build()
.unwrap();

// Should work
let expected = "Projection: #group_alias_0 AS test.a + Int32(1), #COUNT(alias1) AS COUNT(DISTINCT test.c) [test.a + Int32(1):Int32, COUNT(DISTINCT test.c):Int64;N]\
\n Aggregate: groupBy=[[#group_alias_0]], aggr=[[COUNT(#alias1)]] [group_alias_0:Int32, COUNT(alias1):Int64;N]\
\n Aggregate: groupBy=[[#test.a + Int32(1) AS group_alias_0, #test.c AS alias1]], aggr=[[]] [group_alias_0:Int32, alias1:UInt32]\
\n TableScan: test [a:UInt32, b:UInt32, c:UInt32]";

assert_optimized_plan_eq(&plan, expected);
}
}