Skip to main content

datafusion_optimizer/
eliminate_group_by_constant.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//! [`EliminateGroupByConstant`] removes constant and functionally redundant
6//! expressions from `GROUP BY` clause
7use crate::optimizer::ApplyOrder;
8use crate::{OptimizerConfig, OptimizerRule};
9
10use std::collections::HashSet;
11use std::sync::Arc;
12
13use datafusion_common::Result;
14use datafusion_common::tree_node::Transformed;
15use datafusion_expr::{Aggregate, Expr, LogicalPlan, Projection, Volatility};
16
17/// Optimizer rule that removes constant expressions from `GROUP BY` clause
18/// and places additional projection on top of aggregation, to preserve
19/// original schema
20#[derive(Default, Debug)]
21pub struct EliminateGroupByConstant {}
22
23impl EliminateGroupByConstant {
24    pub fn new() -> Self {
25        Self {}
26    }
27}
28
29impl OptimizerRule for EliminateGroupByConstant {
30    fn rewrite(
31        &self,
32        plan: LogicalPlan,
33        _config: &dyn OptimizerConfig,
34    ) -> Result<Transformed<LogicalPlan>> {
35        match plan {
36            LogicalPlan::Aggregate(aggregate) => {
37                // Collect bare column references in GROUP BY
38                let group_by_columns: HashSet<&datafusion_common::Column> = aggregate
39                    .group_expr
40                    .iter()
41                    .filter_map(|expr| match expr {
42                        Expr::Column(c) => Some(c),
43                        _ => None,
44                    })
45                    .collect();
46
47                let is_redundant: Vec<bool> = aggregate
48                    .group_expr
49                    .iter()
50                    .map(|expr| is_redundant_group_expr(expr, &group_by_columns))
51                    .collect();
52                let redundant_count = is_redundant.iter().filter(|r| **r).count();
53                // Return now if no simplification can be done. We also bail out
54                // if applying the optimization would eliminate all of the
55                // grouping expressions (e.g., GROUP BY on only constant
56                // expressions): this would turn a grouped aggregate into an
57                // ungrouped aggregate, which changes query semantics (grouped
58                // aggregates produce an empty result set on an empty input,
59                // whereas ungrouped aggregates return a single row).
60                if redundant_count == 0 || redundant_count == aggregate.group_expr.len() {
61                    return Ok(Transformed::no(LogicalPlan::Aggregate(aggregate)));
62                }
63
64                let original_schema = Arc::clone(&aggregate.schema);
65                let required = aggregate
66                    .group_expr
67                    .iter()
68                    .zip(&is_redundant)
69                    .filter(|(_, redundant)| !**redundant)
70                    .map(|(expr, _)| expr.clone())
71                    .collect();
72                let simplified_aggregate =
73                    Aggregate::try_new(aggregate.input, required, aggregate.aggr_expr)?;
74                let simplified_schema = Arc::clone(&simplified_aggregate.schema);
75
76                // Refer to the output columns of the simplified aggregate by
77                // position. Do not re-plan the original group expressions on top
78                // of it: an expression can refer to an input column through a
79                // name that the aggregate output does not carry, so a rebuilt
80                // projection does not always resolve. A redundant expression
81                // refers only to bare GROUP BY columns, which the simplified
82                // aggregate outputs unchanged.
83                let mut projection_expr =
84                    Vec::with_capacity(original_schema.fields().len());
85                let mut next_output = 0;
86                for (i, (expr, redundant)) in aggregate
87                    .group_expr
88                    .into_iter()
89                    .zip(is_redundant)
90                    .enumerate()
91                {
92                    let (qualifier, field) = original_schema.qualified_field(i);
93                    let expr = if redundant {
94                        expr
95                    } else {
96                        let column =
97                            Expr::from(simplified_schema.qualified_field(next_output));
98                        next_output += 1;
99                        column
100                    };
101                    let expr = if expr.qualified_name()
102                        == (qualifier.cloned(), field.name().clone())
103                    {
104                        expr
105                    } else {
106                        expr.alias_qualified(qualifier.cloned(), field.name())
107                    };
108                    projection_expr.push(expr);
109                }
110                for i in next_output..simplified_schema.fields().len() {
111                    projection_expr
112                        .push(Expr::from(simplified_schema.qualified_field(i)));
113                }
114
115                let projection = LogicalPlan::Projection(Projection::try_new(
116                    projection_expr,
117                    Arc::new(LogicalPlan::Aggregate(simplified_aggregate)),
118                )?);
119
120                Ok(Transformed::yes(projection))
121            }
122            _ => Ok(Transformed::no(plan)),
123        }
124    }
125
126    fn name(&self) -> &str {
127        "eliminate_group_by_constant"
128    }
129
130    fn apply_order(&self) -> Option<ApplyOrder> {
131        Some(ApplyOrder::BottomUp)
132    }
133}
134
135/// Checks if a GROUP BY expression is redundant (can be removed without
136/// changing grouping semantics). An expression is redundant if it is a
137/// deterministic function of constants and columns already present as bare
138/// column references in the GROUP BY.
139fn is_redundant_group_expr(
140    expr: &Expr,
141    group_by_columns: &HashSet<&datafusion_common::Column>,
142) -> bool {
143    // Bare column references are never redundant - they define the grouping
144    if matches!(expr, Expr::Column(_)) {
145        return false;
146    }
147    is_deterministic_of(expr, group_by_columns)
148}
149
150/// Returns true if `expr` is a deterministic expression whose only column
151/// references are contained in `known_columns`.
152fn is_deterministic_of(
153    expr: &Expr,
154    known_columns: &HashSet<&datafusion_common::Column>,
155) -> bool {
156    match expr {
157        Expr::Alias(e) => is_deterministic_of(&e.expr, known_columns),
158        Expr::Column(c) => known_columns.contains(c),
159        Expr::Literal(_, _) => true,
160        Expr::BinaryExpr(e) => {
161            is_deterministic_of(&e.left, known_columns)
162                && is_deterministic_of(&e.right, known_columns)
163        }
164        Expr::ScalarFunction(e) => {
165            matches!(
166                e.func.signature().volatility,
167                Volatility::Immutable | Volatility::Stable
168            ) && e
169                .args
170                .iter()
171                .all(|arg| is_deterministic_of(arg, known_columns))
172        }
173        Expr::Cast(e) => is_deterministic_of(&e.expr, known_columns),
174        Expr::TryCast(e) => is_deterministic_of(&e.expr, known_columns),
175        Expr::Negative(e) => is_deterministic_of(e, known_columns),
176        _ => false,
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use crate::OptimizerContext;
184    use crate::assert_optimized_plan_eq_snapshot;
185    use crate::test::*;
186
187    use arrow::datatypes::DataType;
188    use datafusion_expr::expr::ScalarFunction;
189    use datafusion_expr::{
190        ColumnarValue, LogicalPlanBuilder, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl,
191        Signature, TypeSignature, col, lit,
192    };
193
194    use datafusion_functions_aggregate::expr_fn::count;
195
196    use std::sync::Arc;
197
198    macro_rules! assert_optimized_plan_equal {
199        (
200            $plan:expr,
201            @ $expected:literal $(,)?
202        ) => {{
203            let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
204            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(EliminateGroupByConstant::new())];
205            assert_optimized_plan_eq_snapshot!(
206                optimizer_ctx,
207                rules,
208                $plan,
209                @ $expected,
210            )
211        }};
212    }
213
214    #[derive(Debug, PartialEq, Eq, Hash)]
215    struct ScalarUDFMock {
216        signature: Signature,
217    }
218
219    impl ScalarUDFMock {
220        fn new_with_volatility(volatility: Volatility) -> Self {
221            Self {
222                signature: Signature::new(TypeSignature::Any(1), volatility),
223            }
224        }
225    }
226
227    impl ScalarUDFImpl for ScalarUDFMock {
228        fn name(&self) -> &str {
229            "scalar_fn_mock"
230        }
231        fn signature(&self) -> &Signature {
232            &self.signature
233        }
234        fn return_type(&self, _args: &[DataType]) -> Result<DataType> {
235            Ok(DataType::Int32)
236        }
237        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
238            unimplemented!()
239        }
240    }
241
242    #[test]
243    fn test_eliminate_gby_literal() -> Result<()> {
244        let scan = test_table_scan()?;
245        let plan = LogicalPlanBuilder::from(scan)
246            .aggregate(vec![col("a"), lit(1u32)], vec![count(col("c"))])?
247            .build()?;
248
249        assert_optimized_plan_equal!(plan, @r"
250        Projection: test.a, UInt32(1), count(test.c)
251          Aggregate: groupBy=[[test.a]], aggr=[[count(test.c)]]
252            TableScan: test
253        ")
254    }
255
256    /// A required GROUP BY expression refers to an input column without the
257    /// qualifier that the input schema gives it. `ExtractLeafExpressions`
258    /// creates such references when it moves an extraction projection below a
259    /// `SubqueryAlias`. The rule must keep the plan valid.
260    #[test]
261    fn test_eliminate_with_unqualified_reference_to_qualified_input() -> Result<()> {
262        let input = LogicalPlanBuilder::from(test_table_scan()?)
263            .alias("m")?
264            .build()?;
265        let plan = LogicalPlan::Aggregate(Aggregate::try_new(
266            Arc::new(input),
267            vec![
268                Expr::Column(datafusion_common::Column::new_unqualified("b")).alias("k"),
269                col("m.a"),
270                col("m.a") + lit(1u32),
271            ],
272            vec![count(col("m.c"))],
273        )?);
274
275        assert_optimized_plan_equal!(plan, @r"
276        Projection: k, m.a, m.a + UInt32(1), count(m.c)
277          Aggregate: groupBy=[[b AS k, m.a]], aggr=[[count(m.c)]]
278            SubqueryAlias: m
279              TableScan: test
280        ")
281    }
282
283    #[test]
284    fn test_no_op_only_constant_with_aggregate() -> Result<()> {
285        let scan = test_table_scan()?;
286        let plan = LogicalPlanBuilder::from(scan)
287            .aggregate(vec![lit("test"), lit(123u32)], vec![count(col("c"))])?
288            .build()?;
289
290        assert_optimized_plan_equal!(plan, @r#"
291        Aggregate: groupBy=[[Utf8("test"), UInt32(123)]], aggr=[[count(test.c)]]
292          TableScan: test
293        "#)
294    }
295
296    #[test]
297    fn test_no_op_no_constants() -> Result<()> {
298        let scan = test_table_scan()?;
299        let plan = LogicalPlanBuilder::from(scan)
300            .aggregate(vec![col("a"), col("b")], vec![count(col("c"))])?
301            .build()?;
302
303        assert_optimized_plan_equal!(plan, @r"
304        Aggregate: groupBy=[[test.a, test.b]], aggr=[[count(test.c)]]
305          TableScan: test
306        ")
307    }
308
309    #[test]
310    fn test_no_op_only_constant() -> Result<()> {
311        let scan = test_table_scan()?;
312        let plan = LogicalPlanBuilder::from(scan)
313            .aggregate(vec![lit(123u32)], Vec::<Expr>::new())?
314            .build()?;
315
316        assert_optimized_plan_equal!(plan, @r"
317        Aggregate: groupBy=[[UInt32(123)]], aggr=[[]]
318          TableScan: test
319        ")
320    }
321
322    #[test]
323    fn test_eliminate_constant_with_alias() -> Result<()> {
324        let scan = test_table_scan()?;
325        let plan = LogicalPlanBuilder::from(scan)
326            .aggregate(
327                vec![lit(123u32).alias("const"), col("a")],
328                vec![count(col("c"))],
329            )?
330            .build()?;
331
332        assert_optimized_plan_equal!(plan, @r"
333        Projection: UInt32(123) AS const, test.a, count(test.c)
334          Aggregate: groupBy=[[test.a]], aggr=[[count(test.c)]]
335            TableScan: test
336        ")
337    }
338
339    #[test]
340    fn test_eliminate_scalar_fn_with_constant_arg() -> Result<()> {
341        let udf = ScalarUDF::new_from_impl(ScalarUDFMock::new_with_volatility(
342            Volatility::Immutable,
343        ));
344        let udf_expr =
345            Expr::ScalarFunction(ScalarFunction::new_udf(udf.into(), vec![lit(123u32)]));
346        let scan = test_table_scan()?;
347        let plan = LogicalPlanBuilder::from(scan)
348            .aggregate(vec![udf_expr, col("a")], vec![count(col("c"))])?
349            .build()?;
350
351        assert_optimized_plan_equal!(plan, @r"
352        Projection: scalar_fn_mock(UInt32(123)), test.a, count(test.c)
353          Aggregate: groupBy=[[test.a]], aggr=[[count(test.c)]]
354            TableScan: test
355        ")
356    }
357
358    #[test]
359    fn test_eliminate_deterministic_expr_of_group_by_column() -> Result<()> {
360        let scan = test_table_scan()?;
361        // GROUP BY a, a - 1, a - 2, a - 3  ->  GROUP BY a
362        let plan = LogicalPlanBuilder::from(scan)
363            .aggregate(
364                vec![
365                    col("a"),
366                    col("a") - lit(1u32),
367                    col("a") - lit(2u32),
368                    col("a") - lit(3u32),
369                ],
370                vec![count(col("c"))],
371            )?
372            .build()?;
373
374        assert_optimized_plan_equal!(plan, @r"
375        Projection: test.a, test.a - UInt32(1), test.a - UInt32(2), test.a - UInt32(3), count(test.c)
376          Aggregate: groupBy=[[test.a]], aggr=[[count(test.c)]]
377            TableScan: test
378        ")
379    }
380
381    #[test]
382    fn test_no_eliminate_independent_columns() -> Result<()> {
383        // GROUP BY a, b - 1 should NOT eliminate b - 1 (b is not a group by column)
384        let scan = test_table_scan()?;
385        let plan = LogicalPlanBuilder::from(scan)
386            .aggregate(vec![col("a"), col("b") - lit(1u32)], vec![count(col("c"))])?
387            .build()?;
388
389        assert_optimized_plan_equal!(plan, @r"
390        Aggregate: groupBy=[[test.a, test.b - UInt32(1)]], aggr=[[count(test.c)]]
391          TableScan: test
392        ")
393    }
394
395    #[test]
396    fn test_no_op_volatile_scalar_fn_with_constant_arg() -> Result<()> {
397        let udf = ScalarUDF::new_from_impl(ScalarUDFMock::new_with_volatility(
398            Volatility::Volatile,
399        ));
400        let udf_expr =
401            Expr::ScalarFunction(ScalarFunction::new_udf(udf.into(), vec![lit(123u32)]));
402        let scan = test_table_scan()?;
403        let plan = LogicalPlanBuilder::from(scan)
404            .aggregate(vec![udf_expr, col("a")], vec![count(col("c"))])?
405            .build()?;
406
407        assert_optimized_plan_equal!(plan, @r"
408        Aggregate: groupBy=[[scalar_fn_mock(UInt32(123)), test.a]], aggr=[[count(test.c)]]
409          TableScan: test
410        ")
411    }
412}