1use crate::optimizer::ApplyOrder;
7use crate::{OptimizerConfig, OptimizerRule};
8use datafusion_common::Result;
9use datafusion_common::tree_node::Transformed;
10use datafusion_expr::expr_rewriter::coerce_plan_expr_for_schema;
11use datafusion_expr::{Distinct, LogicalPlan, Projection, Union};
12use itertools::Itertools;
13use std::sync::Arc;
14
15#[derive(Default, Debug)]
16pub struct OptimizeUnions;
20
21impl OptimizeUnions {
22 #[expect(missing_docs)]
23 pub fn new() -> Self {
24 Self {}
25 }
26}
27
28impl OptimizerRule for OptimizeUnions {
29 fn name(&self) -> &str {
30 "optimize_unions"
31 }
32
33 fn apply_order(&self) -> Option<ApplyOrder> {
34 Some(ApplyOrder::BottomUp)
35 }
36
37 fn rewrite(
38 &self,
39 plan: LogicalPlan,
40 _config: &dyn OptimizerConfig,
41 ) -> Result<Transformed<LogicalPlan>> {
42 match plan {
43 LogicalPlan::Union(Union { mut inputs, .. }) if inputs.len() == 1 => Ok(
44 Transformed::yes(Arc::unwrap_or_clone(inputs.pop().unwrap())),
45 ),
46 LogicalPlan::Union(Union { inputs, schema }) => {
47 let inputs = inputs
48 .into_iter()
49 .flat_map(extract_plans_from_union)
50 .map(|plan| Ok(Arc::new(coerce_plan_expr_for_schema(plan, &schema)?)))
51 .collect::<Result<Vec<_>>>()?;
52
53 Ok(Transformed::yes(LogicalPlan::Union(Union {
54 inputs,
55 schema,
56 })))
57 }
58 LogicalPlan::Distinct(Distinct::All(nested_plan)) => {
59 match Arc::unwrap_or_clone(nested_plan) {
60 LogicalPlan::Union(Union { inputs, schema }) => {
61 let inputs = inputs
62 .into_iter()
63 .map(extract_plan_from_distinct)
64 .flat_map(extract_plans_from_union)
65 .map(|plan| coerce_plan_expr_for_schema(plan, &schema))
66 .collect::<Result<Vec<_>>>()?;
67
68 Ok(Transformed::yes(LogicalPlan::Distinct(Distinct::All(
69 Arc::new(LogicalPlan::Union(Union {
70 inputs: inputs.into_iter().map(Arc::new).collect_vec(),
71 schema: Arc::clone(&schema),
72 })),
73 ))))
74 }
75 nested_plan => Ok(Transformed::no(LogicalPlan::Distinct(
76 Distinct::All(Arc::new(nested_plan)),
77 ))),
78 }
79 }
80 _ => Ok(Transformed::no(plan)),
81 }
82 }
83}
84
85fn extract_plans_from_union(plan: Arc<LogicalPlan>) -> Vec<LogicalPlan> {
86 match Arc::unwrap_or_clone(plan) {
87 LogicalPlan::Union(Union { inputs, .. }) => inputs
88 .into_iter()
89 .map(Arc::unwrap_or_clone)
90 .collect::<Vec<_>>(),
91 LogicalPlan::Projection(Projection {
99 expr,
100 input,
101 schema,
102 ..
103 }) => match Arc::unwrap_or_clone(input) {
104 LogicalPlan::Union(Union { inputs, .. }) => inputs
105 .into_iter()
106 .map(Arc::unwrap_or_clone)
107 .map(|plan| {
108 LogicalPlan::Projection(
109 Projection::try_new_with_schema(
110 expr.clone(),
111 Arc::new(plan),
112 Arc::clone(&schema),
113 )
114 .unwrap(),
115 )
116 })
117 .collect::<Vec<_>>(),
118
119 plan => vec![LogicalPlan::Projection(
120 Projection::try_new_with_schema(expr, Arc::new(plan), schema).unwrap(),
121 )],
122 },
123 plan => vec![plan],
124 }
125}
126
127fn extract_plan_from_distinct(plan: Arc<LogicalPlan>) -> Arc<LogicalPlan> {
128 match Arc::unwrap_or_clone(plan) {
129 LogicalPlan::Distinct(Distinct::All(plan)) => plan,
130 plan => Arc::new(plan),
131 }
132}
133
134#[cfg(test)]
135mod tests {
136 use super::*;
137 use crate::OptimizerContext;
138 use crate::analyzer::Analyzer;
139 use crate::analyzer::type_coercion::TypeCoercion;
140 use crate::assert_optimized_plan_eq_snapshot;
141 use arrow::datatypes::{DataType, Field, Schema};
142 use datafusion_common::config::ConfigOptions;
143 use datafusion_expr::{col, logical_plan::table_scan};
144
145 fn schema() -> Schema {
146 Schema::new(vec![
147 Field::new("id", DataType::Int32, false),
148 Field::new("key", DataType::Utf8, false),
149 Field::new("value", DataType::Float64, false),
150 ])
151 }
152
153 macro_rules! assert_optimized_plan_equal {
154 (
155 $plan:expr,
156 @ $expected:literal $(,)?
157 ) => {{
158 let options = ConfigOptions::default();
159 let analyzed_plan = Analyzer::with_rules(vec![Arc::new(TypeCoercion::new())])
160 .execute_and_check($plan, &options, |_, _| {})?;
161 let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
162 let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(OptimizeUnions::new())];
163 assert_optimized_plan_eq_snapshot!(
164 optimizer_ctx,
165 rules,
166 analyzed_plan,
167 @ $expected,
168 )
169 }};
170 }
171
172 #[test]
173 fn eliminate_nothing() -> Result<()> {
174 let plan_builder = table_scan(Some("table"), &schema(), None)?;
175
176 let plan = plan_builder.clone().union(plan_builder.build()?)?.build()?;
177
178 assert_optimized_plan_equal!(plan, @r"
179 Union
180 TableScan: table
181 TableScan: table
182 ")
183 }
184
185 #[test]
186 fn eliminate_distinct_nothing() -> Result<()> {
187 let plan_builder = table_scan(Some("table"), &schema(), None)?;
188
189 let plan = plan_builder
190 .clone()
191 .union_distinct(plan_builder.build()?)?
192 .build()?;
193
194 assert_optimized_plan_equal!(plan, @r"
195 Distinct:
196 Union
197 TableScan: table
198 TableScan: table
199 ")
200 }
201
202 #[test]
203 fn eliminate_nested_union() -> Result<()> {
204 let plan_builder = table_scan(Some("table"), &schema(), None)?;
205
206 let plan = plan_builder
207 .clone()
208 .union(plan_builder.clone().build()?)?
209 .union(plan_builder.clone().build()?)?
210 .union(plan_builder.build()?)?
211 .build()?;
212
213 assert_optimized_plan_equal!(plan, @r"
214 Union
215 TableScan: table
216 TableScan: table
217 TableScan: table
218 TableScan: table
219 ")
220 }
221
222 #[test]
223 fn eliminate_nested_union_with_distinct_union() -> Result<()> {
224 let plan_builder = table_scan(Some("table"), &schema(), None)?;
225
226 let plan = plan_builder
227 .clone()
228 .union_distinct(plan_builder.clone().build()?)?
229 .union(plan_builder.clone().build()?)?
230 .union(plan_builder.build()?)?
231 .build()?;
232
233 assert_optimized_plan_equal!(plan, @r"
234 Union
235 Distinct:
236 Union
237 TableScan: table
238 TableScan: table
239 TableScan: table
240 TableScan: table
241 ")
242 }
243
244 #[test]
245 fn eliminate_nested_distinct_union() -> Result<()> {
246 let plan_builder = table_scan(Some("table"), &schema(), None)?;
247
248 let plan = plan_builder
249 .clone()
250 .union(plan_builder.clone().build()?)?
251 .union_distinct(plan_builder.clone().build()?)?
252 .union(plan_builder.clone().build()?)?
253 .union_distinct(plan_builder.build()?)?
254 .build()?;
255
256 assert_optimized_plan_equal!(plan, @r"
257 Distinct:
258 Union
259 TableScan: table
260 TableScan: table
261 TableScan: table
262 TableScan: table
263 TableScan: table
264 ")
265 }
266
267 #[test]
268 fn eliminate_nested_distinct_union_with_distinct_table() -> Result<()> {
269 let plan_builder = table_scan(Some("table"), &schema(), None)?;
270
271 let plan = plan_builder
272 .clone()
273 .union_distinct(plan_builder.clone().distinct()?.build()?)?
274 .union(plan_builder.clone().distinct()?.build()?)?
275 .union_distinct(plan_builder.build()?)?
276 .build()?;
277
278 assert_optimized_plan_equal!(plan, @r"
279 Distinct:
280 Union
281 TableScan: table
282 TableScan: table
283 TableScan: table
284 TableScan: table
285 ")
286 }
287
288 #[test]
291 fn eliminate_nested_union_with_projection() -> Result<()> {
292 let plan_builder = table_scan(Some("table"), &schema(), None)?;
293
294 let plan = plan_builder
295 .clone()
296 .union(
297 plan_builder
298 .clone()
299 .project(vec![col("id").alias("table_id"), col("key"), col("value")])?
300 .build()?,
301 )?
302 .union(
303 plan_builder
304 .project(vec![col("id").alias("_id"), col("key"), col("value")])?
305 .build()?,
306 )?
307 .build()?;
308
309 assert_optimized_plan_equal!(plan, @r"
310 Union
311 TableScan: table
312 Projection: table.id AS id, table.key, table.value
313 TableScan: table
314 Projection: table.id AS id, table.key, table.value
315 TableScan: table
316 ")
317 }
318
319 #[test]
320 fn eliminate_nested_distinct_union_with_projection() -> Result<()> {
321 let plan_builder = table_scan(Some("table"), &schema(), None)?;
322
323 let plan = plan_builder
324 .clone()
325 .union_distinct(
326 plan_builder
327 .clone()
328 .project(vec![col("id").alias("table_id"), col("key"), col("value")])?
329 .build()?,
330 )?
331 .union_distinct(
332 plan_builder
333 .project(vec![col("id").alias("_id"), col("key"), col("value")])?
334 .build()?,
335 )?
336 .build()?;
337
338 assert_optimized_plan_equal!(plan, @r"
339 Distinct:
340 Union
341 TableScan: table
342 Projection: table.id AS id, table.key, table.value
343 TableScan: table
344 Projection: table.id AS id, table.key, table.value
345 TableScan: table
346 ")
347 }
348
349 #[test]
350 fn eliminate_nested_union_in_projection() -> Result<()> {
351 let plan_builder = table_scan(Some("table"), &schema(), None)?;
352
353 let plan = plan_builder
354 .clone()
355 .union(plan_builder.clone().build()?)?
356 .project(vec![col("id").alias("table_id"), col("key"), col("value")])?
357 .union(plan_builder.build()?)?
358 .build()?;
359
360 assert_optimized_plan_equal!(plan, @r"
361 Union
362 Projection: id AS table_id, key, value
363 TableScan: table
364 Projection: id AS table_id, key, value
365 TableScan: table
366 TableScan: table
367 ")
368 }
369
370 #[test]
371 fn eliminate_nested_union_with_type_cast_projection() -> Result<()> {
372 let table_1 = table_scan(
373 Some("table_1"),
374 &Schema::new(vec![
375 Field::new("id", DataType::Int64, false),
376 Field::new("key", DataType::Utf8, false),
377 Field::new("value", DataType::Float64, false),
378 ]),
379 None,
380 )?;
381
382 let table_2 = table_scan(
383 Some("table_1"),
384 &Schema::new(vec![
385 Field::new("id", DataType::Int32, false),
386 Field::new("key", DataType::Utf8, false),
387 Field::new("value", DataType::Float32, false),
388 ]),
389 None,
390 )?;
391
392 let table_3 = table_scan(
393 Some("table_1"),
394 &Schema::new(vec![
395 Field::new("id", DataType::Int16, false),
396 Field::new("key", DataType::Utf8, false),
397 Field::new("value", DataType::Float32, false),
398 ]),
399 None,
400 )?;
401
402 let plan = table_1
403 .union(table_2.build()?)?
404 .union(table_3.build()?)?
405 .build()?;
406
407 assert_optimized_plan_equal!(plan, @r"
408 Union
409 TableScan: table_1
410 Projection: CAST(table_1.id AS Int64) AS id, table_1.key, CAST(table_1.value AS Float64) AS value
411 TableScan: table_1
412 Projection: CAST(table_1.id AS Int64) AS id, table_1.key, CAST(table_1.value AS Float64) AS value
413 TableScan: table_1
414 ")
415 }
416
417 #[test]
418 fn eliminate_nested_distinct_union_with_type_cast_projection() -> Result<()> {
419 let table_1 = table_scan(
420 Some("table_1"),
421 &Schema::new(vec![
422 Field::new("id", DataType::Int64, false),
423 Field::new("key", DataType::Utf8, false),
424 Field::new("value", DataType::Float64, false),
425 ]),
426 None,
427 )?;
428
429 let table_2 = table_scan(
430 Some("table_1"),
431 &Schema::new(vec![
432 Field::new("id", DataType::Int32, false),
433 Field::new("key", DataType::Utf8, false),
434 Field::new("value", DataType::Float32, false),
435 ]),
436 None,
437 )?;
438
439 let table_3 = table_scan(
440 Some("table_1"),
441 &Schema::new(vec![
442 Field::new("id", DataType::Int16, false),
443 Field::new("key", DataType::Utf8, false),
444 Field::new("value", DataType::Float32, false),
445 ]),
446 None,
447 )?;
448
449 let plan = table_1
450 .union_distinct(table_2.build()?)?
451 .union_distinct(table_3.build()?)?
452 .build()?;
453
454 assert_optimized_plan_equal!(plan, @r"
455 Distinct:
456 Union
457 TableScan: table_1
458 Projection: CAST(table_1.id AS Int64) AS id, table_1.key, CAST(table_1.value AS Float64) AS value
459 TableScan: table_1
460 Projection: CAST(table_1.id AS Int64) AS id, table_1.key, CAST(table_1.value AS Float64) AS value
461 TableScan: table_1
462 ")
463 }
464
465 #[test]
466 fn eliminate_one_union() -> Result<()> {
467 let plan = table_scan(Some("table"), &schema(), None)?.build()?;
468 let schema = Arc::clone(plan.schema());
469 let plan = LogicalPlan::Union(Union {
472 inputs: vec![Arc::new(plan)],
473 schema,
474 });
475
476 assert_optimized_plan_eq_snapshot!(
480 OptimizerContext::new().with_max_passes(1),
481 vec![Arc::new(OptimizeUnions::new())],
482 plan,
483 @"TableScan: table"
484 )
485 }
486}