1use crate::optimizer::ApplyOrder;
9use crate::{OptimizerConfig, OptimizerRule};
10
11use datafusion_common::Result;
12use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
13use datafusion_expr::expr::AggregateFunction;
14use datafusion_expr::expr_rewriter::NamePreserver;
15use datafusion_expr::{DistinctHandling, Expr, LogicalPlan};
16
17#[derive(Default, Debug)]
41pub struct EliminateAggregateDistinct {}
42
43impl EliminateAggregateDistinct {
44 pub fn new() -> Self {
45 Self {}
46 }
47}
48
49impl OptimizerRule for EliminateAggregateDistinct {
50 fn name(&self) -> &str {
51 "eliminate_aggregate_distinct"
52 }
53
54 fn apply_order(&self) -> Option<ApplyOrder> {
55 Some(ApplyOrder::BottomUp)
56 }
57
58 fn rewrite(
59 &self,
60 plan: LogicalPlan,
61 _config: &dyn OptimizerConfig,
62 ) -> Result<Transformed<LogicalPlan>> {
63 let LogicalPlan::Aggregate(aggregate) = &plan else {
67 return Ok(Transformed::no(plan));
68 };
69 if !can_strip_every_distinct(&aggregate.aggr_expr)? {
70 return Ok(Transformed::no(plan));
71 }
72
73 let name_preserver = NamePreserver::new(&plan);
78 plan.map_expressions(|expr| {
79 let saved_name = name_preserver.save(&expr);
80 expr.transform_down(strip_insensitive_distinct)
81 .map(|t| t.update_data(|e| saved_name.restore(e)))
82 })
83 }
84}
85
86fn can_strip_every_distinct(aggr_expr: &[Expr]) -> Result<bool> {
99 let mut found_distinct = false;
100 let mut all_insensitive = true;
101 for expr in aggr_expr {
102 expr.apply(|e| {
103 if let Expr::AggregateFunction(AggregateFunction { func, params }) = e
104 && params.distinct
105 {
106 found_distinct = true;
107 if func.distinct_handling() != DistinctHandling::Insensitive {
108 all_insensitive = false;
109 return Ok(TreeNodeRecursion::Stop);
110 }
111 }
112 Ok(TreeNodeRecursion::Continue)
113 })?;
114 if !all_insensitive {
115 break;
116 }
117 }
118 Ok(found_distinct && all_insensitive)
119}
120
121fn strip_insensitive_distinct(expr: Expr) -> Result<Transformed<Expr>> {
134 Ok(match expr {
135 Expr::AggregateFunction(mut agg)
136 if agg.params.distinct
137 && agg.func.distinct_handling() == DistinctHandling::Insensitive =>
138 {
139 agg.params.distinct = false;
140 Transformed::yes(Expr::AggregateFunction(agg))
141 }
142 _ => Transformed::no(expr),
143 })
144}
145
146#[cfg(test)]
147mod tests {
148 use super::*;
149 use crate::OptimizerContext;
150 use crate::assert_optimized_plan_eq_snapshot;
151 use crate::test::udfs::DistinctHandlingTestUDAF;
152 use crate::test::*;
153
154 use crate::single_distinct_to_groupby::SingleDistinctToGroupBy;
155 use datafusion_expr::{AggregateUDF, ExprFunctionExt, LogicalPlanBuilder, col, lit};
156 use datafusion_functions_aggregate::expr_fn::{bit_xor, max, min, sum};
157
158 use std::sync::Arc;
159
160 macro_rules! assert_optimized_plan_equal {
161 (
162 $plan:expr,
163 @ $expected:literal $(,)?
164 ) => {{
165 let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
166 let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> =
167 vec![Arc::new(EliminateAggregateDistinct::new())];
168 assert_optimized_plan_eq_snapshot!(
169 optimizer_ctx,
170 rules,
171 $plan,
172 @ $expected,
173 )
174 }};
175 }
176
177 fn tagged(name: &'static str, handling: DistinctHandling) -> AggregateUDF {
182 AggregateUDF::from(DistinctHandlingTestUDAF::new(name, handling))
183 }
184
185 #[test]
187 fn eliminate_distinct_from_min() -> Result<()> {
188 let table_scan = test_table_scan()?;
189 let plan = LogicalPlanBuilder::from(table_scan)
190 .aggregate(vec![col("a")], vec![min(col("b")).distinct().build()?])?
191 .build()?;
192
193 assert_optimized_plan_equal!(plan, @r"
194 Aggregate: groupBy=[[test.a]], aggr=[[min(test.b) AS min(DISTINCT test.b)]]
195 TableScan: test
196 ")
197 }
198
199 #[test]
201 fn keep_distinct_on_sum() -> Result<()> {
202 let table_scan = test_table_scan()?;
203 let plan = LogicalPlanBuilder::from(table_scan)
204 .aggregate(vec![col("a")], vec![sum(col("b")).distinct().build()?])?
205 .build()?;
206
207 assert_optimized_plan_equal!(plan, @r"
208 Aggregate: groupBy=[[test.a]], aggr=[[sum(DISTINCT test.b)]]
209 TableScan: test
210 ")
211 }
212
213 #[test]
215 fn keep_distinct_on_bit_xor() -> Result<()> {
216 let table_scan = test_table_scan()?;
217 let plan = LogicalPlanBuilder::from(table_scan)
218 .aggregate(vec![col("a")], vec![bit_xor(col("b")).distinct().build()?])?
219 .build()?;
220
221 assert_optimized_plan_equal!(plan, @r"
222 Aggregate: groupBy=[[test.a]], aggr=[[bit_xor(DISTINCT test.b)]]
223 TableScan: test
224 ")
225 }
226
227 #[test]
230 fn mixed_node_is_left_alone() -> Result<()> {
231 let table_scan = test_table_scan()?;
232 let plan = LogicalPlanBuilder::from(table_scan)
233 .aggregate(
234 vec![col("a")],
235 vec![
236 min(col("b")).distinct().build()?,
237 sum(col("c")).distinct().build()?,
238 ],
239 )?
240 .build()?;
241
242 assert_optimized_plan_equal!(plan, @r"
243 Aggregate: groupBy=[[test.a]], aggr=[[min(DISTINCT test.b), sum(DISTINCT test.c)]]
244 TableScan: test
245 ")
246 }
247
248 #[test]
250 fn eliminate_distinct_from_every_insensitive_aggregate() -> Result<()> {
251 let table_scan = test_table_scan()?;
252 let plan = LogicalPlanBuilder::from(table_scan)
253 .aggregate(
254 vec![col("a")],
255 vec![
256 min(col("b")).distinct().build()?,
257 max(col("c")).distinct().build()?,
258 ],
259 )?
260 .build()?;
261
262 assert_optimized_plan_equal!(plan, @r"
263 Aggregate: groupBy=[[test.a]], aggr=[[min(test.b) AS min(DISTINCT test.b), max(test.c) AS max(DISTINCT test.c)]]
264 TableScan: test
265 ")
266 }
267
268 #[test]
270 fn eliminate_distinct_beside_non_distinct_aggregate() -> Result<()> {
271 let table_scan = test_table_scan()?;
272 let plan = LogicalPlanBuilder::from(table_scan)
273 .aggregate(
274 vec![col("a")],
275 vec![min(col("b")).distinct().build()?, sum(col("c"))],
276 )?
277 .build()?;
278
279 assert_optimized_plan_equal!(plan, @r"
280 Aggregate: groupBy=[[test.a]], aggr=[[min(test.b) AS min(DISTINCT test.b), sum(test.c)]]
281 TableScan: test
282 ")
283 }
284
285 #[test]
288 fn keep_sensitive_distinct_in_group_expr() -> Result<()> {
289 let table_scan = test_table_scan()?;
290 let plan = LogicalPlanBuilder::from(table_scan)
291 .aggregate(
292 vec![sum(col("c")).distinct().build()?],
293 vec![min(col("b")).distinct().build()?],
294 )?
295 .build()?;
296
297 assert_optimized_plan_equal!(plan, @r"
298 Aggregate: groupBy=[[sum(DISTINCT test.c)]], aggr=[[min(test.b) AS min(DISTINCT test.b)]]
299 TableScan: test
300 ")
301 }
302
303 #[test]
305 fn eliminate_distinct_keeps_filter() -> Result<()> {
306 let table_scan = test_table_scan()?;
307 let plan = LogicalPlanBuilder::from(table_scan)
308 .aggregate(
309 vec![col("a")],
310 vec![
311 min(col("b"))
312 .distinct()
313 .filter(col("c").gt(lit(0u32)))
314 .build()?,
315 ],
316 )?
317 .build()?;
318
319 assert_optimized_plan_equal!(plan, @r"
320 Aggregate: groupBy=[[test.a]], aggr=[[min(test.b) FILTER (WHERE test.c > UInt32(0)) AS min(DISTINCT test.b) FILTER (WHERE test.c > UInt32(0))]]
321 TableScan: test
322 ")
323 }
324
325 #[test]
328 fn mixed_node_still_reaches_single_distinct_to_groupby() -> Result<()> {
329 let table_scan = test_table_scan()?;
330 let plan = LogicalPlanBuilder::from(table_scan)
331 .aggregate(
332 vec![col("a")],
333 vec![
334 min(col("b")).distinct().build()?,
335 sum(col("b")).distinct().build()?,
336 ],
337 )?
338 .build()?;
339
340 let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
341 let rules: Vec<Arc<dyn OptimizerRule + Send + Sync>> = vec![
342 Arc::new(EliminateAggregateDistinct::new()),
343 Arc::new(SingleDistinctToGroupBy::new()),
344 ];
345 assert_optimized_plan_eq_snapshot!(
346 optimizer_ctx,
347 rules,
348 plan,
349 @r"
350 Projection: test.a, min(alias1) AS min(DISTINCT test.b), sum(alias1) AS sum(DISTINCT test.b)
351 Aggregate: groupBy=[[test.a]], aggr=[[min(alias1), sum(alias1)]]
352 Aggregate: groupBy=[[test.a, test.b AS alias1]], aggr=[[]]
353 TableScan: test
354 ",
355 )
356 }
357
358 #[test]
361 fn eliminate_distinct_from_insensitive_udaf() -> Result<()> {
362 let table_scan = test_table_scan()?;
363 let plan = LogicalPlanBuilder::from(table_scan)
364 .aggregate(
365 vec![col("a")],
366 vec![
367 tagged("first_seen", DistinctHandling::Insensitive)
368 .call(vec![col("b")])
369 .distinct()
370 .filter(col("c").gt(lit(0u32)))
371 .order_by(vec![col("b").sort(true, false)])
372 .build()?,
373 ],
374 )?
375 .build()?;
376
377 assert_optimized_plan_equal!(plan, @r"
378 Aggregate: groupBy=[[test.a]], aggr=[[first_seen(test.b) FILTER (WHERE test.c > UInt32(0)) ORDER BY [test.b ASC NULLS LAST] AS first_seen(DISTINCT test.b) FILTER (WHERE test.c > UInt32(0)) ORDER BY [test.b ASC NULLS LAST]]]
379 TableScan: test
380 ")
381 }
382
383 #[test]
385 fn keep_distinct_on_sensitive_udaf() -> Result<()> {
386 let table_scan = test_table_scan()?;
387 let plan = LogicalPlanBuilder::from(table_scan)
388 .aggregate(
389 vec![col("a")],
390 vec![
391 tagged("counts_uniques", DistinctHandling::Sensitive)
392 .call(vec![col("b")])
393 .distinct()
394 .build()?,
395 ],
396 )?
397 .build()?;
398
399 assert_optimized_plan_equal!(plan, @r"
400 Aggregate: groupBy=[[test.a]], aggr=[[counts_uniques(DISTINCT test.b)]]
401 TableScan: test
402 ")
403 }
404
405 #[test]
408 fn keep_distinct_on_unsupported_udaf() -> Result<()> {
409 let table_scan = test_table_scan()?;
410 let plan = LogicalPlanBuilder::from(table_scan)
411 .aggregate(
412 vec![col("a")],
413 vec![
414 tagged("needs_dedup", DistinctHandling::Unsupported)
415 .call(vec![col("b")])
416 .distinct()
417 .build()?,
418 ],
419 )?
420 .build()?;
421
422 assert_optimized_plan_equal!(plan, @r"
423 Aggregate: groupBy=[[test.a]], aggr=[[needs_dedup(DISTINCT test.b)]]
424 TableScan: test
425 ")
426 }
427
428 #[test]
431 fn mixed_udaf_node_is_left_alone() -> Result<()> {
432 let table_scan = test_table_scan()?;
433 let plan = LogicalPlanBuilder::from(table_scan)
434 .aggregate(
435 vec![col("a")],
436 vec![
437 tagged("first_seen", DistinctHandling::Insensitive)
438 .call(vec![col("b")])
439 .distinct()
440 .build()?,
441 tagged("counts_uniques", DistinctHandling::Sensitive)
442 .call(vec![col("c")])
443 .distinct()
444 .build()?,
445 ],
446 )?
447 .build()?;
448
449 assert_optimized_plan_equal!(plan, @r"
450 Aggregate: groupBy=[[test.a]], aggr=[[first_seen(DISTINCT test.b), counts_uniques(DISTINCT test.c)]]
451 TableScan: test
452 ")
453 }
454
455 #[test]
458 fn already_aliased_aggregate_gets_no_second_alias() -> Result<()> {
459 let table_scan = test_table_scan()?;
460 let plan = LogicalPlanBuilder::from(table_scan)
461 .aggregate(
462 vec![col("a")],
463 vec![
464 tagged("first_seen", DistinctHandling::Insensitive)
465 .call(vec![col("b")])
466 .distinct()
467 .build()?
468 .alias("m"),
469 ],
470 )?
471 .build()?;
472
473 assert_optimized_plan_equal!(plan, @r"
474 Aggregate: groupBy=[[test.a]], aggr=[[first_seen(test.b) AS m]]
475 TableScan: test
476 ")
477 }
478
479 #[test]
482 fn with_aliases_delegates_distinct_handling() -> Result<()> {
483 let aliased = tagged("first_seen", DistinctHandling::Insensitive)
484 .with_aliases(["first_hit"]);
485 assert_eq!(aliased.distinct_handling(), DistinctHandling::Insensitive);
486
487 let table_scan = test_table_scan()?;
488 let plan = LogicalPlanBuilder::from(table_scan)
489 .aggregate(
490 vec![col("a")],
491 vec![aliased.call(vec![col("b")]).distinct().build()?],
492 )?
493 .build()?;
494
495 assert_optimized_plan_equal!(plan, @r"
496 Aggregate: groupBy=[[test.a]], aggr=[[first_seen(test.b) AS first_seen(DISTINCT test.b)]]
497 TableScan: test
498 ")
499 }
500
501 #[test]
503 fn non_aggregate_plan_is_unchanged() -> Result<()> {
504 let table_scan = test_table_scan()?;
505 let plan = LogicalPlanBuilder::from(table_scan)
506 .filter(col("b").gt(lit(1u32)))?
507 .project(vec![col("a")])?
508 .build()?;
509
510 assert_optimized_plan_equal!(plan, @r"
511 Projection: test.a
512 Filter: test.b > UInt32(1)
513 TableScan: test
514 ")
515 }
516}