Skip to main content

datafusion_optimizer/
eliminate_duplicated_expr.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//! [`EliminateDuplicatedExpr`] Removes redundant expressions
6
7use crate::optimizer::ApplyOrder;
8use crate::{OptimizerConfig, OptimizerRule};
9use datafusion_common::tree_node::Transformed;
10use datafusion_common::{Result, get_required_sort_exprs_indices, internal_err};
11use datafusion_expr::logical_plan::LogicalPlan;
12use datafusion_expr::utils::passthrough_field_index;
13use datafusion_expr::{Aggregate, Expr, Sort, SortExpr};
14use std::hash::{Hash, Hasher};
15
16use indexmap::IndexSet;
17
18/// Optimization rule that eliminate duplicated expr.
19#[derive(Default, Debug)]
20pub struct EliminateDuplicatedExpr;
21
22impl EliminateDuplicatedExpr {
23    #[expect(missing_docs)]
24    pub fn new() -> Self {
25        Self {}
26    }
27}
28// use this structure to avoid initial clone
29#[derive(Eq, Clone, Debug)]
30struct SortExprWrapper(SortExpr);
31impl PartialEq for SortExprWrapper {
32    fn eq(&self, other: &Self) -> bool {
33        self.0.expr == other.0.expr
34    }
35}
36impl Hash for SortExprWrapper {
37    fn hash<H: Hasher>(&self, state: &mut H) {
38        self.0.expr.hash(state);
39    }
40}
41impl OptimizerRule for EliminateDuplicatedExpr {
42    fn apply_order(&self) -> Option<ApplyOrder> {
43        Some(ApplyOrder::TopDown)
44    }
45
46    fn rewrite(
47        &self,
48        plan: LogicalPlan,
49        _config: &dyn OptimizerConfig,
50    ) -> Result<Transformed<LogicalPlan>> {
51        match plan {
52            LogicalPlan::Sort(sort) => {
53                let len = sort.expr.len();
54                let unique_exprs: Vec<_> = sort
55                    .expr
56                    .into_iter()
57                    .map(SortExprWrapper)
58                    .collect::<IndexSet<_>>()
59                    .into_iter()
60                    .map(|wrapper| wrapper.0)
61                    .collect();
62
63                let sort_input_indices = unique_exprs
64                    .iter()
65                    .map(|sort_expr| {
66                        passthrough_field_index(&sort_expr.expr, sort.input.schema())
67                    })
68                    .collect::<Vec<_>>();
69                let required_indices = get_required_sort_exprs_indices(
70                    sort.input.schema().as_ref(),
71                    &sort_input_indices,
72                );
73
74                let unique_exprs = if required_indices.len() < unique_exprs.len() {
75                    required_indices
76                        .into_iter()
77                        .map(|idx| unique_exprs[idx].clone())
78                        .collect()
79                } else {
80                    unique_exprs
81                };
82
83                let transformed = if len != unique_exprs.len() {
84                    Transformed::yes
85                } else {
86                    Transformed::no
87                };
88
89                if unique_exprs.is_empty() {
90                    return internal_err!(
91                        "FD pruning unexpectedly removed all ORDER BY expressions"
92                    );
93                }
94
95                Ok(transformed(LogicalPlan::Sort(Sort {
96                    expr: unique_exprs,
97                    input: sort.input,
98                    fetch: sort.fetch,
99                })))
100            }
101            LogicalPlan::Aggregate(mut agg) => {
102                let len = agg.group_expr.len();
103                // With zero or one group expression, there is nothing to deduplicate.
104                if len <= 1 {
105                    return Ok(Transformed::no(LogicalPlan::Aggregate(agg)));
106                }
107
108                let unique_exprs: Vec<Expr> = agg
109                    .group_expr
110                    .into_iter()
111                    .collect::<IndexSet<_>>()
112                    .into_iter()
113                    .collect();
114
115                if len == unique_exprs.len() {
116                    // No duplicate expressions were found, so we can reuse the
117                    // existing schema (including functional dependencies).
118                    agg.group_expr = unique_exprs;
119                    return Ok(Transformed::no(LogicalPlan::Aggregate(agg)));
120                }
121
122                Aggregate::try_new(agg.input, unique_exprs, agg.aggr_expr)
123                    .map(|f| Transformed::yes(LogicalPlan::Aggregate(f)))
124            }
125            _ => Ok(Transformed::no(plan)),
126        }
127    }
128    fn name(&self) -> &str {
129        "eliminate_duplicated_expr"
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use crate::OptimizerContext;
137    use crate::assert_optimized_plan_eq_snapshot;
138    use crate::test::*;
139    use datafusion_expr::{
140        GroupingSet, col, lit, logical_plan::builder::LogicalPlanBuilder,
141    };
142    use datafusion_functions_aggregate::expr_fn::sum;
143    use std::sync::Arc;
144
145    macro_rules! assert_optimized_plan_equal {
146        (
147            $plan:expr,
148            @ $expected:literal $(,)?
149        ) => {{
150            let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
151            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> =
152                vec![Arc::new(EliminateDuplicatedExpr::new())];
153            assert_optimized_plan_eq_snapshot!(
154                optimizer_ctx,
155                rules,
156                $plan,
157                @ $expected,
158            )
159        }};
160    }
161
162    #[test]
163    fn eliminate_sort_expr() -> Result<()> {
164        let table_scan = test_table_scan().unwrap();
165        let plan = LogicalPlanBuilder::from(table_scan)
166            .sort_by(vec![col("a"), col("a"), col("b"), col("c")])?
167            .limit(5, Some(10))?
168            .build()?;
169
170        assert_optimized_plan_equal!(plan, @r"
171        Limit: skip=5, fetch=10
172          Sort: test.a ASC NULLS LAST, test.b ASC NULLS LAST, test.c ASC NULLS LAST
173            TableScan: test
174        ")
175    }
176
177    #[test]
178    fn eliminate_sort_exprs_with_options() -> Result<()> {
179        let table_scan = test_table_scan().unwrap();
180        let sort_exprs = vec![
181            col("a").sort(true, true),
182            col("b").sort(true, false),
183            col("a").sort(false, false),
184            col("b").sort(false, true),
185        ];
186        let plan = LogicalPlanBuilder::from(table_scan)
187            .sort(sort_exprs)?
188            .limit(5, Some(10))?
189            .build()?;
190
191        assert_optimized_plan_equal!(plan, @r"
192        Limit: skip=5, fetch=10
193          Sort: test.a ASC NULLS FIRST, test.b ASC NULLS LAST
194            TableScan: test
195        ")
196    }
197
198    /// A no-op must preserve both the plan and its already computed schema.
199    fn assert_unchanged_aggregate(plan: LogicalPlan) -> Result<()> {
200        let schema = Arc::clone(plan.schema());
201        let result = EliminateDuplicatedExpr::new()
202            .rewrite(plan.clone(), &OptimizerContext::new())?;
203        assert!(!result.transformed);
204        assert_eq!(result.data, plan);
205        assert!(Arc::ptr_eq(result.data.schema(), &schema));
206        Ok(())
207    }
208
209    #[test]
210    fn unchanged_aggregates_reuse_schema() -> Result<()> {
211        for group_expr in [vec![], vec![col("a")], vec![col("b"), col("a") + lit(1u32)]] {
212            let plan = LogicalPlanBuilder::from(test_table_scan()?)
213                .aggregate(group_expr, vec![sum(col("c")).alias("total")])?
214                .build()?;
215            assert_unchanged_aggregate(plan)?;
216        }
217        Ok(())
218    }
219
220    #[test]
221    fn unchanged_grouping_sets_reuse_schema() -> Result<()> {
222        // Repeat "a" to check that this rule leaves the GroupingSet's contents unchanged.
223        let grouping_set = GroupingSet::GroupingSets(vec![
224            vec![col("a"), col("b")],
225            vec![col("a")],
226            vec![col("a")],
227            vec![],
228        ]);
229        let plan = LogicalPlanBuilder::from(test_table_scan()?)
230            .aggregate(vec![Expr::GroupingSet(grouping_set)], vec![sum(col("c"))])?
231            .build()?;
232        assert_unchanged_aggregate(plan)
233    }
234
235    #[test]
236    fn eliminate_duplicate_group_exprs() -> Result<()> {
237        let input = Arc::new(test_table_scan()?);
238        let a = col("test.a");
239        let b = col("test.b");
240        let computed = a.clone() + lit(1u32);
241        let aggr_expr = vec![sum(col("test.c")).alias("total")];
242        let plan = LogicalPlan::Aggregate(Aggregate::try_new(
243            Arc::clone(&input),
244            vec![
245                b.clone(),
246                computed.clone(),
247                b.clone(),
248                a.clone(),
249                computed.clone(),
250            ],
251            aggr_expr.clone(),
252        )?);
253        let expected = LogicalPlan::Aggregate(Aggregate::try_new(
254            input,
255            // Keep the order of the first occurrence of each expression.
256            vec![b, computed, a],
257            aggr_expr,
258        )?);
259
260        let result =
261            EliminateDuplicatedExpr::new().rewrite(plan, &OptimizerContext::new())?;
262        assert!(result.transformed);
263        assert_eq!(result.data, expected);
264        Ok(())
265    }
266}