Skip to main content

datafusion_optimizer/
single_distinct_to_groupby.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//! [`SingleDistinctToGroupBy`] replaces `AGG(DISTINCT ..)` with `AGG(..) GROUP BY ..`
6
7use std::sync::Arc;
8
9use crate::optimizer::ApplyOrder;
10use crate::{OptimizerConfig, OptimizerRule};
11
12use datafusion_common::{
13    DFSchema, DataFusionError, HashSet, Result, assert_or_internal_err,
14    tree_node::Transformed,
15};
16use datafusion_expr::builder::project;
17use datafusion_expr::expr::AggregateFunctionParams;
18use datafusion_expr::expr_schema::ExprSchemable;
19use datafusion_expr::{
20    AggregateUDF, Expr, cast, col,
21    expr::AggregateFunction,
22    lit,
23    logical_plan::{Aggregate, LogicalPlan},
24    when,
25};
26
27/// single distinct to group by optimizer rule
28///  ```text
29///    Before:
30///    SELECT a, count(DISTINCT b), sum(c)
31///    FROM t
32///    GROUP BY a
33///
34///    After:
35///    SELECT a, count(alias1), sum(alias2)
36///    FROM (
37///      SELECT a, b as alias1, sum(c) as alias2
38///      FROM t
39///      GROUP BY a, b
40///    )
41///    GROUP BY a
42///  ```
43///
44/// A non-distinct `count` may also appear alongside the distinct aggregate. It
45/// is the one supported function whose outer phase is a different function: the
46/// inner group-by counts rows per `(group, distinct value)` pair, and the outer
47/// phase sums those partial counts.
48///
49///  ```text
50///    Before:
51///    SELECT a, count(*), count(DISTINCT b)
52///    FROM t
53///    GROUP BY a
54///
55///    After:
56///    SELECT a,
57///           CASE WHEN sum(alias2) IS NOT NULL THEN sum(alias2) ELSE 0 END,
58///           count(alias1)
59///    FROM (
60///      SELECT a, b as alias1, count(*) as alias2
61///      FROM t
62///      GROUP BY a, b
63///    )
64///    GROUP BY a
65///  ```
66///
67/// The `CASE` restores the 0 that `count` reports over an empty input, where a
68/// `sum` of no rows is NULL.
69///
70/// See `rewrite_pays_for_count` for when the `count` is allowed.
71#[derive(Default, Debug)]
72pub struct SingleDistinctToGroupBy {}
73
74const SINGLE_DISTINCT_ALIAS: &str = "alias1";
75
76impl SingleDistinctToGroupBy {
77    #[expect(missing_docs)]
78    pub fn new() -> Self {
79        Self {}
80    }
81}
82
83/// The pair of functions used to compute a non-distinct `count` in two phases:
84/// `count` identifies the aggregates that need the treatment, `sum` combines
85/// the partial counts the inner group-by produces.
86///
87/// Both are resolved from the session's function registry, so a plan built
88/// without one keeps the previous behaviour of bailing out on `count`.
89struct CountRollup {
90    count: Arc<AggregateUDF>,
91    sum: Arc<AggregateUDF>,
92}
93
94impl CountRollup {
95    fn try_new(config: &dyn OptimizerConfig) -> Option<Self> {
96        let registry = config.function_registry()?;
97        Some(Self {
98            count: registry.udaf("count").ok()?,
99            sum: registry.udaf("sum").ok()?,
100        })
101    }
102
103    /// Whether `func` is the registry's `count`, and so decomposes into
104    /// `sum` over per-partition counts.
105    fn is_count(&self, func: &AggregateUDF) -> bool {
106        self.count.as_ref() == func
107    }
108}
109
110/// Check whether all aggregate exprs are distinct on a single field.
111fn is_single_distinct_agg(
112    aggr_expr: &[Expr],
113    input_schema: &DFSchema,
114    count_rollup: Option<&CountRollup>,
115) -> Result<bool> {
116    let mut fields_set = HashSet::new();
117    let mut aggregate_count = 0;
118    let mut distinct_aggs = vec![];
119    let mut has_count_rollup = false;
120    for expr in aggr_expr {
121        if let Expr::AggregateFunction(AggregateFunction {
122            func,
123            params:
124                AggregateFunctionParams {
125                    distinct,
126                    args,
127                    filter,
128                    order_by,
129                    null_treatment: _,
130                },
131        }) = expr
132        {
133            if filter.is_some() || !order_by.is_empty() {
134                return Ok(false);
135            }
136            aggregate_count += 1;
137            if *distinct {
138                for e in args {
139                    fields_set.insert(e);
140                }
141                distinct_aggs.push((func, args.as_slice()));
142            } else if count_rollup.is_some_and(|rollup| rollup.is_count(func)) {
143                has_count_rollup = true;
144            } else if func.name() != "sum"
145                && func.name().to_lowercase() != "min"
146                && func.name().to_lowercase() != "max"
147            {
148                return Ok(false);
149            }
150        } else {
151            return Ok(false);
152        }
153    }
154    if aggregate_count != aggr_expr.len() || fields_set.len() != 1 {
155        return Ok(false);
156    }
157    if has_count_rollup && !rewrite_pays_for_count(&distinct_aggs, input_schema)? {
158        return Ok(false);
159    }
160    Ok(true)
161}
162
163/// Whether the rewrite is worth extending to a plan that only qualifies because
164/// of the non-distinct `count`.
165///
166/// The rewrite is not free: every other aggregate moves down to the inner group
167/// by, which has a row per `(group, distinct value)` pair rather than per group,
168/// and keeps its state at that finer grain. What pays for that is taking the
169/// distinct aggregate off `GroupsAccumulatorAdapter` and its one boxed
170/// accumulator per group. An aggregate that already has a specialized
171/// `GroupsAccumulator` never went near the adapter, so there is nothing to buy
172/// and only the inner group by to pay for.
173///
174/// `Some(false)` is therefore the only answer that permits the rewrite. `None`,
175/// the default for almost every function, is not evidence that it pays.
176///
177/// This is a proxy: what actually decides the outcome is the cost per distinct
178/// value on each side, which this rule cannot see. It is deliberately
179/// conservative in the direction that leaves a plan alone. The pre-existing
180/// tolerance of a non-distinct `sum`, `min` or `max` is not gated, since
181/// narrowing it would change plans that have always been rewritten.
182///
183/// Measured in <https://github.com/apache/datafusion/pull/24859>.
184fn rewrite_pays_for_count(
185    distinct_aggs: &[(&Arc<AggregateUDF>, &[Expr])],
186    input_schema: &DFSchema,
187) -> Result<bool> {
188    for (func, args) in distinct_aggs {
189        let arg_types = args
190            .iter()
191            .map(|arg| arg.get_type(input_schema))
192            .collect::<Result<Vec<_>>>()?;
193        if func.groups_accumulator_supported_for_types(&arg_types, true) == Some(false) {
194            return Ok(true);
195        }
196    }
197    Ok(false)
198}
199
200/// Check if the first expr is [Expr::GroupingSet].
201fn contains_grouping_set(expr: &[Expr]) -> bool {
202    matches!(expr.first(), Some(Expr::GroupingSet(_)))
203}
204
205impl OptimizerRule for SingleDistinctToGroupBy {
206    fn name(&self) -> &str {
207        "single_distinct_aggregation_to_group_by"
208    }
209
210    fn apply_order(&self) -> Option<ApplyOrder> {
211        Some(ApplyOrder::TopDown)
212    }
213
214    fn rewrite(
215        &self,
216        plan: LogicalPlan,
217        config: &dyn OptimizerConfig,
218    ) -> Result<Transformed<LogicalPlan>, DataFusionError> {
219        if !matches!(plan, LogicalPlan::Aggregate(_)) {
220            return Ok(Transformed::no(plan));
221        }
222        let count_rollup = CountRollup::try_new(config);
223        match plan {
224            LogicalPlan::Aggregate(Aggregate {
225                input,
226                aggr_expr,
227                schema,
228                group_expr,
229                ..
230            }) if is_single_distinct_agg(
231                &aggr_expr,
232                input.schema(),
233                count_rollup.as_ref(),
234            )? && !contains_grouping_set(&group_expr) =>
235            {
236                let group_size = group_expr.len();
237                // alias all original group_by exprs
238                let (mut inner_group_exprs, out_group_expr_with_alias): (
239                    Vec<Expr>,
240                    Vec<(Expr, _)>,
241                ) = group_expr
242                    .into_iter()
243                    .enumerate()
244                    .map(|(i, group_expr)| {
245                        if let Expr::Column(_) = group_expr {
246                            // For Column expressions we can use existing expression as is.
247                            (group_expr.clone(), (group_expr, None))
248                        } else {
249                            // For complex expression write is as alias, to be able to refer
250                            // if from parent operators successfully.
251                            // Consider plan below.
252                            //
253                            // Aggregate: groupBy=[[group_alias_0]], aggr=[[count(alias1)]] [group_alias_0:Int32, count(alias1):Int64;N]\
254                            // --Aggregate: groupBy=[[test.a + Int32(1) AS group_alias_0, test.c AS alias1]], aggr=[[]] [group_alias_0:Int32, alias1:UInt32]\
255                            // ----TableScan: test [a:UInt32, b:UInt32, c:UInt32]
256                            //
257                            // First aggregate(from bottom) refers to `test.a` column.
258                            // Second aggregate refers to the `group_alias_0` column, Which is a valid field in the first aggregate.
259
260                            // If we were to write plan above as below without alias
261                            //
262                            // Aggregate: groupBy=[[test.a + Int32(1)]], aggr=[[count(alias1)]] [group_alias_0:Int32, count(alias1):Int64;N]\
263                            // --Aggregate: groupBy=[[test.a + Int32(1), test.c AS alias1]], aggr=[[]] [group_alias_0:Int32, alias1:UInt32]\
264                            // ----TableScan: test [a:UInt32, b:UInt32, c:UInt32]
265                            //
266                            // Second aggregate refers to the `test.a + Int32(1)` expression However, its input do not have `test.a` expression in it.
267                            let alias_str = format!("group_alias_{i}");
268                            let (qualifier, field) = schema.qualified_field(i);
269                            (
270                                group_expr.alias(alias_str.clone()),
271                                (col(alias_str), Some((qualifier, field.name()))),
272                            )
273                        }
274                    })
275                    .unzip();
276
277                // replace the distinct arg with alias
278                let mut index = 1;
279                let mut group_fields_set = HashSet::new();
280                let mut inner_aggr_exprs = vec![];
281                // Each aggregate yields the expression the outer `Aggregate`
282                // computes and the expression the projection above it selects.
283                // They differ only for `count`, whose projection restores the
284                // zero that `sum` reports as NULL over an empty input.
285                let (outer_aggr_exprs, outer_proj_exprs): (Vec<Expr>, Vec<Expr>) = aggr_expr
286                    .into_iter()
287                    .map(|aggr_expr| match aggr_expr {
288                        Expr::AggregateFunction(AggregateFunction {
289                            func,
290                            params:
291                                AggregateFunctionParams {
292                                    mut args,
293                                    distinct,
294                                    filter,
295                                    order_by,
296                                    null_treatment,
297                                },
298                        }) => {
299                            if distinct {
300                                // `is_single_distinct_agg` checked that every
301                                // distinct argument in the plan is the same
302                                // expression. A call may still take it more than
303                                // once, as `corr(DISTINCT x, x)` does, and keeps
304                                // its arity here: its distinct argument tuples
305                                // are the distinct values of that expression.
306                                assert_or_internal_err!(
307                                    args.first()
308                                        .is_some_and(|f| args.iter().all(|a| a == f)),
309                                    "DISTINCT aggregate arguments should be the same expression"
310                                );
311                                let arity = args.len();
312                                let arg = args.swap_remove(0);
313
314                                if group_fields_set.insert(arg.schema_name().to_string())
315                                {
316                                    inner_group_exprs
317                                        .push(arg.alias(SINGLE_DISTINCT_ALIAS));
318                                }
319                                let outer =
320                                    Expr::AggregateFunction(AggregateFunction::new_udf(
321                                        func,
322                                        vec![col(SINGLE_DISTINCT_ALIAS); arity],
323                                        false, // intentional to remove distinct here
324                                        filter,
325                                        order_by,
326                                        null_treatment,
327                                    ));
328                                Ok((outer.clone(), outer))
329                                // if the aggregate function is not distinct, we need to rewrite it like two phase aggregation
330                            } else {
331                                index += 1;
332                                let alias_str = format!("alias{index}");
333                                // `count`'s outer phase is `sum`, over the
334                                // partial counts the inner group-by produced.
335                                let rollup = count_rollup
336                                    .as_ref()
337                                    .filter(|rollup| rollup.is_count(&func));
338                                let outer_func = match rollup {
339                                    Some(rollup) => Arc::clone(&rollup.sum),
340                                    None => Arc::clone(&func),
341                                };
342                                inner_aggr_exprs.push(
343                                    Expr::AggregateFunction(AggregateFunction::new_udf(
344                                        Arc::clone(&func),
345                                        args,
346                                        false,
347                                        filter,
348                                        order_by,
349                                        null_treatment,
350                                    ))
351                                    .alias(&alias_str),
352                                );
353                                let outer =
354                                    Expr::AggregateFunction(AggregateFunction::new_udf(
355                                        outer_func,
356                                        vec![col(&alias_str)],
357                                        false,
358                                        None,
359                                        vec![],
360                                        None,
361                                    ));
362                                if rollup.is_none() {
363                                    return Ok((outer.clone(), outer));
364                                }
365                                // `sum` of no rows is NULL where `count` is 0.
366                                // Restoring the 0 also keeps the column
367                                // non-nullable, as `count` had it.
368                                let proj =
369                                    when(outer.clone().is_not_null(), outer.clone())
370                                        .otherwise(lit(0_i64))?;
371                                Ok((outer, proj))
372                            }
373                        }
374                        _ => Ok((aggr_expr.clone(), aggr_expr)),
375                    })
376                    .collect::<Result<Vec<_>>>()?
377                    .into_iter()
378                    .unzip();
379
380                // construct the inner AggrPlan
381                let inner_agg = LogicalPlan::Aggregate(Aggregate::try_new(
382                    input,
383                    inner_group_exprs,
384                    inner_aggr_exprs,
385                )?);
386
387                let outer_group_exprs = out_group_expr_with_alias
388                    .iter()
389                    .map(|(expr, _)| expr.clone())
390                    .collect();
391
392                let outer_aggr = LogicalPlan::Aggregate(Aggregate::try_new(
393                    Arc::new(inner_agg),
394                    outer_group_exprs,
395                    outer_aggr_exprs,
396                )?);
397
398                // so the aggregates are displayed in the same way even after the rewrite
399                // this optimizer has two kinds of alias:
400                // - group_by aggr
401                // - aggr expr
402                let alias_expr: Vec<_> = out_group_expr_with_alias
403                    .into_iter()
404                    .map(|(group_expr, original_name)| match original_name {
405                        Some((qualifier, name)) => {
406                            group_expr.alias_qualified(qualifier.cloned(), name)
407                        }
408                        None => group_expr,
409                    })
410                    .chain(outer_proj_exprs.into_iter().enumerate().map(|(idx, expr)| {
411                        let idx = idx + group_size;
412                        let (qualifier, field) = schema.qualified_field(idx);
413                        let current_type = outer_aggr.schema().field(idx).data_type();
414                        let expr = if current_type != field.data_type() {
415                            cast(expr, field.data_type().clone())
416                        } else {
417                            expr
418                        };
419                        expr.alias_qualified(qualifier.cloned(), field.name())
420                    }))
421                    .collect();
422
423                Ok(Transformed::yes(project(outer_aggr, alias_expr)?))
424            }
425            _ => Ok(Transformed::no(plan)),
426        }
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433    use crate::assert_optimized_plan_eq_display_indent_snapshot;
434    use crate::test::*;
435    use crate::{Optimizer, OptimizerContext};
436    use arrow::datatypes::{DataType, Field, Schema};
437    use chrono::{DateTime, Utc};
438    use datafusion_common::alias::AliasGenerator;
439    use datafusion_common::config::ConfigOptions;
440    use datafusion_expr::ExprFunctionExt;
441    use datafusion_expr::expr::GroupingSet;
442    use datafusion_expr::function::AccumulatorArgs;
443    use datafusion_expr::registry::{FunctionRegistry, MemoryFunctionRegistry};
444    use datafusion_expr::{Accumulator, AggregateUDFImpl, Signature, Volatility};
445    use datafusion_expr::{
446        lit,
447        logical_plan::builder::{LogicalPlanBuilder, table_scan},
448    };
449    use datafusion_functions_aggregate::correlation::corr_udaf;
450    use datafusion_functions_aggregate::count::count_udaf;
451    use datafusion_functions_aggregate::expr_fn::{count, count_distinct, max, min, sum};
452    use datafusion_functions_aggregate::min_max::max_udaf;
453    use datafusion_functions_aggregate::sum::sum_udaf;
454
455    fn max_distinct(expr: Expr) -> Expr {
456        Expr::AggregateFunction(AggregateFunction::new_udf(
457            max_udaf(),
458            vec![expr],
459            true,
460            None,
461            vec![],
462            None,
463        ))
464    }
465
466    fn corr_distinct(y: Expr, x: Expr) -> Expr {
467        Expr::AggregateFunction(AggregateFunction::new_udf(
468            corr_udaf(),
469            vec![y, x],
470            true,
471            None,
472            vec![],
473            None,
474        ))
475    }
476
477    fn sum_distinct(expr: Expr) -> Expr {
478        Expr::AggregateFunction(AggregateFunction::new_udf(
479            sum_udaf(),
480            vec![expr],
481            true,
482            None,
483            vec![],
484            None,
485        ))
486    }
487
488    /// An aggregate that leaves
489    /// [`AggregateUDFImpl::groups_accumulator_supported_for_types`] at its
490    /// default, which is what almost every function in the wild does.
491    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
492    struct SilentUdaf {
493        signature: Signature,
494    }
495
496    impl SilentUdaf {
497        fn new() -> Self {
498            Self {
499                signature: Signature::any(1, Volatility::Immutable),
500            }
501        }
502    }
503
504    impl AggregateUDFImpl for SilentUdaf {
505        fn name(&self) -> &str {
506            "silent"
507        }
508
509        fn signature(&self) -> &Signature {
510            &self.signature
511        }
512
513        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
514            Ok(DataType::UInt32)
515        }
516
517        fn accumulator(
518            &self,
519            _acc_args: AccumulatorArgs,
520        ) -> Result<Box<dyn Accumulator>> {
521            unimplemented!("not needed for this test")
522        }
523    }
524
525    fn silent_distinct(expr: Expr) -> Expr {
526        Expr::AggregateFunction(AggregateFunction::new_udf(
527            Arc::new(AggregateUDF::from(SilentUdaf::new())),
528            vec![expr],
529            true,
530            None,
531            vec![],
532            None,
533        ))
534    }
535
536    fn count_star() -> Expr {
537        Expr::AggregateFunction(AggregateFunction::new_udf(
538            count_udaf(),
539            vec![lit(1_i64)],
540            false,
541            None,
542            vec![],
543            None,
544        ))
545    }
546
547    /// `test` with a `Utf8` `b`, the column the distinct aggregate reads.
548    ///
549    /// `count(DISTINCT b)` over a string has no specialized
550    /// `GroupsAccumulator`, so it is the case a non-distinct `count` may join.
551    /// The `UInt32` `b` of [`test_table_scan`] is the case it may not.
552    fn test_table_scan_utf8_b() -> Result<LogicalPlan> {
553        let schema = Schema::new(vec![
554            Field::new("a", DataType::UInt32, false),
555            Field::new("b", DataType::Utf8, false),
556            Field::new("c", DataType::UInt32, false),
557        ]);
558        table_scan(Some("test"), &schema, None)?.build()
559    }
560
561    /// An [`OptimizerConfig`] that resolves functions the way a session does.
562    /// The rule needs `count` and `sum` from the registry to rewrite a
563    /// non-distinct `count`.
564    #[derive(Debug)]
565    struct RegistryOptimizerContext {
566        inner: OptimizerContext,
567        registry: MemoryFunctionRegistry,
568    }
569
570    impl RegistryOptimizerContext {
571        fn new() -> Self {
572            let mut registry = MemoryFunctionRegistry::new();
573            registry.register_udaf(count_udaf()).unwrap();
574            registry.register_udaf(sum_udaf()).unwrap();
575            Self {
576                inner: OptimizerContext::new(),
577                registry,
578            }
579        }
580    }
581
582    impl OptimizerConfig for RegistryOptimizerContext {
583        fn query_execution_start_time(&self) -> Option<DateTime<Utc>> {
584            self.inner.query_execution_start_time()
585        }
586
587        fn alias_generator(&self) -> &Arc<AliasGenerator> {
588            self.inner.alias_generator()
589        }
590
591        fn options(&self) -> Arc<ConfigOptions> {
592            self.inner.options()
593        }
594
595        fn function_registry(&self) -> Option<&dyn FunctionRegistry> {
596            Some(&self.registry)
597        }
598    }
599
600    macro_rules! assert_optimized_plan_equal {
601        (
602            $plan:expr,
603            @ $expected:literal $(,)?
604        ) => {{
605            let rule: Arc<dyn crate::OptimizerRule + Send + Sync> =
606                Arc::new(SingleDistinctToGroupBy::new());
607            let optimizer = Optimizer::with_rules(vec![rule]);
608            let optimized_plan = optimizer
609                .optimize($plan, &RegistryOptimizerContext::new(), |_, _| {})
610                .expect("failed to optimize plan");
611            insta::assert_snapshot!(optimized_plan.display_indent_schema(), @ $expected);
612
613            Ok::<(), DataFusionError>(())
614        }};
615    }
616
617    #[test]
618    fn not_exist_distinct() -> Result<()> {
619        let table_scan = test_table_scan()?;
620
621        let plan = LogicalPlanBuilder::from(table_scan)
622            .aggregate(Vec::<Expr>::new(), vec![max(col("b"))])?
623            .build()?;
624
625        // Do nothing
626        assert_optimized_plan_equal!(
627            plan,
628            @r"
629        Aggregate: groupBy=[[]], aggr=[[max(test.b)]] [max(test.b):UInt32;N]
630          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
631        "
632        )
633    }
634
635    #[test]
636    fn single_distinct() -> Result<()> {
637        let table_scan = test_table_scan()?;
638
639        let plan = LogicalPlanBuilder::from(table_scan)
640            .aggregate(Vec::<Expr>::new(), vec![count_distinct(col("b"))])?
641            .build()?;
642
643        // Should work
644        assert_optimized_plan_equal!(
645            plan,
646            @r"
647        Projection: count(alias1) AS count(DISTINCT test.b) [count(DISTINCT test.b):Int64]
648          Aggregate: groupBy=[[]], aggr=[[count(alias1)]] [count(alias1):Int64]
649            Aggregate: groupBy=[[test.b AS alias1]], aggr=[[]] [alias1:UInt32]
650              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
651        "
652        )
653    }
654
655    // Currently this optimization is disabled for CUBE/ROLLUP/GROUPING SET
656    #[test]
657    fn single_distinct_and_grouping_set() -> Result<()> {
658        let table_scan = test_table_scan()?;
659
660        let grouping_set = Expr::GroupingSet(GroupingSet::GroupingSets(vec![
661            vec![col("a")],
662            vec![col("b")],
663        ]));
664
665        let plan = LogicalPlanBuilder::from(table_scan)
666            .aggregate(vec![grouping_set], vec![count_distinct(col("c"))])?
667            .build()?;
668
669        // Should not be optimized
670        assert_optimized_plan_equal!(
671            plan,
672            @r"
673        Aggregate: groupBy=[[GROUPING SETS ((test.a), (test.b))]], aggr=[[count(DISTINCT test.c)]] [a:UInt32;N, b:UInt32;N, __grouping_id:UInt8, count(DISTINCT test.c):Int64]
674          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
675        "
676        )
677    }
678
679    // Currently this optimization is disabled for CUBE/ROLLUP/GROUPING SET
680    #[test]
681    fn single_distinct_and_cube() -> Result<()> {
682        let table_scan = test_table_scan()?;
683
684        let grouping_set = Expr::GroupingSet(GroupingSet::Cube(vec![col("a"), col("b")]));
685
686        let plan = LogicalPlanBuilder::from(table_scan)
687            .aggregate(vec![grouping_set], vec![count_distinct(col("c"))])?
688            .build()?;
689
690        // Should not be optimized
691        assert_optimized_plan_equal!(
692            plan,
693            @r"
694        Aggregate: groupBy=[[CUBE (test.a, test.b)]], aggr=[[count(DISTINCT test.c)]] [a:UInt32;N, b:UInt32;N, __grouping_id:UInt8, count(DISTINCT test.c):Int64]
695          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
696        "
697        )
698    }
699
700    // Currently this optimization is disabled for CUBE/ROLLUP/GROUPING SET
701    #[test]
702    fn single_distinct_and_rollup() -> Result<()> {
703        let table_scan = test_table_scan()?;
704
705        let grouping_set =
706            Expr::GroupingSet(GroupingSet::Rollup(vec![col("a"), col("b")]));
707
708        let plan = LogicalPlanBuilder::from(table_scan)
709            .aggregate(vec![grouping_set], vec![count_distinct(col("c"))])?
710            .build()?;
711
712        // Should not be optimized
713        assert_optimized_plan_equal!(
714            plan,
715            @r"
716        Aggregate: groupBy=[[ROLLUP (test.a, test.b)]], aggr=[[count(DISTINCT test.c)]] [a:UInt32;N, b:UInt32;N, __grouping_id:UInt8, count(DISTINCT test.c):Int64]
717          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
718        "
719        )
720    }
721
722    #[test]
723    fn single_distinct_expr() -> Result<()> {
724        let table_scan = test_table_scan()?;
725
726        let plan = LogicalPlanBuilder::from(table_scan)
727            .aggregate(Vec::<Expr>::new(), vec![count_distinct(lit(2) * col("b"))])?
728            .build()?;
729
730        assert_optimized_plan_equal!(
731            plan,
732            @r"
733        Projection: count(alias1) AS count(DISTINCT Int32(2) * test.b) [count(DISTINCT Int32(2) * test.b):Int64]
734          Aggregate: groupBy=[[]], aggr=[[count(alias1)]] [count(alias1):Int64]
735            Aggregate: groupBy=[[Int32(2) * test.b AS alias1]], aggr=[[]] [alias1:Int64]
736              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
737        "
738        )
739    }
740
741    #[test]
742    fn single_distinct_and_groupby() -> Result<()> {
743        let table_scan = test_table_scan()?;
744
745        let plan = LogicalPlanBuilder::from(table_scan)
746            .aggregate(vec![col("a")], vec![count_distinct(col("b"))])?
747            .build()?;
748
749        // Should work
750        assert_optimized_plan_equal!(
751            plan,
752            @r"
753        Projection: test.a, count(alias1) AS count(DISTINCT test.b) [a:UInt32, count(DISTINCT test.b):Int64]
754          Aggregate: groupBy=[[test.a]], aggr=[[count(alias1)]] [a:UInt32, count(alias1):Int64]
755            Aggregate: groupBy=[[test.a, test.b AS alias1]], aggr=[[]] [a:UInt32, alias1:UInt32]
756              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
757        "
758        )
759    }
760
761    #[test]
762    fn two_distinct_and_groupby() -> Result<()> {
763        let table_scan = test_table_scan()?;
764
765        let plan = LogicalPlanBuilder::from(table_scan)
766            .aggregate(
767                vec![col("a")],
768                vec![count_distinct(col("b")), count_distinct(col("c"))],
769            )?
770            .build()?;
771
772        // Do nothing
773        assert_optimized_plan_equal!(
774            plan,
775            @r"
776        Aggregate: groupBy=[[test.a]], aggr=[[count(DISTINCT test.b), count(DISTINCT test.c)]] [a:UInt32, count(DISTINCT test.b):Int64, count(DISTINCT test.c):Int64]
777          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
778        "
779        )
780    }
781
782    #[test]
783    fn single_distinct_repeated_arg_and_groupby() -> Result<()> {
784        let table_scan = test_table_scan()?;
785
786        let plan = LogicalPlanBuilder::from(table_scan)
787            .aggregate(vec![col("a")], vec![corr_distinct(col("b"), col("b"))])?
788            .build()?;
789
790        // Should work: the call takes the distinct argument twice, so it keeps
791        // both arguments after the rewrite.
792        assert_optimized_plan_equal!(
793            plan,
794            @r"
795        Projection: test.a, corr(alias1,alias1) AS corr(DISTINCT test.b,test.b) [a:UInt32, corr(DISTINCT test.b,test.b):Float64;N]
796          Aggregate: groupBy=[[test.a]], aggr=[[corr(alias1, alias1)]] [a:UInt32, corr(alias1,alias1):Float64;N]
797            Aggregate: groupBy=[[test.a, test.b AS alias1]], aggr=[[]] [a:UInt32, alias1:UInt32]
798              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
799        "
800        )
801    }
802
803    #[test]
804    fn single_distinct_two_args_and_groupby() -> Result<()> {
805        let table_scan = test_table_scan()?;
806
807        let plan = LogicalPlanBuilder::from(table_scan)
808            .aggregate(vec![col("a")], vec![corr_distinct(col("b"), col("c"))])?
809            .build()?;
810
811        // Do nothing: the arguments are different expressions, so there is no
812        // single field to group by.
813        assert_optimized_plan_equal!(
814            plan,
815            @r"
816        Aggregate: groupBy=[[test.a]], aggr=[[corr(DISTINCT test.b, test.c)]] [a:UInt32, corr(DISTINCT test.b,test.c):Float64;N]
817          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
818        "
819        )
820    }
821
822    #[test]
823    fn one_field_two_distinct_and_groupby() -> Result<()> {
824        let table_scan = test_table_scan()?;
825
826        let plan = LogicalPlanBuilder::from(table_scan)
827            .aggregate(
828                vec![col("a")],
829                vec![count_distinct(col("b")), max_distinct(col("b"))],
830            )?
831            .build()?;
832
833        // Should work
834        assert_optimized_plan_equal!(
835            plan,
836            @r"
837        Projection: test.a, count(alias1) AS count(DISTINCT test.b), max(alias1) AS max(DISTINCT test.b) [a:UInt32, count(DISTINCT test.b):Int64, max(DISTINCT test.b):UInt32;N]
838          Aggregate: groupBy=[[test.a]], aggr=[[count(alias1), max(alias1)]] [a:UInt32, count(alias1):Int64, max(alias1):UInt32;N]
839            Aggregate: groupBy=[[test.a, test.b AS alias1]], aggr=[[]] [a:UInt32, alias1:UInt32]
840              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
841        "
842        )
843    }
844
845    #[test]
846    fn distinct_and_common() -> Result<()> {
847        let table_scan = test_table_scan_utf8_b()?;
848
849        let plan = LogicalPlanBuilder::from(table_scan)
850            .aggregate(
851                vec![col("a")],
852                vec![count_distinct(col("b")), count(col("c"))],
853            )?
854            .build()?;
855
856        // Should work: the non-distinct count becomes a sum of the counts the
857        // inner group-by produces per (test.a, test.b) pair
858        assert_optimized_plan_equal!(
859            plan,
860            @r"
861        Projection: test.a, count(alias1) AS count(DISTINCT test.b), CASE WHEN sum(alias2) IS NOT NULL THEN sum(alias2) ELSE Int64(0) END AS count(test.c) [a:UInt32, count(DISTINCT test.b):Int64, count(test.c):Int64]
862          Aggregate: groupBy=[[test.a]], aggr=[[count(alias1), sum(alias2)]] [a:UInt32, count(alias1):Int64, sum(alias2):Int64;N]
863            Aggregate: groupBy=[[test.a, test.b AS alias1]], aggr=[[count(test.c) AS alias2]] [a:UInt32, alias1:Utf8, alias2:Int64]
864              TableScan: test [a:UInt32, b:Utf8, c:UInt32]
865        "
866        )
867    }
868
869    #[test]
870    fn distinct_and_common_over_a_natively_supported_type() -> Result<()> {
871        let table_scan = test_table_scan()?;
872
873        let plan = LogicalPlanBuilder::from(table_scan)
874            .aggregate(
875                vec![col("a")],
876                vec![count_distinct(col("b")), count(col("c"))],
877            )?
878            .build()?;
879
880        // Should not work: `count(DISTINCT b)` over a `UInt32` has its own
881        // `GroupsAccumulator`, so the rewrite would add an inner group-by
882        // without taking anything off `GroupsAccumulatorAdapter`
883        assert_optimized_plan_equal!(
884            plan,
885            @r"
886        Aggregate: groupBy=[[test.a]], aggr=[[count(DISTINCT test.b), count(test.c)]] [a:UInt32, count(DISTINCT test.b):Int64, count(test.c):Int64]
887          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
888        "
889        )
890    }
891
892    #[test]
893    fn distinct_over_a_natively_supported_type_without_a_count() -> Result<()> {
894        let table_scan = test_table_scan()?;
895
896        let plan = LogicalPlanBuilder::from(table_scan)
897            .aggregate(
898                vec![col("a")],
899                vec![count_distinct(col("b")), sum(col("c"))],
900            )?
901            .build()?;
902
903        // Should work: the gate covers only the `count` this change added, so a
904        // plan that already qualified through `sum`, `min` or `max` is rewritten
905        // exactly as before
906        assert_optimized_plan_equal!(
907            plan,
908            @r"
909        Projection: test.a, count(alias1) AS count(DISTINCT test.b), sum(alias2) AS sum(test.c) [a:UInt32, count(DISTINCT test.b):Int64, sum(test.c):UInt64;N]
910          Aggregate: groupBy=[[test.a]], aggr=[[count(alias1), sum(alias2)]] [a:UInt32, count(alias1):Int64, sum(alias2):UInt64;N]
911            Aggregate: groupBy=[[test.a, test.b AS alias1]], aggr=[[sum(test.c) AS alias2]] [a:UInt32, alias1:UInt32, alias2:UInt64;N]
912              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
913        "
914        )
915    }
916
917    #[test]
918    fn distinct_over_a_function_with_no_opinion_is_not_rewritten() -> Result<()> {
919        let table_scan = test_table_scan()?;
920
921        let plan = LogicalPlanBuilder::from(table_scan)
922            .aggregate(
923                vec![col("a")],
924                vec![silent_distinct(col("b")), count(col("c"))],
925            )?
926            .build()?;
927
928        // Should not work: `silent` leaves
929        // `groups_accumulator_supported_for_types` at its default, so it
930        // reports nothing about `GroupsAccumulatorAdapter`. Silence is not
931        // evidence that the rewrite pays, and the rule must not read it as
932        // permission
933        assert_optimized_plan_equal!(
934            plan,
935            @r"
936        Aggregate: groupBy=[[test.a]], aggr=[[silent(DISTINCT test.b), count(test.c)]] [a:UInt32, silent(DISTINCT test.b):UInt32;N, count(test.c):Int64]
937          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
938        "
939        )
940    }
941
942    #[test]
943    fn distinct_sum_and_count_is_not_rewritten() -> Result<()> {
944        let table_scan = test_table_scan()?;
945
946        let plan = LogicalPlanBuilder::from(table_scan)
947            .aggregate(
948                vec![col("a")],
949                vec![sum_distinct(col("b")), count(col("c"))],
950            )?
951            .build()?;
952
953        // Should not work: `sum` reports nothing about
954        // `GroupsAccumulatorAdapter` either, so the rewrite is not known to pay
955        assert_optimized_plan_equal!(
956            plan,
957            @r"
958        Aggregate: groupBy=[[test.a]], aggr=[[sum(DISTINCT test.b), count(test.c)]] [a:UInt32, sum(DISTINCT test.b):UInt64;N, count(test.c):Int64]
959          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
960        "
961        )
962    }
963
964    #[test]
965    fn group_by_with_expr() -> Result<()> {
966        let table_scan = test_table_scan().unwrap();
967
968        let plan = LogicalPlanBuilder::from(table_scan)
969            .aggregate(vec![col("a") + lit(1)], vec![count_distinct(col("c"))])?
970            .build()?;
971
972        // Should work
973        assert_optimized_plan_equal!(
974            plan,
975            @r"
976        Projection: group_alias_0 AS test.a + Int32(1), count(alias1) AS count(DISTINCT test.c) [test.a + Int32(1):Int64, count(DISTINCT test.c):Int64]
977          Aggregate: groupBy=[[group_alias_0]], aggr=[[count(alias1)]] [group_alias_0:Int64, count(alias1):Int64]
978            Aggregate: groupBy=[[test.a + Int32(1) AS group_alias_0, test.c AS alias1]], aggr=[[]] [group_alias_0:Int64, alias1:UInt32]
979              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
980        "
981        )
982    }
983
984    #[test]
985    fn two_distinct_and_one_common() -> Result<()> {
986        let table_scan = test_table_scan()?;
987
988        let plan = LogicalPlanBuilder::from(table_scan)
989            .aggregate(
990                vec![col("a")],
991                vec![
992                    sum(col("c")),
993                    count_distinct(col("b")),
994                    max_distinct(col("b")),
995                ],
996            )?
997            .build()?;
998
999        // Should work
1000        assert_optimized_plan_equal!(
1001            plan,
1002            @r"
1003        Projection: test.a, sum(alias2) AS sum(test.c), count(alias1) AS count(DISTINCT test.b), max(alias1) AS max(DISTINCT test.b) [a:UInt32, sum(test.c):UInt64;N, count(DISTINCT test.b):Int64, max(DISTINCT test.b):UInt32;N]
1004          Aggregate: groupBy=[[test.a]], aggr=[[sum(alias2), count(alias1), max(alias1)]] [a:UInt32, sum(alias2):UInt64;N, count(alias1):Int64, max(alias1):UInt32;N]
1005            Aggregate: groupBy=[[test.a, test.b AS alias1]], aggr=[[sum(test.c) AS alias2]] [a:UInt32, alias1:UInt32, alias2:UInt64;N]
1006              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1007        "
1008        )
1009    }
1010
1011    #[test]
1012    fn one_distinct_and_two_common() -> Result<()> {
1013        let table_scan = test_table_scan()?;
1014
1015        let plan = LogicalPlanBuilder::from(table_scan)
1016            .aggregate(
1017                vec![col("a")],
1018                vec![sum(col("c")), max(col("c")), count_distinct(col("b"))],
1019            )?
1020            .build()?;
1021
1022        // Should work
1023        assert_optimized_plan_equal!(
1024            plan,
1025            @r"
1026        Projection: test.a, sum(alias2) AS sum(test.c), max(alias3) AS max(test.c), count(alias1) AS count(DISTINCT test.b) [a:UInt32, sum(test.c):UInt64;N, max(test.c):UInt32;N, count(DISTINCT test.b):Int64]
1027          Aggregate: groupBy=[[test.a]], aggr=[[sum(alias2), max(alias3), count(alias1)]] [a:UInt32, sum(alias2):UInt64;N, max(alias3):UInt32;N, count(alias1):Int64]
1028            Aggregate: groupBy=[[test.a, test.b AS alias1]], aggr=[[sum(test.c) AS alias2, max(test.c) AS alias3]] [a:UInt32, alias1:UInt32, alias2:UInt64;N, alias3:UInt32;N]
1029              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1030        "
1031        )
1032    }
1033
1034    #[test]
1035    fn one_distinct_and_one_common() -> Result<()> {
1036        let table_scan = test_table_scan()?;
1037
1038        let plan = LogicalPlanBuilder::from(table_scan)
1039            .aggregate(
1040                vec![col("c")],
1041                vec![min(col("a")), count_distinct(col("b"))],
1042            )?
1043            .build()?;
1044
1045        // Should work
1046        assert_optimized_plan_equal!(
1047            plan,
1048            @r"
1049        Projection: test.c, min(alias2) AS min(test.a), count(alias1) AS count(DISTINCT test.b) [c:UInt32, min(test.a):UInt32;N, count(DISTINCT test.b):Int64]
1050          Aggregate: groupBy=[[test.c]], aggr=[[min(alias2), count(alias1)]] [c:UInt32, min(alias2):UInt32;N, count(alias1):Int64]
1051            Aggregate: groupBy=[[test.c, test.b AS alias1]], aggr=[[min(test.a) AS alias2]] [c:UInt32, alias1:UInt32, alias2:UInt32;N]
1052              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1053        "
1054        )
1055    }
1056
1057    #[test]
1058    fn common_with_filter() -> Result<()> {
1059        let table_scan = test_table_scan()?;
1060
1061        // sum(a) FILTER (WHERE a > 5)
1062        let expr = Expr::AggregateFunction(AggregateFunction::new_udf(
1063            sum_udaf(),
1064            vec![col("a")],
1065            false,
1066            Some(Box::new(col("a").gt(lit(5)))),
1067            vec![],
1068            None,
1069        ));
1070        let plan = LogicalPlanBuilder::from(table_scan)
1071            .aggregate(vec![col("c")], vec![expr, count_distinct(col("b"))])?
1072            .build()?;
1073
1074        // Do nothing
1075        assert_optimized_plan_equal!(
1076            plan,
1077            @r"
1078        Aggregate: groupBy=[[test.c]], aggr=[[sum(test.a) FILTER (WHERE test.a > Int32(5)), count(DISTINCT test.b)]] [c:UInt32, sum(test.a) FILTER (WHERE test.a > Int32(5)):UInt64;N, count(DISTINCT test.b):Int64]
1079          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1080        "
1081        )
1082    }
1083
1084    #[test]
1085    fn distinct_with_filter() -> Result<()> {
1086        let table_scan = test_table_scan()?;
1087
1088        // count(DISTINCT a) FILTER (WHERE a > 5)
1089        let expr = count_udaf()
1090            .call(vec![col("a")])
1091            .distinct()
1092            .filter(col("a").gt(lit(5)))
1093            .build()?;
1094        let plan = LogicalPlanBuilder::from(table_scan)
1095            .aggregate(vec![col("c")], vec![sum(col("a")), expr])?
1096            .build()?;
1097
1098        // Do nothing
1099        assert_optimized_plan_equal!(
1100            plan,
1101            @r"
1102        Aggregate: groupBy=[[test.c]], aggr=[[sum(test.a), count(DISTINCT test.a) FILTER (WHERE test.a > Int32(5))]] [c:UInt32, sum(test.a):UInt64;N, count(DISTINCT test.a) FILTER (WHERE test.a > Int32(5)):Int64]
1103          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1104        "
1105        )
1106    }
1107
1108    #[test]
1109    fn common_with_order_by() -> Result<()> {
1110        let table_scan = test_table_scan()?;
1111
1112        // SUM(a ORDER BY a)
1113        let expr = Expr::AggregateFunction(AggregateFunction::new_udf(
1114            sum_udaf(),
1115            vec![col("a")],
1116            false,
1117            None,
1118            vec![col("a").sort(true, false)],
1119            None,
1120        ));
1121        let plan = LogicalPlanBuilder::from(table_scan)
1122            .aggregate(vec![col("c")], vec![expr, count_distinct(col("b"))])?
1123            .build()?;
1124
1125        // Do nothing
1126        assert_optimized_plan_equal!(
1127            plan,
1128            @r"
1129        Aggregate: groupBy=[[test.c]], aggr=[[sum(test.a) ORDER BY [test.a ASC NULLS LAST], count(DISTINCT test.b)]] [c:UInt32, sum(test.a) ORDER BY [test.a ASC NULLS LAST]:UInt64;N, count(DISTINCT test.b):Int64]
1130          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1131        "
1132        )
1133    }
1134
1135    #[test]
1136    fn distinct_with_order_by() -> Result<()> {
1137        let table_scan = test_table_scan()?;
1138
1139        // count(DISTINCT a ORDER BY a)
1140        let expr = count_udaf()
1141            .call(vec![col("a")])
1142            .distinct()
1143            .order_by(vec![col("a").sort(true, false)])
1144            .build()?;
1145        let plan = LogicalPlanBuilder::from(table_scan)
1146            .aggregate(vec![col("c")], vec![sum(col("a")), expr])?
1147            .build()?;
1148
1149        // Do nothing
1150        assert_optimized_plan_equal!(
1151            plan,
1152            @r"
1153        Aggregate: groupBy=[[test.c]], aggr=[[sum(test.a), count(DISTINCT test.a) ORDER BY [test.a ASC NULLS LAST]]] [c:UInt32, sum(test.a):UInt64;N, count(DISTINCT test.a) ORDER BY [test.a ASC NULLS LAST]:Int64]
1154          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1155        "
1156        )
1157    }
1158
1159    #[test]
1160    fn aggregate_with_filter_and_order_by() -> Result<()> {
1161        let table_scan = test_table_scan()?;
1162
1163        // count(DISTINCT a ORDER BY a) FILTER (WHERE a > 5)
1164        let expr = count_udaf()
1165            .call(vec![col("a")])
1166            .distinct()
1167            .filter(col("a").gt(lit(5)))
1168            .order_by(vec![col("a").sort(true, false)])
1169            .build()?;
1170        let plan = LogicalPlanBuilder::from(table_scan)
1171            .aggregate(vec![col("c")], vec![sum(col("a")), expr])?
1172            .build()?;
1173
1174        // Do nothing
1175        assert_optimized_plan_equal!(
1176            plan,
1177            @r"
1178        Aggregate: groupBy=[[test.c]], aggr=[[sum(test.a), count(DISTINCT test.a) FILTER (WHERE test.a > Int32(5)) ORDER BY [test.a ASC NULLS LAST]]] [c:UInt32, sum(test.a):UInt64;N, count(DISTINCT test.a) FILTER (WHERE test.a > Int32(5)) ORDER BY [test.a ASC NULLS LAST]:Int64]
1179          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1180        "
1181        )
1182    }
1183
1184    #[test]
1185    fn count_star_and_distinct_without_groupby() -> Result<()> {
1186        let table_scan = test_table_scan_utf8_b()?;
1187
1188        let plan = LogicalPlanBuilder::from(table_scan)
1189            .aggregate(
1190                Vec::<Expr>::new(),
1191                vec![count_star(), count_distinct(col("b"))],
1192            )?
1193            .build()?;
1194
1195        // Should work. Without a group by the outer aggregate sees no rows at
1196        // all for an empty input, so the projection has to turn the NULL that
1197        // `sum` reports there back into the 0 `count` reports.
1198        assert_optimized_plan_equal!(
1199            plan,
1200            @r"
1201        Projection: CASE WHEN sum(alias2) IS NOT NULL THEN sum(alias2) ELSE Int64(0) END AS count(Int64(1)), count(alias1) AS count(DISTINCT test.b) [count(Int64(1)):Int64, count(DISTINCT test.b):Int64]
1202          Aggregate: groupBy=[[]], aggr=[[sum(alias2), count(alias1)]] [sum(alias2):Int64;N, count(alias1):Int64]
1203            Aggregate: groupBy=[[test.b AS alias1]], aggr=[[count(Int64(1)) AS alias2]] [alias1:Utf8, alias2:Int64]
1204              TableScan: test [a:UInt32, b:Utf8, c:UInt32]
1205        "
1206        )
1207    }
1208
1209    #[test]
1210    fn count_star_min_max_sum_and_distinct_with_groupby() -> Result<()> {
1211        let table_scan = test_table_scan_utf8_b()?;
1212
1213        let plan = LogicalPlanBuilder::from(table_scan)
1214            .aggregate(
1215                vec![col("a")],
1216                vec![
1217                    count_star(),
1218                    count_distinct(col("b")),
1219                    min(col("c")),
1220                    max(col("c")),
1221                    sum(col("c")),
1222                ],
1223            )?
1224            .build()?;
1225
1226        // Should work: this is the shape a `count(*)` alongside a
1227        // `count(DISTINCT ..)`, a min, a max and a sum produces
1228        assert_optimized_plan_equal!(
1229            plan,
1230            @r"
1231        Projection: test.a, CASE WHEN sum(alias2) IS NOT NULL THEN sum(alias2) ELSE Int64(0) END AS count(Int64(1)), count(alias1) AS count(DISTINCT test.b), min(alias3) AS min(test.c), max(alias4) AS max(test.c), sum(alias5) AS sum(test.c) [a:UInt32, count(Int64(1)):Int64, count(DISTINCT test.b):Int64, min(test.c):UInt32;N, max(test.c):UInt32;N, sum(test.c):UInt64;N]
1232          Aggregate: groupBy=[[test.a]], aggr=[[sum(alias2), count(alias1), min(alias3), max(alias4), sum(alias5)]] [a:UInt32, sum(alias2):Int64;N, count(alias1):Int64, min(alias3):UInt32;N, max(alias4):UInt32;N, sum(alias5):UInt64;N]
1233            Aggregate: groupBy=[[test.a, test.b AS alias1]], aggr=[[count(Int64(1)) AS alias2, min(test.c) AS alias3, max(test.c) AS alias4, sum(test.c) AS alias5]] [a:UInt32, alias1:Utf8, alias2:Int64, alias3:UInt32;N, alias4:UInt32;N, alias5:UInt64;N]
1234              TableScan: test [a:UInt32, b:Utf8, c:UInt32]
1235        "
1236        )
1237    }
1238
1239    #[test]
1240    fn count_with_filter_is_not_rewritten() -> Result<()> {
1241        let table_scan = test_table_scan()?;
1242
1243        // count(a) FILTER (WHERE a > 5)
1244        let expr = count_udaf()
1245            .call(vec![col("a")])
1246            .filter(col("a").gt(lit(5)))
1247            .build()?;
1248        let plan = LogicalPlanBuilder::from(table_scan)
1249            .aggregate(vec![col("c")], vec![expr, count_distinct(col("b"))])?
1250            .build()?;
1251
1252        // Do nothing: the filter would have to be applied per input row, but
1253        // the inner aggregate has already collapsed them
1254        assert_optimized_plan_equal!(
1255            plan,
1256            @r"
1257        Aggregate: groupBy=[[test.c]], aggr=[[count(test.a) FILTER (WHERE test.a > Int32(5)), count(DISTINCT test.b)]] [c:UInt32, count(test.a) FILTER (WHERE test.a > Int32(5)):Int64, count(DISTINCT test.b):Int64]
1258          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1259        "
1260        )
1261    }
1262
1263    #[test]
1264    fn count_with_order_by_is_not_rewritten() -> Result<()> {
1265        let table_scan = test_table_scan()?;
1266
1267        // count(a ORDER BY a)
1268        let expr = count_udaf()
1269            .call(vec![col("a")])
1270            .order_by(vec![col("a").sort(true, false)])
1271            .build()?;
1272        let plan = LogicalPlanBuilder::from(table_scan)
1273            .aggregate(vec![col("c")], vec![expr, count_distinct(col("b"))])?
1274            .build()?;
1275
1276        // Do nothing
1277        assert_optimized_plan_equal!(
1278            plan,
1279            @r"
1280        Aggregate: groupBy=[[test.c]], aggr=[[count(test.a) ORDER BY [test.a ASC NULLS LAST], count(DISTINCT test.b)]] [c:UInt32, count(test.a) ORDER BY [test.a ASC NULLS LAST]:Int64, count(DISTINCT test.b):Int64]
1281          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1282        "
1283        )
1284    }
1285
1286    #[test]
1287    fn count_without_function_registry_is_not_rewritten() -> Result<()> {
1288        let table_scan = test_table_scan()?;
1289
1290        let plan = LogicalPlanBuilder::from(table_scan)
1291            .aggregate(vec![col("a")], vec![count_star(), count_distinct(col("b"))])?
1292            .build()?;
1293
1294        // Do nothing: without a registry the rule cannot resolve the `sum` the
1295        // outer phase needs
1296        let rule: Arc<dyn OptimizerRule + Send + Sync> =
1297            Arc::new(SingleDistinctToGroupBy::new());
1298        assert_optimized_plan_eq_display_indent_snapshot!(
1299            rule,
1300            plan,
1301            @r"
1302        Aggregate: groupBy=[[test.a]], aggr=[[count(Int64(1)), count(DISTINCT test.b)]] [a:UInt32, count(Int64(1)):Int64, count(DISTINCT test.b):Int64]
1303          TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1304        ",
1305        )
1306    }
1307
1308    #[test]
1309    fn sum_decimal_with_distinct_preserves_declared_type() -> Result<()> {
1310        let schema = Schema::new(vec![
1311            Field::new("d", DataType::Decimal128(5, 2), false),
1312            Field::new("x", DataType::Int32, false),
1313        ]);
1314        let table_scan = table_scan(Some("test"), &schema, None)?.build()?;
1315
1316        let plan = LogicalPlanBuilder::from(table_scan)
1317            .aggregate(
1318                Vec::<Expr>::new(),
1319                vec![sum(col("d")), count_distinct(col("x"))],
1320            )?
1321            .build()?;
1322
1323        let rule: Arc<dyn OptimizerRule + Send + Sync> =
1324            Arc::new(SingleDistinctToGroupBy::new());
1325        let optimizer = Optimizer::with_rules(vec![rule]);
1326        let optimized_plan = optimizer
1327            .optimize(plan.clone(), &RegistryOptimizerContext::new(), |_, _| {})
1328            .expect("failed to optimize plan");
1329
1330        assert_eq!(plan.schema().as_ref(), optimized_plan.schema().as_ref());
1331        Ok(())
1332    }
1333}