Skip to main content

datafusion_optimizer/analyzer/
resolve_grouping_function.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Analyzed rule to replace TableScan references
6//! such as DataFrames and Views and inlines the LogicalPlan.
7
8use std::cmp::Ordering;
9use std::collections::HashMap;
10use std::sync::Arc;
11
12use crate::analyzer::AnalyzerRule;
13
14use arrow::datatypes::DataType;
15use datafusion_common::config::ConfigOptions;
16use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode};
17use datafusion_common::{
18    Column, DFSchema, Result, ScalarValue, internal_datafusion_err, plan_err,
19};
20use datafusion_expr::expr::{AggregateFunction, Alias};
21use datafusion_expr::logical_plan::LogicalPlan;
22use datafusion_expr::utils::grouping_set_to_exprlist;
23use datafusion_expr::{
24    Aggregate, Expr, Projection, bitwise_and, bitwise_or, bitwise_shift_left,
25    bitwise_shift_right, cast,
26};
27use itertools::Itertools;
28
29/// Replaces grouping aggregation function with value derived from internal grouping id
30#[derive(Default, Debug)]
31pub struct ResolveGroupingFunction;
32
33impl ResolveGroupingFunction {
34    pub fn new() -> Self {
35        Self {}
36    }
37}
38
39impl AnalyzerRule for ResolveGroupingFunction {
40    fn analyze(&self, plan: LogicalPlan, _: &ConfigOptions) -> Result<LogicalPlan> {
41        plan.transform_up(analyze_internal).data()
42    }
43
44    fn name(&self) -> &str {
45        "resolve_grouping_function"
46    }
47}
48
49/// Create a map from grouping expr to index in the internal grouping id.
50///
51/// For more details on how the grouping id bitmap works the documentation for
52/// [[Aggregate::INTERNAL_GROUPING_ID]]
53fn group_expr_to_bitmap_index(group_expr: &[Expr]) -> Result<HashMap<&Expr, usize>> {
54    Ok(grouping_set_to_exprlist(group_expr)?
55        .into_iter()
56        .rev()
57        .enumerate()
58        .map(|(idx, v)| (v, idx))
59        .collect::<HashMap<_, _>>())
60}
61
62#[allow(clippy::allow_attributes, clippy::mutable_key_type)] // Expr contains Arc with interior mutability but is intentionally used as hash key
63fn replace_grouping_exprs(
64    input: Arc<LogicalPlan>,
65    schema: &DFSchema,
66    group_expr: Vec<Expr>,
67    aggr_expr: Vec<Expr>,
68) -> Result<LogicalPlan> {
69    // Create HashMap from Expr to index in the grouping_id bitmap
70    let is_grouping_set = matches!(group_expr.as_slice(), [Expr::GroupingSet(_)]);
71    let group_expr_to_bitmap_index = group_expr_to_bitmap_index(&group_expr)?;
72    let columns = schema.columns();
73    let mut new_agg_expr = Vec::new();
74    let grouping_id_len = usize::from(is_grouping_set);
75    let group_expr_len = columns.len() - aggr_expr.len() - grouping_id_len;
76    let mut projection_exprs = Vec::with_capacity(group_expr_len + aggr_expr.len());
77    projection_exprs.extend(
78        columns
79            .iter()
80            .take(group_expr_len)
81            .map(|column| Expr::Column(column.clone())),
82    );
83    for (expr, column) in aggr_expr
84        .into_iter()
85        .zip(columns.into_iter().skip(group_expr_len + grouping_id_len))
86    {
87        let grouping_id_type = is_grouping_set
88            .then(|| {
89                schema
90                    .field_with_name(None, Aggregate::INTERNAL_GROUPING_ID)
91                    .map(|f| f.data_type().clone())
92            })
93            .transpose()?;
94        match expr {
95            Expr::AggregateFunction(ref function) if is_grouping_function(&expr) => {
96                let grouping_expr = grouping_function_on_id(
97                    function,
98                    &group_expr_to_bitmap_index,
99                    grouping_id_type,
100                )?;
101                projection_exprs.push(Expr::Alias(Alias::new(
102                    grouping_expr,
103                    column.relation,
104                    column.name,
105                )));
106            }
107            Expr::Alias(Alias {
108                ref relation,
109                ref name,
110                ..
111            }) if is_grouping_function(&expr) => {
112                let function = unwrap_alias_to_grouping_function(&expr)?;
113                let grouping_expr = grouping_function_on_id(
114                    function,
115                    &group_expr_to_bitmap_index,
116                    grouping_id_type,
117                )?;
118                // Preserve the outermost user-provided alias
119                projection_exprs.push(Expr::Alias(Alias::new(
120                    grouping_expr,
121                    relation.clone(),
122                    name.clone(),
123                )));
124            }
125            _ => {
126                projection_exprs.push(Expr::Column(column));
127                new_agg_expr.push(expr);
128            }
129        }
130    }
131    // Recreate aggregate without grouping functions
132    let new_aggregate =
133        LogicalPlan::Aggregate(Aggregate::try_new(input, group_expr, new_agg_expr)?);
134    // Create projection with grouping functions calculations
135    let projection = LogicalPlan::Projection(Projection::try_new(
136        projection_exprs,
137        new_aggregate.into(),
138    )?);
139    Ok(projection)
140}
141
142fn analyze_internal(plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
143    // rewrite any subqueries in the plan first
144    let transformed_plan =
145        plan.map_subqueries(|plan| plan.transform_up(analyze_internal))?;
146
147    let transformed_plan = transformed_plan.transform_data(|plan| match plan {
148        LogicalPlan::Aggregate(Aggregate {
149            input,
150            group_expr,
151            aggr_expr,
152            schema,
153            ..
154        }) if contains_grouping_function(&aggr_expr) => Ok(Transformed::yes(
155            replace_grouping_exprs(input, schema.as_ref(), group_expr, aggr_expr)?,
156        )),
157        _ => Ok(Transformed::no(plan)),
158    })?;
159
160    Ok(transformed_plan)
161}
162
163/// Recursively unwrap `Expr::Alias` nodes to reach the inner `AggregateFunction`.
164/// Returns an error if the innermost expression is not an `AggregateFunction`,
165/// which should not happen if `is_grouping_function` returned true.
166fn unwrap_alias_to_grouping_function(expr: &Expr) -> Result<&AggregateFunction> {
167    match expr {
168        Expr::AggregateFunction(function) => Ok(function),
169        Expr::Alias(Alias { expr, .. }) => unwrap_alias_to_grouping_function(expr),
170        _ => plan_err!("Expected grouping aggregate function inside alias, got {expr}"),
171    }
172}
173
174fn is_grouping_function(expr: &Expr) -> bool {
175    // TODO: Do something better than name here should grouping be a built
176    // in expression?
177    match expr {
178        Expr::AggregateFunction(AggregateFunction { func, .. }) => {
179            func.name() == "grouping"
180        }
181        Expr::Alias(Alias { expr, .. }) => is_grouping_function(expr),
182        _ => false,
183    }
184}
185
186fn contains_grouping_function(exprs: &[Expr]) -> bool {
187    exprs.iter().any(is_grouping_function)
188}
189
190/// Validate that the arguments to the grouping function are in the group by clause.
191#[allow(clippy::allow_attributes, clippy::mutable_key_type)] // Expr contains Arc with interior mutability but is intentionally used as hash key
192fn validate_args(
193    function: &AggregateFunction,
194    group_by_expr: &HashMap<&Expr, usize>,
195) -> Result<()> {
196    let expr_not_in_group_by = function
197        .params
198        .args
199        .iter()
200        .find(|expr| !group_by_expr.contains_key(expr));
201    if let Some(expr) = expr_not_in_group_by {
202        plan_err!(
203            "Argument {} to grouping function is not in grouping columns {}",
204            expr,
205            group_by_expr.keys().map(|e| e.to_string()).join(", ")
206        )
207    } else {
208        Ok(())
209    }
210}
211
212#[allow(clippy::allow_attributes, clippy::mutable_key_type)] // Expr contains Arc with interior mutability but is intentionally used as hash key
213fn grouping_function_on_id(
214    function: &AggregateFunction,
215    group_by_expr: &HashMap<&Expr, usize>,
216    // None means not a grouping set (result is always 0).
217    grouping_id_type: Option<DataType>,
218) -> Result<Expr> {
219    validate_args(function, group_by_expr)?;
220    let args = &function.params.args;
221
222    // Postgres allows grouping function for group by without grouping sets, the result is then
223    // always 0
224    let Some(grouping_id_type) = grouping_id_type else {
225        return Ok(Expr::Literal(ScalarValue::from(0i32), None));
226    };
227
228    // Use the actual __grouping_id column type to size literals correctly. This
229    // accounts for duplicate-ordinal bits that `Aggregate::grouping_id_type`
230    // packs into the high bits of the column, which a simple count of grouping
231    // expressions would miss.
232    let literal = |value: usize| match &grouping_id_type {
233        DataType::UInt8 => Expr::Literal(ScalarValue::from(value as u8), None),
234        DataType::UInt16 => Expr::Literal(ScalarValue::from(value as u16), None),
235        DataType::UInt32 => Expr::Literal(ScalarValue::from(value as u32), None),
236        DataType::UInt64 => Expr::Literal(ScalarValue::from(value as u64), None),
237        other => panic!("unexpected __grouping_id type: {other}"),
238    };
239    let grouping_id_column = Expr::Column(Column::from(Aggregate::INTERNAL_GROUPING_ID));
240    if args.len() == group_by_expr.len()
241        && args
242            .iter()
243            .rev()
244            .enumerate()
245            .all(|(idx, expr)| group_by_expr.get(expr) == Some(&idx))
246    {
247        let n = group_by_expr.len();
248        // Mask the ordinal bits above position `n` so only the semantic bitmask is visible.
249        // checked_shl returns None when n >= 64 (all bits are semantic), mapping to u64::MAX.
250        let semantic_mask: u64 = 1u64.checked_shl(n as u32).map_or(u64::MAX, |m| m - 1);
251        let masked_id =
252            bitwise_and(grouping_id_column.clone(), literal(semantic_mask as usize));
253        return Ok(cast(masked_id, DataType::Int32));
254    }
255
256    args.iter()
257        .rev()
258        .enumerate()
259        .map(|(arg_idx, expr)| {
260            group_by_expr.get(expr).map(|group_by_idx| {
261                let group_by_bit =
262                    bitwise_and(grouping_id_column.clone(), literal(1 << group_by_idx));
263                match group_by_idx.cmp(&arg_idx) {
264                    Ordering::Less => {
265                        bitwise_shift_left(group_by_bit, literal(arg_idx - group_by_idx))
266                    }
267                    Ordering::Greater => {
268                        bitwise_shift_right(group_by_bit, literal(group_by_idx - arg_idx))
269                    }
270                    Ordering::Equal => group_by_bit,
271                }
272            })
273        })
274        .collect::<Option<Vec<_>>>()
275        .and_then(|bit_exprs| {
276            bit_exprs
277                .into_iter()
278                .reduce(bitwise_or)
279                .map(|expr| cast(expr, DataType::Int32))
280        })
281        .ok_or_else(|| {
282            internal_datafusion_err!("Grouping sets should contains at least one element")
283        })
284}