Skip to main content

datafusion_optimizer/
replace_distinct_aggregate.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//! [`ReplaceDistinctWithAggregate`] replaces `DISTINCT ...` with `GROUP BY ...`
6
7use crate::optimizer::{ApplyOrder, ApplyOrder::BottomUp};
8use crate::{OptimizerConfig, OptimizerRule};
9use std::sync::Arc;
10
11use datafusion_common::tree_node::Transformed;
12use datafusion_common::{Column, Dependency, Result};
13use datafusion_expr::expr_rewriter::normalize_cols;
14use datafusion_expr::utils::expand_wildcard;
15use datafusion_expr::{Aggregate, Distinct, DistinctOn, Expr, LogicalPlan};
16use datafusion_expr::{ExprFunctionExt, Limit, LogicalPlanBuilder, col, lit};
17
18/// Optimizer that replaces logical [[Distinct]] with a logical [[Aggregate]]
19///
20/// ```text
21/// SELECT DISTINCT a, b FROM tab
22/// ```
23///
24/// Into
25/// ```text
26/// SELECT a, b FROM tab GROUP BY a, b
27/// ```
28///
29/// On the other hand, for a `DISTINCT ON` query the replacement is
30/// a bit more involved and effectively converts
31/// ```text
32/// SELECT DISTINCT ON (a) b FROM tab ORDER BY a DESC, c
33/// ```
34///
35/// into
36/// ```text
37/// SELECT b FROM (
38///     SELECT a, FIRST_VALUE(b ORDER BY a DESC, c) AS b
39///     FROM tab
40///     GROUP BY a
41/// )
42/// ORDER BY a DESC
43/// ```
44///
45/// In case there are no columns, the [[Distinct]] is replaced by a [[Limit]]
46///
47/// ```text
48/// SELECT DISTINCT * FROM empty_table
49/// ```
50///
51/// Into
52/// ```text
53/// SELECT * FROM empty_table LIMIT 1
54/// ```
55#[derive(Default, Debug)]
56pub struct ReplaceDistinctWithAggregate {}
57
58impl ReplaceDistinctWithAggregate {
59    #[expect(missing_docs)]
60    pub fn new() -> Self {
61        Self {}
62    }
63}
64
65impl OptimizerRule for ReplaceDistinctWithAggregate {
66    fn rewrite(
67        &self,
68        plan: LogicalPlan,
69        config: &dyn OptimizerConfig,
70    ) -> Result<Transformed<LogicalPlan>> {
71        match plan {
72            LogicalPlan::Distinct(Distinct::All(input)) => {
73                let group_expr = expand_wildcard(input.schema(), &input, None)?;
74
75                if group_expr.is_empty() {
76                    // Special case: there are no columns to group by, so we can't replace it by a group by
77                    // however, we can replace it by LIMIT 1 because there is either no output or a single empty row
78                    return Ok(Transformed::yes(LogicalPlan::Limit(Limit {
79                        skip: None,
80                        fetch: Some(Box::new(lit(1i64))),
81                        input,
82                    })));
83                }
84
85                let field_count = input.schema().fields().len();
86                for dep in input.schema().functional_dependencies().iter() {
87                    // If the input is already unique on all of its columns (e.g.
88                    // it is a GROUP BY over exactly these columns), the DISTINCT
89                    // is a no-op and we can simply remove it. The dependency mode
90                    // must be `Single`: a `Multi` dependence (e.g. a former key
91                    // downgraded by a join) means equal rows may occur multiple
92                    // times, so the DISTINCT still has work to do. Uniqueness
93                    // must also hold across NULLs: a nullable UNIQUE key can
94                    // contain multiple NULL rows that DISTINCT must collapse.
95                    if dep.mode == Dependency::Single
96                        && dep.is_valid_across_nulls(input.schema())
97                        && dep.source_indices.len() >= field_count
98                        && dep.source_indices[..field_count]
99                            .iter()
100                            .enumerate()
101                            .all(|(idx, f_idx)| idx == *f_idx)
102                    {
103                        return Ok(Transformed::yes(Arc::unwrap_or_clone(input)));
104                    }
105                }
106
107                // Replace with aggregation:
108                let aggr_plan = LogicalPlan::Aggregate(Aggregate::try_new(
109                    input,
110                    group_expr,
111                    vec![],
112                )?);
113                Ok(Transformed::yes(aggr_plan))
114            }
115            LogicalPlan::Distinct(Distinct::On(DistinctOn {
116                select_expr,
117                on_expr,
118                sort_expr,
119                input,
120                schema,
121            })) => {
122                let expr_cnt = on_expr.len();
123
124                // Construct the aggregation expression to be used to fetch the selected expressions.
125                let first_value_udaf: Arc<datafusion_expr::AggregateUDF> =
126                    config.function_registry().unwrap().udaf("first_value")?;
127                let aggr_expr = select_expr.into_iter().map(|e| {
128                    if let Some(order_by) = &sort_expr {
129                        first_value_udaf
130                            .call(vec![e])
131                            .order_by(order_by.clone())
132                            .build()
133                            // guaranteed to be `Expr::AggregateFunction`
134                            .unwrap()
135                    } else {
136                        first_value_udaf.call(vec![e])
137                    }
138                });
139
140                let aggr_expr = normalize_cols(aggr_expr, input.as_ref())?;
141                let group_expr = normalize_cols(on_expr, input.as_ref())?;
142
143                // Build the aggregation plan
144                let plan = LogicalPlan::Aggregate(Aggregate::try_new(
145                    input, group_expr, aggr_expr,
146                )?);
147                // TODO use LogicalPlanBuilder directly rather than recreating the Aggregate
148                // when https://github.com/apache/datafusion/issues/10485 is available
149                let lpb = LogicalPlanBuilder::from(plan);
150
151                let plan = if let Some(mut sort_expr) = sort_expr {
152                    // While sort expressions were used in the `FIRST_VALUE` aggregation itself above,
153                    // this on it's own isn't enough to guarantee the proper output order of the grouping
154                    // (`ON`) expression, so we need to sort those as well.
155
156                    // truncate the sort_expr to the length of on_expr
157                    sort_expr.truncate(expr_cnt);
158
159                    lpb.sort(sort_expr)?.build()?
160                } else {
161                    lpb.build()?
162                };
163
164                // Whereas the aggregation plan by default outputs both the grouping and the aggregation
165                // expressions, for `DISTINCT ON` we only need to emit the original selection expressions.
166
167                let project_exprs = plan
168                    .schema()
169                    .iter()
170                    .skip(expr_cnt)
171                    .zip(schema.iter())
172                    .map(|((new_qualifier, new_field), (old_qualifier, old_field))| {
173                        col(Column::from((new_qualifier, new_field)))
174                            .alias_qualified(old_qualifier.cloned(), old_field.name())
175                    })
176                    .collect::<Vec<Expr>>();
177
178                let plan = LogicalPlanBuilder::from(plan)
179                    .project(project_exprs)?
180                    .build()?;
181
182                Ok(Transformed::yes(plan))
183            }
184            _ => Ok(Transformed::no(plan)),
185        }
186    }
187
188    fn name(&self) -> &str {
189        "replace_distinct_aggregate"
190    }
191
192    fn apply_order(&self) -> Option<ApplyOrder> {
193        Some(BottomUp)
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use crate::assert_optimized_plan_eq_snapshot;
200    use crate::replace_distinct_aggregate::ReplaceDistinctWithAggregate;
201    use crate::test::*;
202    use arrow::datatypes::{Fields, Schema};
203    use std::sync::Arc;
204
205    use crate::OptimizerContext;
206    use datafusion_common::Result;
207    use datafusion_expr::{
208        Expr, col, logical_plan::builder::LogicalPlanBuilder, table_scan,
209    };
210    use datafusion_functions_aggregate::sum::sum;
211
212    macro_rules! assert_optimized_plan_equal {
213        (
214            $plan:expr,
215            @ $expected:literal $(,)?
216        ) => {{
217            let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
218            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(ReplaceDistinctWithAggregate::new())];
219            assert_optimized_plan_eq_snapshot!(
220                optimizer_ctx,
221                rules,
222                $plan,
223                @ $expected,
224            )
225        }};
226    }
227
228    #[test]
229    fn eliminate_redundant_distinct_simple() -> Result<()> {
230        let table_scan = test_table_scan().unwrap();
231        let plan = LogicalPlanBuilder::from(table_scan)
232            .aggregate(vec![col("c")], Vec::<Expr>::new())?
233            .project(vec![col("c")])?
234            .distinct()?
235            .build()?;
236
237        assert_optimized_plan_equal!(plan, @r"
238        Projection: test.c
239          Aggregate: groupBy=[[test.c]], aggr=[[]]
240            TableScan: test
241        ")
242    }
243
244    #[test]
245    fn eliminate_redundant_distinct_pair() -> Result<()> {
246        let table_scan = test_table_scan().unwrap();
247        let plan = LogicalPlanBuilder::from(table_scan)
248            .aggregate(vec![col("a"), col("b")], Vec::<Expr>::new())?
249            .project(vec![col("a"), col("b")])?
250            .distinct()?
251            .build()?;
252
253        assert_optimized_plan_equal!(plan, @r"
254        Projection: test.a, test.b
255          Aggregate: groupBy=[[test.a, test.b]], aggr=[[]]
256            TableScan: test
257        ")
258    }
259
260    #[test]
261    fn do_not_eliminate_distinct() -> Result<()> {
262        let table_scan = test_table_scan().unwrap();
263        let plan = LogicalPlanBuilder::from(table_scan)
264            .project(vec![col("a"), col("b")])?
265            .distinct()?
266            .build()?;
267
268        assert_optimized_plan_equal!(plan, @r"
269        Aggregate: groupBy=[[test.a, test.b]], aggr=[[]]
270          Projection: test.a, test.b
271            TableScan: test
272        ")
273    }
274
275    #[test]
276    fn do_not_eliminate_distinct_with_aggr() -> Result<()> {
277        let table_scan = test_table_scan().unwrap();
278        let plan = LogicalPlanBuilder::from(table_scan)
279            .aggregate(vec![col("a"), col("b"), col("c")], vec![sum(col("c"))])?
280            .project(vec![col("a"), col("b")])?
281            .distinct()?
282            .build()?;
283
284        assert_optimized_plan_equal!(plan, @r"
285        Aggregate: groupBy=[[test.a, test.b]], aggr=[[]]
286          Projection: test.a, test.b
287            Aggregate: groupBy=[[test.a, test.b, test.c]], aggr=[[sum(test.c)]]
288              TableScan: test
289        ")
290    }
291
292    #[test]
293    fn use_limit_1_when_no_columns() -> Result<()> {
294        let plan = table_scan(Some("test"), &Schema::new(Fields::empty()), None)?
295            .distinct()?
296            .build()?;
297
298        assert_optimized_plan_equal!(plan, @r"
299        Limit: skip=0, fetch=1
300          TableScan: test
301        ")
302    }
303}