datafusion_optimizer/
replace_distinct_aggregate.rs1use crate::optimizer::{ApplyOrder, ApplyOrder::BottomUp};
8use crate::{OptimizerConfig, OptimizerRule};
9use std::sync::Arc;
10
11use datafusion_common::tree_node::Transformed;
12use datafusion_common::{Column, Dependency, Result};
13use datafusion_expr::expr_rewriter::normalize_cols;
14use datafusion_expr::utils::expand_wildcard;
15use datafusion_expr::{Aggregate, Distinct, DistinctOn, Expr, LogicalPlan};
16use datafusion_expr::{ExprFunctionExt, Limit, LogicalPlanBuilder, col, lit};
17
18#[derive(Default, Debug)]
56pub struct ReplaceDistinctWithAggregate {}
57
58impl ReplaceDistinctWithAggregate {
59 #[expect(missing_docs)]
60 pub fn new() -> Self {
61 Self {}
62 }
63}
64
65impl OptimizerRule for ReplaceDistinctWithAggregate {
66 fn rewrite(
67 &self,
68 plan: LogicalPlan,
69 config: &dyn OptimizerConfig,
70 ) -> Result<Transformed<LogicalPlan>> {
71 match plan {
72 LogicalPlan::Distinct(Distinct::All(input)) => {
73 let group_expr = expand_wildcard(input.schema(), &input, None)?;
74
75 if group_expr.is_empty() {
76 return Ok(Transformed::yes(LogicalPlan::Limit(Limit {
79 skip: None,
80 fetch: Some(Box::new(lit(1i64))),
81 input,
82 })));
83 }
84
85 let field_count = input.schema().fields().len();
86 for dep in input.schema().functional_dependencies().iter() {
87 if dep.mode == Dependency::Single
96 && dep.is_valid_across_nulls(input.schema())
97 && dep.source_indices.len() >= field_count
98 && dep.source_indices[..field_count]
99 .iter()
100 .enumerate()
101 .all(|(idx, f_idx)| idx == *f_idx)
102 {
103 return Ok(Transformed::yes(Arc::unwrap_or_clone(input)));
104 }
105 }
106
107 let aggr_plan = LogicalPlan::Aggregate(Aggregate::try_new(
109 input,
110 group_expr,
111 vec![],
112 )?);
113 Ok(Transformed::yes(aggr_plan))
114 }
115 LogicalPlan::Distinct(Distinct::On(DistinctOn {
116 select_expr,
117 on_expr,
118 sort_expr,
119 input,
120 schema,
121 })) => {
122 let expr_cnt = on_expr.len();
123
124 let first_value_udaf: Arc<datafusion_expr::AggregateUDF> =
126 config.function_registry().unwrap().udaf("first_value")?;
127 let aggr_expr = select_expr.into_iter().map(|e| {
128 if let Some(order_by) = &sort_expr {
129 first_value_udaf
130 .call(vec![e])
131 .order_by(order_by.clone())
132 .build()
133 .unwrap()
135 } else {
136 first_value_udaf.call(vec![e])
137 }
138 });
139
140 let aggr_expr = normalize_cols(aggr_expr, input.as_ref())?;
141 let group_expr = normalize_cols(on_expr, input.as_ref())?;
142
143 let plan = LogicalPlan::Aggregate(Aggregate::try_new(
145 input, group_expr, aggr_expr,
146 )?);
147 let lpb = LogicalPlanBuilder::from(plan);
150
151 let plan = if let Some(mut sort_expr) = sort_expr {
152 sort_expr.truncate(expr_cnt);
158
159 lpb.sort(sort_expr)?.build()?
160 } else {
161 lpb.build()?
162 };
163
164 let project_exprs = plan
168 .schema()
169 .iter()
170 .skip(expr_cnt)
171 .zip(schema.iter())
172 .map(|((new_qualifier, new_field), (old_qualifier, old_field))| {
173 col(Column::from((new_qualifier, new_field)))
174 .alias_qualified(old_qualifier.cloned(), old_field.name())
175 })
176 .collect::<Vec<Expr>>();
177
178 let plan = LogicalPlanBuilder::from(plan)
179 .project(project_exprs)?
180 .build()?;
181
182 Ok(Transformed::yes(plan))
183 }
184 _ => Ok(Transformed::no(plan)),
185 }
186 }
187
188 fn name(&self) -> &str {
189 "replace_distinct_aggregate"
190 }
191
192 fn apply_order(&self) -> Option<ApplyOrder> {
193 Some(BottomUp)
194 }
195}
196
197#[cfg(test)]
198mod tests {
199 use crate::assert_optimized_plan_eq_snapshot;
200 use crate::replace_distinct_aggregate::ReplaceDistinctWithAggregate;
201 use crate::test::*;
202 use arrow::datatypes::{Fields, Schema};
203 use std::sync::Arc;
204
205 use crate::OptimizerContext;
206 use datafusion_common::Result;
207 use datafusion_expr::{
208 Expr, col, logical_plan::builder::LogicalPlanBuilder, table_scan,
209 };
210 use datafusion_functions_aggregate::sum::sum;
211
212 macro_rules! assert_optimized_plan_equal {
213 (
214 $plan:expr,
215 @ $expected:literal $(,)?
216 ) => {{
217 let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
218 let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(ReplaceDistinctWithAggregate::new())];
219 assert_optimized_plan_eq_snapshot!(
220 optimizer_ctx,
221 rules,
222 $plan,
223 @ $expected,
224 )
225 }};
226 }
227
228 #[test]
229 fn eliminate_redundant_distinct_simple() -> Result<()> {
230 let table_scan = test_table_scan().unwrap();
231 let plan = LogicalPlanBuilder::from(table_scan)
232 .aggregate(vec![col("c")], Vec::<Expr>::new())?
233 .project(vec![col("c")])?
234 .distinct()?
235 .build()?;
236
237 assert_optimized_plan_equal!(plan, @r"
238 Projection: test.c
239 Aggregate: groupBy=[[test.c]], aggr=[[]]
240 TableScan: test
241 ")
242 }
243
244 #[test]
245 fn eliminate_redundant_distinct_pair() -> Result<()> {
246 let table_scan = test_table_scan().unwrap();
247 let plan = LogicalPlanBuilder::from(table_scan)
248 .aggregate(vec![col("a"), col("b")], Vec::<Expr>::new())?
249 .project(vec![col("a"), col("b")])?
250 .distinct()?
251 .build()?;
252
253 assert_optimized_plan_equal!(plan, @r"
254 Projection: test.a, test.b
255 Aggregate: groupBy=[[test.a, test.b]], aggr=[[]]
256 TableScan: test
257 ")
258 }
259
260 #[test]
261 fn do_not_eliminate_distinct() -> Result<()> {
262 let table_scan = test_table_scan().unwrap();
263 let plan = LogicalPlanBuilder::from(table_scan)
264 .project(vec![col("a"), col("b")])?
265 .distinct()?
266 .build()?;
267
268 assert_optimized_plan_equal!(plan, @r"
269 Aggregate: groupBy=[[test.a, test.b]], aggr=[[]]
270 Projection: test.a, test.b
271 TableScan: test
272 ")
273 }
274
275 #[test]
276 fn do_not_eliminate_distinct_with_aggr() -> Result<()> {
277 let table_scan = test_table_scan().unwrap();
278 let plan = LogicalPlanBuilder::from(table_scan)
279 .aggregate(vec![col("a"), col("b"), col("c")], vec![sum(col("c"))])?
280 .project(vec![col("a"), col("b")])?
281 .distinct()?
282 .build()?;
283
284 assert_optimized_plan_equal!(plan, @r"
285 Aggregate: groupBy=[[test.a, test.b]], aggr=[[]]
286 Projection: test.a, test.b
287 Aggregate: groupBy=[[test.a, test.b, test.c]], aggr=[[sum(test.c)]]
288 TableScan: test
289 ")
290 }
291
292 #[test]
293 fn use_limit_1_when_no_columns() -> Result<()> {
294 let plan = table_scan(Some("test"), &Schema::new(Fields::empty()), None)?
295 .distinct()?
296 .build()?;
297
298 assert_optimized_plan_equal!(plan, @r"
299 Limit: skip=0, fetch=1
300 TableScan: test
301 ")
302 }
303}