1use 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#[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
83struct 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 fn is_count(&self, func: &AggregateUDF) -> bool {
106 self.count.as_ref() == func
107 }
108}
109
110fn 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
163fn 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
200fn 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 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 (group_expr.clone(), (group_expr, None))
248 } else {
249 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 let mut index = 1;
279 let mut group_fields_set = HashSet::new();
280 let mut inner_aggr_exprs = vec![];
281 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 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, filter,
325 order_by,
326 null_treatment,
327 ));
328 Ok((outer.clone(), outer))
329 } else {
331 index += 1;
332 let alias_str = format!("alias{index}");
333 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 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 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 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 #[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 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 #[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 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 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 #[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 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 #[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 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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}