Apache DataFusion SQL Query Engine
improve: support combining multiple grouping expressions (#5559)
yujie.zhang68e304087be4
diff --git a/datafusion/core/tests/sqllogictests/test_files/aggregate.slt b/datafusion/core/tests/sqllogictests/test_files/aggregate.sltindex 0fffb2a5db..51e61ec4c3 100644--- a/datafusion/core/tests/sqllogictests/test_files/aggregate.slt+++ b/datafusion/core/tests/sqllogictests/test_files/aggregate.slt@@ -756,6 +756,126 @@ b 5 NULL 20135.4b NULL NULL 7732.315789473684NULL NULL NULL 3833.525+# csv_query_groupingsets_avg+query TIIR+SELECT c1, c2, c3, AVG(c4)+FROM aggregate_test_100_by_sql+WHERE c1 IN ('a', 'b', NULL)+GROUP BY GROUPING SETS ((c1), (c1,c2), (c1,c2,c3))+ORDER BY c1, c2, c3+----+a 1 -85 -15154+a 1 -56 8692+a 1 -25 15295+a 1 -5 12636+a 1 83 -14704+a 1 NULL 1353+a 2 -48 -18025+a 2 -43 13080+a 2 45 15673+a 2 NULL 3576+a 3 -72 -11122+a 3 -12 -9168+a 3 13 22338.5+a 3 14 28162+a 3 17 -22796+a 3 NULL 4958.833333333333+a 4 -101 11640+a 4 -54 -2376+a 4 -38 20744+a 4 65 -28462+a 4 NULL 386.5+a 5 -101 -12484+a 5 -31 -12907+a 5 36 -16974+a 5 NULL -14121.666666666666+a NULL NULL 306.047619047619+b 1 12 7652+b 1 29 -18218+b 1 54 -18410+b 1 NULL -9658.666666666666+b 2 -60 -21739+b 2 31 23127+b 2 63 21456+b 2 68 15874+b 2 NULL 9679.5+b 3 -101 -13217+b 3 17 14457+b 3 NULL 620+b 4 -117 19316+b 4 -111 -1967+b 4 -59 25286+b 4 17 -28070+b 4 47 20690+b 4 NULL 7051+b 5 -82 22080+b 5 -44 15788+b 5 -5 24896+b 5 62 16337+b 5 68 21576+b 5 NULL 20135.4+b NULL NULL 7732.315789473684++# csv_query_singlecol_with_rollup_avg+query TIIR+SELECT c1, c2, c3, AVG(c4)+FROM aggregate_test_100_by_sql+WHERE c1 IN ('a', 'b', NULL)+GROUP BY c1, ROLLUP (c2, c3)+ORDER BY c1, c2, c3+----+a 1 -85 -15154+a 1 -56 8692+a 1 -25 15295+a 1 -5 12636+a 1 83 -14704+a 1 NULL 1353+a 2 -48 -18025+a 2 -43 13080+a 2 45 15673+a 2 NULL 3576+a 3 -72 -11122+a 3 -12 -9168+a 3 13 22338.5+a 3 14 28162+a 3 17 -22796+a 3 NULL 4958.833333333333+a 4 -101 11640+a 4 -54 -2376+a 4 -38 20744+a 4 65 -28462+a 4 NULL 386.5+a 5 -101 -12484+a 5 -31 -12907+a 5 36 -16974+a 5 NULL -14121.666666666666+a NULL NULL 306.047619047619+b 1 12 7652+b 1 29 -18218+b 1 54 -18410+b 1 NULL -9658.666666666666+b 2 -60 -21739+b 2 31 23127+b 2 63 21456+b 2 68 15874+b 2 NULL 9679.5+b 3 -101 -13217+b 3 17 14457+b 3 NULL 620+b 4 -117 19316+b 4 -111 -1967+b 4 -59 25286+b 4 17 -28070+b 4 47 20690+b 4 NULL 7051+b 5 -82 22080+b 5 -44 15788+b 5 -5 24896+b 5 62 16337+b 5 68 21576+b 5 NULL 20135.4+b NULL NULL 7732.315789473684+# csv_query_approx_percentile_cont_with_weightquery TISELECT c1, approx_percentile_cont(c3, 0.95) AS c3_p95 FROM aggregate_test_100 GROUP BY 1 ORDER BY 1diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rsindex 05a7c2e320..da490db395 100644--- a/datafusion/expr/src/logical_plan/plan.rs+++ b/datafusion/expr/src/logical_plan/plan.rs@@ -24,8 +24,8 @@ use crate::logical_plan::display::{GraphvizVisitor, IndentVisitor};use crate::logical_plan::extension::UserDefinedLogicalNode;use crate::logical_plan::plan;use crate::utils::{- exprlist_to_fields, find_out_reference_exprs, from_plan, grouping_set_expr_count,- grouping_set_to_exprlist,+ enumerate_grouping_sets, exprlist_to_fields, find_out_reference_exprs, from_plan,+ grouping_set_expr_count, grouping_set_to_exprlist,};use crate::{build_join_schema, Expr, ExprSchemable, TableProviderFilterPushDown, TableSource,@@ -1810,6 +1810,7 @@ impl Aggregate {group_expr: Vec<Expr>,aggr_expr: Vec<Expr>,) -> Result<Self> {+ let group_expr = enumerate_grouping_sets(group_expr)?;let grouping_expr: Vec<Expr> = grouping_set_to_exprlist(group_expr.as_slice())?;let all_expr = grouping_expr.iter().chain(aggr_expr.iter());validate_unique_names("Aggregations", all_expr.clone())?;diff --git a/datafusion/expr/src/utils.rs b/datafusion/expr/src/utils.rsindex 556603f596..c8bc851807 100644--- a/datafusion/expr/src/utils.rs+++ b/datafusion/expr/src/utils.rs@@ -29,8 +29,8 @@ use crate::logical_plan::{SubqueryAlias, Union, Unnest, Values, Window,};use crate::{- BinaryExpr, Cast, DmlStatement, Expr, ExprSchemable, LogicalPlan, LogicalPlanBuilder,- Operator, TableScan, TryCast,+ BinaryExpr, Cast, DmlStatement, Expr, ExprSchemable, GroupingSet, LogicalPlan,+ LogicalPlanBuilder, Operator, TableScan, TryCast,};use arrow::datatypes::{DataType, TimeUnit};use datafusion_common::{@@ -70,6 +70,182 @@ pub fn grouping_set_expr_count(group_expr: &[Expr]) -> Result<usize> {}}+/// The power set (or powerset) of a set S is the set of all subsets of S, \+/// including the empty set and S itself.+///+/// Example:+///+/// If S is the set {x, y, z}, then all the subsets of S are \+/// {} \+/// {x} \+/// {y} \+/// {z} \+/// {x, y} \+/// {x, z} \+/// {y, z} \+/// {x, y, z} \+/// and hence the power set of S is {{}, {x}, {y}, {z}, {x, y}, {x, z}, {y, z}, {x, y, z}}.+///+/// Reference: https://en.wikipedia.org/wiki/Power_set+fn powerset<T>(slice: &[T]) -> Result<Vec<Vec<&T>>, String> {+ if slice.len() >= 64 {+ return Err("The size of the set must be less than 64.".into());+ }++ let mut v = Vec::new();+ for mask in 0..(1 << slice.len()) {+ let mut ss = vec![];+ let mut bitset = mask;+ while bitset > 0 {+ let rightmost: u64 = bitset & !(bitset - 1);+ let idx = rightmost.trailing_zeros();+ let item = slice.get(idx as usize).unwrap();+ ss.push(item);+ // zero the trailing bit+ bitset &= bitset - 1;+ }+ v.push(ss);+ }+ Ok(v)+}++/// check the number of expressions contained in the grouping_set+fn check_grouping_set_size_limit(size: usize) -> Result<()> {+ let max_grouping_set_size = 65535;+ if size > max_grouping_set_size {+ return Err(DataFusionError::Plan(format!("The number of group_expression in grouping_set exceeds the maximum limit {}, found {}", max_grouping_set_size, size)));+ }++ Ok(())+}++/// check the number of grouping_set contained in the grouping sets+fn check_grouping_sets_size_limit(size: usize) -> Result<()> {+ let max_grouping_sets_size = 4096;+ if size > max_grouping_sets_size {+ return Err(DataFusionError::Plan(format!("The number of grouping_set in grouping_sets exceeds the maximum limit {}, found {}", max_grouping_sets_size, size)));+ }++ Ok(())+}++/// Merge two grouping_set+///+///+/// Example:+///+/// (A, B), (C, D) -> (A, B, C, D)+///+/// Error:+///+/// [`DataFusionError`] The number of group_expression in grouping_set exceeds the maximum limit+fn merge_grouping_set<T: Clone>(left: &[T], right: &[T]) -> Result<Vec<T>> {+ check_grouping_set_size_limit(left.len() + right.len())?;+ Ok(left.iter().chain(right.iter()).cloned().collect())+}++/// Compute the cross product of two grouping_sets+///+///+/// Example:+///+/// \[(A, B), (C, D)], [(E), (F)\] -> \[(A, B, E), (A, B, F), (C, D, E), (C, D, F)\]+///+/// Error:+///+/// [`DataFusionError`] The number of group_expression in grouping_set exceeds the maximum limit \+/// [`DataFusionError`] The number of grouping_set in grouping_sets exceeds the maximum limit+fn cross_join_grouping_sets<T: Clone>(+ left: &[Vec<T>],+ right: &[Vec<T>],+) -> Result<Vec<Vec<T>>> {+ let grouping_sets_size = left.len() * right.len();++ check_grouping_sets_size_limit(grouping_sets_size)?;++ let mut result = Vec::with_capacity(grouping_sets_size);+ for le in left {+ for re in right {+ result.push(merge_grouping_set(le, re)?);+ }+ }+ Ok(result)+}++/// Convert multiple grouping expressions into one [`GroupingSet::GroupingSets`],\+/// if the grouping expression does not contain [`Expr::GroupingSet`] or only has one expression,\+/// no conversion will be performed.+///+/// e.g.+///+/// person.id,\+/// GROUPING SETS ((person.age, person.salary),(person.age)),\+/// ROLLUP(person.state, person.birth_date)+///+/// =>+///+/// GROUPING SETS (\+/// (person.id, person.age, person.salary),\+/// (person.id, person.age, person.salary, person.state),\+/// (person.id, person.age, person.salary, person.state, person.birth_date),\+/// (person.id, person.age),\+/// (person.id, person.age, person.state),\+/// (person.id, person.age, person.state, person.birth_date)\+/// )+pub fn enumerate_grouping_sets(group_expr: Vec<Expr>) -> Result<Vec<Expr>> {+ let has_grouping_set = group_expr+ .iter()+ .any(|expr| matches!(expr, Expr::GroupingSet(_)));+ if !has_grouping_set || group_expr.len() == 1 {+ return Ok(group_expr);+ }+ // only process mix grouping sets+ let partial_sets = group_expr+ .iter()+ .map(|expr| {+ let exprs = match expr {+ Expr::GroupingSet(GroupingSet::GroupingSets(grouping_sets)) => {+ check_grouping_sets_size_limit(grouping_sets.len())?;+ grouping_sets.iter().map(|e| e.iter().collect()).collect()+ }+ Expr::GroupingSet(GroupingSet::Cube(group_exprs)) => {+ let grouping_sets =+ powerset(group_exprs).map_err(DataFusionError::Plan)?;+ check_grouping_sets_size_limit(grouping_sets.len())?;+ grouping_sets+ }+ Expr::GroupingSet(GroupingSet::Rollup(group_exprs)) => {+ let size = group_exprs.len();+ let slice = group_exprs.as_slice();+ check_grouping_sets_size_limit(size * (size + 1) / 2 + 1)?;+ (0..(size + 1))+ .map(|i| slice[0..i].iter().collect())+ .collect()+ }+ expr => vec![vec![expr]],+ };+ Ok(exprs)+ })+ .collect::<Result<Vec<_>>>()?;++ // cross join+ let grouping_sets = partial_sets+ .into_iter()+ .map(Ok)+ .reduce(|l, r| cross_join_grouping_sets(&l?, &r?))+ .transpose()?+ .map(|e| {+ e.into_iter()+ .map(|e| e.into_iter().cloned().collect())+ .collect()+ })+ .unwrap_or_default();++ Ok(vec![Expr::GroupingSet(GroupingSet::GroupingSets(+ grouping_sets,+ ))])+}+/// Find all distinct exprs in a list of group by expressions. If the/// first element is a `GroupingSet` expression then it must be the only expr.pub fn grouping_set_to_exprlist(group_expr: &[Expr]) -> Result<Vec<Expr>> {@@ -1052,7 +1228,10 @@ pub fn find_valid_equijoin_key_pair(#[cfg(test)]mod tests {use super::*;- use crate::{col, expr, AggregateFunction, WindowFrame, WindowFunction};+ use crate::{+ col, cube, expr, grouping_set, rollup, AggregateFunction, WindowFrame,+ WindowFunction,+ };#[test]fn test_group_window_expr_by_sort_keys_empty_case() -> Result<()> {@@ -1243,4 +1422,124 @@ mod tests {}Ok(())}++ #[test]+ fn test_enumerate_grouping_sets() -> Result<()> {+ let multi_cols = vec![col("col1"), col("col2"), col("col3")];+ let simple_col = col("simple_col");+ let cube = cube(multi_cols.clone());+ let rollup = rollup(multi_cols.clone());+ let grouping_set = grouping_set(vec![multi_cols]);++ // 1. col+ let sets = enumerate_grouping_sets(vec![simple_col.clone()])?;+ let result = format!("{sets:?}");+ assert_eq!("[simple_col]", &result);++ // 2. cube+ let sets = enumerate_grouping_sets(vec![cube.clone()])?;+ let result = format!("{sets:?}");+ assert_eq!("[CUBE (col1, col2, col3)]", &result);++ // 3. rollup+ let sets = enumerate_grouping_sets(vec![rollup.clone()])?;+ let result = format!("{sets:?}");+ assert_eq!("[ROLLUP (col1, col2, col3)]", &result);++ // 4. col + cube+ let sets = enumerate_grouping_sets(vec![simple_col.clone(), cube.clone()])?;+ let result = format!("{sets:?}");+ assert_eq!(+ "[GROUPING SETS (\+ (simple_col), \+ (simple_col, col1), \+ (simple_col, col2), \+ (simple_col, col1, col2), \+ (simple_col, col3), \+ (simple_col, col1, col3), \+ (simple_col, col2, col3), \+ (simple_col, col1, col2, col3))]",+ &result+ );++ // 5. col + rollup+ let sets = enumerate_grouping_sets(vec![simple_col.clone(), rollup.clone()])?;+ let result = format!("{sets:?}");+ assert_eq!(+ "[GROUPING SETS (\+ (simple_col), \+ (simple_col, col1), \+ (simple_col, col1, col2), \+ (simple_col, col1, col2, col3))]",+ &result+ );++ // 6. col + grouping_set+ let sets =+ enumerate_grouping_sets(vec![simple_col.clone(), grouping_set.clone()])?;+ let result = format!("{sets:?}");+ assert_eq!(+ "[GROUPING SETS (\+ (simple_col, col1, col2, col3))]",+ &result+ );++ // 7. col + grouping_set + rollup+ let sets = enumerate_grouping_sets(vec![+ simple_col.clone(),+ grouping_set,+ rollup.clone(),+ ])?;+ let result = format!("{sets:?}");+ assert_eq!(+ "[GROUPING SETS (\+ (simple_col, col1, col2, col3), \+ (simple_col, col1, col2, col3, col1), \+ (simple_col, col1, col2, col3, col1, col2), \+ (simple_col, col1, col2, col3, col1, col2, col3))]",+ &result+ );++ // 8. col + cube + rollup+ let sets = enumerate_grouping_sets(vec![simple_col, cube, rollup])?;+ let result = format!("{sets:?}");+ assert_eq!(+ "[GROUPING SETS (\+ (simple_col), \+ (simple_col, col1), \+ (simple_col, col1, col2), \+ (simple_col, col1, col2, col3), \+ (simple_col, col1), \+ (simple_col, col1, col1), \+ (simple_col, col1, col1, col2), \+ (simple_col, col1, col1, col2, col3), \+ (simple_col, col2), \+ (simple_col, col2, col1), \+ (simple_col, col2, col1, col2), \+ (simple_col, col2, col1, col2, col3), \+ (simple_col, col1, col2), \+ (simple_col, col1, col2, col1), \+ (simple_col, col1, col2, col1, col2), \+ (simple_col, col1, col2, col1, col2, col3), \+ (simple_col, col3), \+ (simple_col, col3, col1), \+ (simple_col, col3, col1, col2), \+ (simple_col, col3, col1, col2, col3), \+ (simple_col, col1, col3), \+ (simple_col, col1, col3, col1), \+ (simple_col, col1, col3, col1, col2), \+ (simple_col, col1, col3, col1, col2, col3), \+ (simple_col, col2, col3), \+ (simple_col, col2, col3, col1), \+ (simple_col, col2, col3, col1, col2), \+ (simple_col, col2, col3, col1, col2, col3), \+ (simple_col, col1, col2, col3), \+ (simple_col, col1, col2, col3, col1), \+ (simple_col, col1, col2, col3, col1, col2), \+ (simple_col, col1, col2, col3, col1, col2, col3))]",+ &result+ );++ Ok(())+ }}diff --git a/datafusion/sql/tests/integration_test.rs b/datafusion/sql/tests/integration_test.rsindex a77c1f1f96..3242989f57 100644--- a/datafusion/sql/tests/integration_test.rs+++ b/datafusion/sql/tests/integration_test.rs@@ -2856,8 +2856,8 @@ fn aggregate_with_rollup() {let sql ="SELECT id, state, age, COUNT(*) FROM person GROUP BY id, ROLLUP (state, age)";let expected = "Projection: person.id, person.state, person.age, COUNT(UInt8(1))\- \n Aggregate: groupBy=[[person.id, ROLLUP (person.state, person.age)]], aggr=[[COUNT(UInt8(1))]]\- \n TableScan: person";+ \n Aggregate: groupBy=[[GROUPING SETS ((person.id), (person.id, person.state), (person.id, person.state, person.age))]], aggr=[[COUNT(UInt8(1))]]\+ \n TableScan: person";quick_test(sql, expected);}@@ -2866,8 +2866,8 @@ fn aggregate_with_rollup_with_grouping() {let sql = "SELECT id, state, age, grouping(state), grouping(age), grouping(state) + grouping(age), COUNT(*) \FROM person GROUP BY id, ROLLUP (state, age)";let expected = "Projection: person.id, person.state, person.age, GROUPING(person.state), GROUPING(person.age), GROUPING(person.state) + GROUPING(person.age), COUNT(UInt8(1))\- \n Aggregate: groupBy=[[person.id, ROLLUP (person.state, person.age)]], aggr=[[GROUPING(person.state), GROUPING(person.age), COUNT(UInt8(1))]]\- \n TableScan: person";+ \n Aggregate: groupBy=[[GROUPING SETS ((person.id), (person.id, person.state), (person.id, person.state, person.age))]], aggr=[[GROUPING(person.state), GROUPING(person.age), COUNT(UInt8(1))]]\+ \n TableScan: person";quick_test(sql, expected);}@@ -2898,8 +2898,8 @@ fn aggregate_with_cube() {let sql ="SELECT id, state, age, COUNT(*) FROM person GROUP BY id, CUBE (state, age)";let expected = "Projection: person.id, person.state, person.age, COUNT(UInt8(1))\- \n Aggregate: groupBy=[[person.id, CUBE (person.state, person.age)]], aggr=[[COUNT(UInt8(1))]]\- \n TableScan: person";+ \n Aggregate: groupBy=[[GROUPING SETS ((person.id), (person.id, person.state), (person.id, person.age), (person.id, person.state, person.age))]], aggr=[[COUNT(UInt8(1))]]\+ \n TableScan: person";quick_test(sql, expected);}@@ -2915,8 +2915,8 @@ fn round_decimal() {fn aggregate_with_grouping_sets() {let sql = "SELECT id, state, age, COUNT(*) FROM person GROUP BY id, GROUPING SETS ((state), (state, age), (id, state))";let expected = "Projection: person.id, person.state, person.age, COUNT(UInt8(1))\- \n Aggregate: groupBy=[[person.id, GROUPING SETS ((person.state), (person.state, person.age), (person.id, person.state))]], aggr=[[COUNT(UInt8(1))]]\- \n TableScan: person";+ \n Aggregate: groupBy=[[GROUPING SETS ((person.id, person.state), (person.id, person.state, person.age), (person.id, person.id, person.state))]], aggr=[[COUNT(UInt8(1))]]\+ \n TableScan: person";quick_test(sql, expected);}@@ -3893,6 +3893,38 @@ fn test_inner_join_with_cast_key() {quick_test(sql, expected);}+#[test]+fn test_multi_grouping_sets() {+ let sql = "SELECT person.id, person.age+ FROM person+ GROUP BY+ person.id,+ GROUPING SETS ((person.age,person.salary),(person.age))";++ let expected = "Projection: person.id, person.age\+ \n Aggregate: groupBy=[[GROUPING SETS ((person.id, person.age, person.salary), (person.id, person.age))]], aggr=[[]]\+ \n TableScan: person";+ quick_test(sql, expected);++ let sql = "SELECT person.id, person.age+ FROM person+ GROUP BY+ person.id,+ GROUPING SETS ((person.age, person.salary),(person.age)),+ ROLLUP(person.state, person.birth_date)";++ let expected = "Projection: person.id, person.age\+ \n Aggregate: groupBy=[[GROUPING SETS (\+ (person.id, person.age, person.salary), \+ (person.id, person.age, person.salary, person.state), \+ (person.id, person.age, person.salary, person.state, person.birth_date), \+ (person.id, person.age), \+ (person.id, person.age, person.state), \+ (person.id, person.age, person.state, person.birth_date))]], aggr=[[]]\+ \n TableScan: person";+ quick_test(sql, expected);+}+fn assert_field_not_found(err: DataFusionError, name: &str) {match err {DataFusionError::SchemaError { .. } => {