Skip to main content

datafusion_optimizer/
unions_to_filter.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//! Rewrites `UNION DISTINCT` branches that differ only by filter predicates
6//! into a single filtered branch plus `DISTINCT`.
7
8use crate::utils::is_repeatable;
9use crate::{OptimizerConfig, OptimizerRule};
10use datafusion_common::Result;
11use datafusion_common::tree_node::{
12    Transformed, TreeNode, TreeNodeRecursion, TreeNodeRewriter,
13};
14use datafusion_expr::expr_rewriter::coerce_plan_expr_for_schema;
15use datafusion_expr::logical_plan::builder::LogicalPlanBuilder;
16use datafusion_expr::utils::disjunction;
17use datafusion_expr::{
18    Distinct, Expr, Filter, LogicalPlan, Projection, SubqueryAlias, TableSource, Union,
19};
20use log::debug;
21use std::sync::Arc;
22
23#[derive(Default, Debug)]
24pub struct UnionsToFilter;
25
26impl UnionsToFilter {
27    #[expect(missing_docs)]
28    pub fn new() -> Self {
29        Self
30    }
31}
32
33impl OptimizerRule for UnionsToFilter {
34    fn name(&self) -> &str {
35        "unions_to_filter"
36    }
37
38    fn rewrite(
39        &self,
40        plan: LogicalPlan,
41        config: &dyn OptimizerConfig,
42    ) -> Result<Transformed<LogicalPlan>> {
43        if !config.options().optimizer.enable_unions_to_filter {
44            return Ok(Transformed::no(plan));
45        }
46
47        // Fast pre-check: if the plan tree has no Distinct::All node at all we can
48        // skip the expensive bottom-up rewrite_with_subqueries traversal entirely.
49        // This matters for large UNION ALL plans (e.g. TPC-DS Q4) where the rule
50        // can never fire and the traversal overhead is otherwise measurable.
51        if !plan.exists(|p| Ok(matches!(p, LogicalPlan::Distinct(Distinct::All(_)))))? {
52            return Ok(Transformed::no(plan));
53        }
54
55        plan.rewrite_with_subqueries(&mut UnionsToFilterRewriter)
56    }
57}
58
59struct UnionsToFilterRewriter;
60
61impl TreeNodeRewriter for UnionsToFilterRewriter {
62    type Node = LogicalPlan;
63
64    fn f_up(&mut self, plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
65        match &plan {
66            LogicalPlan::Distinct(Distinct::All(input)) => {
67                match try_rewrite_distinct_union(input.as_ref().clone())? {
68                    Some(rewritten) => Ok(Transformed::yes(rewritten)),
69                    None => Ok(Transformed::no(plan)),
70                }
71            }
72            _ => Ok(Transformed::no(plan)),
73        }
74    }
75}
76
77fn try_rewrite_distinct_union(plan: LogicalPlan) -> Result<Option<LogicalPlan>> {
78    let LogicalPlan::Union(Union { inputs, schema }) = plan else {
79        debug!("unions_to_filter skipped: input is not a UNION");
80        return Ok(None);
81    };
82
83    if inputs.len() < 2 {
84        debug!(
85            "unions_to_filter skipped: UNION has {} input(s), need at least 2",
86            inputs.len()
87        );
88        return Ok(None);
89    }
90
91    // Use a Vec instead of HashMap: union branches are typically 2-10 entries,
92    // so a linear scan with PartialEq is faster than recursively hashing entire
93    // LogicalPlan subtrees (O(N * tree_size) hashing for every insert/lookup).
94    let mut grouped: Vec<(GroupKey, Vec<Expr>)> = Vec::with_capacity(inputs.len());
95    let mut transformed = false;
96
97    for input in inputs {
98        let Some(branch) = extract_branch(Arc::unwrap_or_clone(input))? else {
99            return Ok(None);
100        };
101
102        let table_sources = collect_table_sources(&branch.source)?;
103        let key = GroupKey {
104            source: branch.source,
105            wrappers: branch.wrappers,
106            table_sources,
107        };
108        if let Some((_, conds)) = grouped.iter_mut().find(|(k, _)| k == &key) {
109            conds.push(branch.predicate);
110            transformed = true;
111        } else {
112            grouped.push((key, vec![branch.predicate]));
113        }
114    }
115
116    if !transformed {
117        debug!("unions_to_filter skipped: no branch groups could be merged");
118        return Ok(None);
119    }
120
121    let mut builder: Option<LogicalPlanBuilder> = None;
122    for (key, predicates) in grouped {
123        let combined =
124            disjunction(predicates).expect("union branches always provide predicates");
125        let branch = LogicalPlanBuilder::from(key.source)
126            .filter(combined)?
127            .build()?;
128        let branch = wrap_branch(branch, &key.wrappers)?;
129        let branch = coerce_plan_expr_for_schema(branch, &schema)?;
130        let branch = align_plan_to_schema(branch, Arc::clone(&schema))?;
131        builder = Some(match builder {
132            None => LogicalPlanBuilder::from(branch),
133            Some(builder) => builder.union(branch)?,
134        });
135    }
136
137    let union = builder
138        .expect("at least one branch after rewrite")
139        .build()?;
140    Ok(Some(LogicalPlan::Distinct(Distinct::All(Arc::new(union)))))
141}
142
143struct UnionBranch {
144    source: LogicalPlan,
145    predicate: Expr,
146    wrappers: Vec<Wrapper>,
147}
148
149fn extract_branch(plan: LogicalPlan) -> Result<Option<UnionBranch>> {
150    let (wrappers, plan) = peel_wrappers(plan);
151
152    // Volatile or subquery expressions in the projection must not be merged:
153    // they are evaluated once per branch in the original plan but would be
154    // evaluated once per combined row after the rewrite, which can change the
155    // output row set.
156    if !wrapper_projections_are_safe(&wrappers) {
157        debug!(
158            "unions_to_filter skipped: projection wrapper contains volatile expression or subquery"
159        );
160        return Ok(None);
161    }
162
163    let (source, predicate) = match plan {
164        LogicalPlan::Filter(Filter {
165            predicate, input, ..
166        }) => {
167            if !is_repeatable(&predicate) {
168                debug!(
169                    "unions_to_filter skipped: branch predicate contains volatility or a subquery"
170                );
171                return Ok(None);
172            }
173            // Keep the input intact: projections compute values and aliases
174            // define the qualifiers used by the predicate. GroupKey compares
175            // the retained plans before merging their predicates.
176            (Arc::unwrap_or_clone(input), predicate)
177        }
178        // A Limit or Sort node changes the row-set semantics of the branch.
179        // Merging two such branches into one would silently drop the per-branch
180        // row restriction (LIMIT) or rely on an order guarantee that UNION does
181        // not preserve (ORDER BY).  Bail out to leave the UNION unchanged.
182        LogicalPlan::Limit(_) => {
183            debug!("unions_to_filter skipped: branch contains LIMIT");
184            return Ok(None);
185        }
186        LogicalPlan::Sort(_) => {
187            debug!("unions_to_filter skipped: branch contains ORDER BY / SORT");
188            return Ok(None);
189        }
190        other => (
191            other,
192            Expr::Literal(datafusion_common::ScalarValue::Boolean(Some(true)), None),
193        ),
194    };
195
196    if !source_is_safe(&source)? {
197        debug!(
198            "unions_to_filter skipped: source contains volatile expression or subquery"
199        );
200        return Ok(None);
201    }
202
203    Ok(Some(UnionBranch {
204        source,
205        predicate,
206        wrappers,
207    }))
208}
209
210struct GroupKey {
211    source: LogicalPlan,
212    wrappers: Vec<Wrapper>,
213    // LogicalPlan equality deliberately ignores TableScan::source. Retain the
214    // corresponding Arcs so structurally identical scans over different data
215    // cannot be grouped together.
216    table_sources: Vec<Arc<dyn TableSource>>,
217}
218
219impl PartialEq for GroupKey {
220    fn eq(&self, other: &Self) -> bool {
221        self.source == other.source
222            && self.wrappers == other.wrappers
223            && self.table_sources.len() == other.table_sources.len()
224            && self
225                .table_sources
226                .iter()
227                .zip(&other.table_sources)
228                .all(|(left, right)| Arc::ptr_eq(left, right))
229    }
230}
231
232impl Eq for GroupKey {}
233
234#[derive(Debug, Clone, PartialEq, Eq)]
235enum Wrapper {
236    Projection {
237        expr: Vec<Expr>,
238        schema: datafusion_common::DFSchemaRef,
239    },
240    SubqueryAlias {
241        alias: datafusion_common::TableReference,
242        schema: datafusion_common::DFSchemaRef,
243    },
244}
245
246fn peel_wrappers(mut plan: LogicalPlan) -> (Vec<Wrapper>, LogicalPlan) {
247    let mut wrappers = vec![];
248    loop {
249        match plan {
250            LogicalPlan::Projection(Projection {
251                expr,
252                input,
253                schema,
254                ..
255            }) => {
256                wrappers.push(Wrapper::Projection { expr, schema });
257                plan = Arc::unwrap_or_clone(input);
258            }
259            LogicalPlan::SubqueryAlias(SubqueryAlias {
260                input,
261                alias,
262                schema,
263                ..
264            }) => {
265                wrappers.push(Wrapper::SubqueryAlias { alias, schema });
266                plan = Arc::unwrap_or_clone(input);
267            }
268            other => return (wrappers, other),
269        }
270    }
271}
272
273fn wrap_branch(mut plan: LogicalPlan, wrappers: &[Wrapper]) -> Result<LogicalPlan> {
274    for wrapper in wrappers.iter().rev() {
275        plan = match wrapper {
276            Wrapper::Projection { expr, schema } => {
277                LogicalPlan::Projection(Projection::try_new_with_schema(
278                    expr.clone(),
279                    Arc::new(plan),
280                    Arc::clone(schema),
281                )?)
282            }
283            // SubqueryAlias::try_new recomputes the schema from the new input.
284            // This is safe because the source table is unchanged; only the
285            // filter predicate differs, so the recomputed schema matches the
286            // original one stored in peel_wrappers.
287            Wrapper::SubqueryAlias { alias, .. } => LogicalPlan::SubqueryAlias(
288                SubqueryAlias::try_new(Arc::new(plan), alias.clone())?,
289            ),
290        };
291    }
292    Ok(plan)
293}
294
295fn align_plan_to_schema(
296    plan: LogicalPlan,
297    schema: datafusion_common::DFSchemaRef,
298) -> Result<LogicalPlan> {
299    if plan.schema() == &schema {
300        return Ok(plan);
301    }
302
303    let expr = plan
304        .schema()
305        .iter()
306        .enumerate()
307        .map(|(i, _)| {
308            Expr::Column(datafusion_common::Column::from(
309                plan.schema().qualified_field(i),
310            ))
311        })
312        .collect::<Vec<_>>();
313
314    Ok(LogicalPlan::Projection(Projection::try_new_with_schema(
315        expr,
316        Arc::new(plan),
317        schema,
318    )?))
319}
320
321/// Check every expression in the retained source, including its descendants.
322/// Merging branches also merges their source evaluations, so the same
323/// restrictions as for projection wrappers apply throughout the source.
324fn source_is_safe(source: &LogicalPlan) -> Result<bool> {
325    let mut safe = true;
326    source.apply(|node| {
327        node.apply_expressions(|expr| {
328            if is_repeatable(expr) {
329                Ok(TreeNodeRecursion::Continue)
330            } else {
331                safe = false;
332                Ok(TreeNodeRecursion::Stop)
333            }
334        })
335    })?;
336    Ok(safe)
337}
338
339fn collect_table_sources(source: &LogicalPlan) -> Result<Vec<Arc<dyn TableSource>>> {
340    let mut table_sources = vec![];
341    source.apply(|node| {
342        if let LogicalPlan::TableScan(scan) = node {
343            table_sources.push(Arc::clone(&scan.source));
344        }
345        Ok(TreeNodeRecursion::Continue)
346    })?;
347    Ok(table_sources)
348}
349
350/// Returns `true` when every projection expression in `wrappers` is both
351/// non-volatile and subquery-free.
352///
353/// Volatile expressions (e.g. `random()`) or correlated subqueries
354/// in the SELECT list cannot be safely merged: the original plan evaluates
355/// them once per branch execution, while the rewritten plan evaluates them
356/// once per combined row, which can change the set of output rows.
357fn wrapper_projections_are_safe(wrappers: &[Wrapper]) -> bool {
358    wrappers.iter().all(|w| match w {
359        Wrapper::Projection { expr, .. } => expr.iter().all(is_repeatable),
360        Wrapper::SubqueryAlias { .. } => true,
361    })
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367    use crate::OptimizerContext;
368    use crate::assert_optimized_plan_eq_snapshot;
369    use crate::test::test_table_scan_with_name;
370    use arrow::datatypes::DataType;
371    use datafusion_common::Result;
372    use datafusion_expr::{
373        ColumnarValue, Expr, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature,
374        Volatility, col, lit,
375    };
376
377    macro_rules! assert_optimized_plan_equal {
378        (
379            $plan:expr,
380            @ $expected:literal $(,)?
381        ) => {{
382            let mut options = datafusion_common::config::ConfigOptions::default();
383            options.optimizer.enable_unions_to_filter = true;
384            let optimizer_ctx = OptimizerContext::new_with_config_options(Arc::new(options))
385                .with_max_passes(1);
386            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> =
387                vec![Arc::new(UnionsToFilter::new())];
388            assert_optimized_plan_eq_snapshot!(
389                optimizer_ctx,
390                rules,
391                $plan,
392                @ $expected,
393            )
394        }};
395    }
396
397    #[derive(Debug, PartialEq, Eq, Hash)]
398    struct VolatileTestUdf;
399
400    impl ScalarUDFImpl for VolatileTestUdf {
401        fn name(&self) -> &str {
402            "volatile_test"
403        }
404
405        fn signature(&self) -> &Signature {
406            static SIGNATURE: std::sync::LazyLock<Signature> =
407                std::sync::LazyLock::new(|| Signature::nullary(Volatility::Volatile));
408            &SIGNATURE
409        }
410
411        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
412            Ok(DataType::Float64)
413        }
414
415        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
416            panic!("VolatileTestUdf is not intended for execution")
417        }
418    }
419
420    fn volatile_expr() -> Expr {
421        ScalarUDF::new_from_impl(VolatileTestUdf).call(vec![])
422    }
423
424    fn assert_not_rewritten(plan: LogicalPlan) {
425        let mut options = datafusion_common::config::ConfigOptions::default();
426        options.optimizer.enable_unions_to_filter = true;
427        let optimizer_ctx = OptimizerContext::new_with_config_options(Arc::new(options));
428        let result = UnionsToFilter::new()
429            .rewrite(plan.clone(), &optimizer_ctx)
430            .unwrap();
431        assert!(!result.transformed);
432        assert_eq!(result.data, plan);
433    }
434
435    #[test]
436    fn rewrite_union_distinct_preserves_alias_below_filter() -> Result<()> {
437        let scan = test_table_scan_with_name("t").unwrap();
438        let left_source = LogicalPlanBuilder::from(scan.clone())
439            .alias("x")
440            .unwrap()
441            .build()
442            .unwrap();
443        let right_source = LogicalPlanBuilder::from(scan)
444            .alias("x")
445            .unwrap()
446            .build()
447            .unwrap();
448        let left = LogicalPlanBuilder::from(left_source)
449            .filter(col("x.a").eq(lit(1)))
450            .unwrap()
451            .project(vec![col("x.a")])
452            .unwrap()
453            .build()
454            .unwrap();
455        let right = LogicalPlanBuilder::from(right_source)
456            .filter(col("x.a").eq(lit(2)))
457            .unwrap()
458            .project(vec![col("x.a")])
459            .unwrap()
460            .build()
461            .unwrap();
462        let plan = LogicalPlanBuilder::from(left)
463            .union_distinct(right)
464            .unwrap()
465            .build()
466            .unwrap();
467
468        assert_optimized_plan_equal!(plan, @r"
469        Distinct:
470          Projection: x.a
471            Projection: x.a
472              Filter: x.a = Int32(1) OR x.a = Int32(2)
473                SubqueryAlias: x
474                  TableScan: t
475        ")
476        .unwrap();
477        Ok(())
478    }
479
480    #[test]
481    fn rewrite_union_distinct_matching_computed_projection_below_filter() -> Result<()> {
482        let scan = test_table_scan_with_name("prices").unwrap();
483        let left_source = LogicalPlanBuilder::from(scan.clone())
484            .project(vec![(col("a") + lit(100)).alias("amount")])
485            .unwrap()
486            .alias("prices")
487            .unwrap()
488            .build()
489            .unwrap();
490        let right_source = LogicalPlanBuilder::from(scan)
491            .project(vec![(col("a") + lit(100)).alias("amount")])
492            .unwrap()
493            .alias("prices")
494            .unwrap()
495            .build()
496            .unwrap();
497        let left = LogicalPlanBuilder::from(left_source)
498            .filter(col("amount").gt(lit(0)))
499            .unwrap()
500            .project(vec![col("amount")])
501            .unwrap()
502            .build()
503            .unwrap();
504        let right = LogicalPlanBuilder::from(right_source)
505            .filter(col("amount").gt(lit(1)))
506            .unwrap()
507            .project(vec![col("amount")])
508            .unwrap()
509            .build()
510            .unwrap();
511        let plan = LogicalPlanBuilder::from(left)
512            .union_distinct(right)
513            .unwrap()
514            .build()
515            .unwrap();
516
517        assert_optimized_plan_equal!(plan, @r"
518        Distinct:
519          Projection: prices.amount
520            Projection: prices.amount
521              Filter: prices.amount > Int32(0) OR prices.amount > Int32(1)
522                SubqueryAlias: prices
523                  Projection: prices.a + Int32(100) AS amount
524                    TableScan: prices
525        ")
526        .unwrap();
527        Ok(())
528    }
529
530    #[test]
531    fn keep_union_distinct_with_volatile_source_projection() {
532        for nested in [false, true] {
533            let mut source =
534                LogicalPlanBuilder::from(test_table_scan_with_name("t").unwrap())
535                    .project(vec![(volatile_expr() + lit(1.0_f64)).alias("v"), col("a")])
536                    .unwrap()
537                    .alias("x")
538                    .unwrap();
539            if nested {
540                // The volatile projection is below another Filter, so checking
541                // just the source node's expressions would miss it.
542                source = source.filter(col("x.v").gt(lit(0.5_f64))).unwrap();
543            }
544            let source = source.build().unwrap();
545            let left = LogicalPlanBuilder::from(source.clone())
546                .filter(col("x.a").eq(lit(1)))
547                .unwrap()
548                .build()
549                .unwrap();
550            let right = LogicalPlanBuilder::from(source)
551                .filter(col("x.a").eq(lit(2)))
552                .unwrap()
553                .build()
554                .unwrap();
555            let plan = LogicalPlanBuilder::from(left)
556                .union_distinct(right)
557                .unwrap()
558                .build()
559                .unwrap();
560            assert_not_rewritten(plan);
561        }
562    }
563
564    #[test]
565    fn keep_union_distinct_with_volatile_source_without_filter() {
566        let source = LogicalPlanBuilder::from(test_table_scan_with_name("t").unwrap())
567            .project(vec![volatile_expr().alias("v"), col("a")])
568            .unwrap()
569            // Keep the volatile projection inside the retained source rather
570            // than letting peel_wrappers classify it as an outer wrapper.
571            .distinct()
572            .unwrap()
573            .build()
574            .unwrap();
575        let left = LogicalPlanBuilder::from(source.clone())
576            .project(vec![col("a")])
577            .unwrap()
578            .build()
579            .unwrap();
580        let right = LogicalPlanBuilder::from(source)
581            .filter(col("a").eq(lit(2)))
582            .unwrap()
583            .project(vec![col("a")])
584            .unwrap()
585            .build()
586            .unwrap();
587        let plan = LogicalPlanBuilder::from(left)
588            .union_distinct(right)
589            .unwrap()
590            .build()
591            .unwrap();
592        assert_not_rewritten(plan);
593    }
594
595    #[test]
596    fn keep_union_distinct_with_subquery_in_source() {
597        let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("t2").unwrap())
598            .project(vec![col("b")])
599            .unwrap()
600            .build()
601            .unwrap();
602        let source = LogicalPlanBuilder::from(test_table_scan_with_name("t").unwrap())
603            .project(vec![
604                datafusion_expr::scalar_subquery(Arc::new(subquery)).alias("v"),
605                col("a"),
606            ])
607            .unwrap()
608            .build()
609            .unwrap();
610        let left = LogicalPlanBuilder::from(source.clone())
611            .filter(col("a").eq(lit(1)))
612            .unwrap()
613            .build()
614            .unwrap();
615        let right = LogicalPlanBuilder::from(source)
616            .filter(col("a").eq(lit(2)))
617            .unwrap()
618            .build()
619            .unwrap();
620        let plan = LogicalPlanBuilder::from(left)
621            .union_distinct(right)
622            .unwrap()
623            .build()
624            .unwrap();
625        assert_not_rewritten(plan);
626    }
627
628    #[test]
629    fn rewrite_union_distinct_same_source_filters() -> Result<()> {
630        let scan = test_table_scan_with_name("t")?;
631        let left = LogicalPlanBuilder::from(scan.clone())
632            .filter(col("a").eq(lit(1)))?
633            .build()?;
634        let right = LogicalPlanBuilder::from(scan)
635            .filter(col("a").eq(lit(2)))?
636            .build()?;
637
638        let plan = LogicalPlanBuilder::from(left)
639            .union_distinct(right)?
640            .build()?;
641
642        assert_optimized_plan_equal!(plan, @r"
643        Distinct:
644          Projection: t.a, t.b, t.c
645            Filter: t.a = Int32(1) OR t.a = Int32(2)
646              TableScan: t
647        ")?;
648        Ok(())
649    }
650
651    #[test]
652    fn keep_union_distinct_same_metadata_different_root_sources() -> Result<()> {
653        let left_scan_plan = test_table_scan_with_name("t")?;
654        let right_scan_plan = test_table_scan_with_name("t")?;
655
656        // TableScan equality compares metadata but deliberately ignores its provider.
657        assert_eq!(left_scan_plan, right_scan_plan);
658        let (LogicalPlan::TableScan(left_scan), LogicalPlan::TableScan(right_scan)) =
659            (&left_scan_plan, &right_scan_plan)
660        else {
661            panic!("test helper must return TableScan plans");
662        };
663        assert!(!Arc::ptr_eq(&left_scan.source, &right_scan.source));
664
665        let left = LogicalPlanBuilder::from(left_scan_plan)
666            .filter(col("a").eq(lit(1)))?
667            .build()?;
668        let right = LogicalPlanBuilder::from(right_scan_plan)
669            .filter(col("a").eq(lit(2)))?
670            .build()?;
671        let plan = LogicalPlanBuilder::from(left)
672            .union_distinct(right)?
673            .build()?;
674
675        assert_not_rewritten(plan);
676        Ok(())
677    }
678
679    #[test]
680    fn keep_union_distinct_same_metadata_different_nested_sources() {
681        let left_scan_plan = test_table_scan_with_name("t").unwrap();
682        let right_scan_plan = test_table_scan_with_name("t").unwrap();
683        assert_eq!(left_scan_plan, right_scan_plan);
684        let left_sources = collect_table_sources(&left_scan_plan).unwrap();
685        let right_sources = collect_table_sources(&right_scan_plan).unwrap();
686        assert_eq!(left_sources.len(), 1);
687        assert_eq!(right_sources.len(), 1);
688        assert!(!Arc::ptr_eq(&left_sources[0], &right_sources[0]));
689
690        // Verify collection through the Projection/SubqueryAlias source shape
691        // retained below a branch Filter.
692        let left_source = LogicalPlanBuilder::from(left_scan_plan)
693            .project(vec![col("a")])
694            .unwrap()
695            .alias("x")
696            .unwrap()
697            .build()
698            .unwrap();
699        let right_source = LogicalPlanBuilder::from(right_scan_plan)
700            .project(vec![col("a")])
701            .unwrap()
702            .alias("x")
703            .unwrap()
704            .build()
705            .unwrap();
706        assert_eq!(left_source, right_source);
707
708        let left = LogicalPlanBuilder::from(left_source)
709            .filter(col("x.a").eq(lit(1)))
710            .unwrap()
711            .build()
712            .unwrap();
713        let right = LogicalPlanBuilder::from(right_source)
714            .filter(col("x.a").eq(lit(2)))
715            .unwrap()
716            .build()
717            .unwrap();
718        let plan = LogicalPlanBuilder::from(left)
719            .union_distinct(right)
720            .unwrap()
721            .build()
722            .unwrap();
723
724        assert_not_rewritten(plan);
725    }
726
727    #[test]
728    fn keep_union_distinct_different_sources() -> Result<()> {
729        let left = LogicalPlanBuilder::from(test_table_scan_with_name("t1")?)
730            .filter(col("a").eq(lit(1)))?
731            .build()?;
732        let right = LogicalPlanBuilder::from(test_table_scan_with_name("t2")?)
733            .filter(col("a").eq(lit(2)))?
734            .build()?;
735
736        let plan = LogicalPlanBuilder::from(left)
737            .union_distinct(right)?
738            .build()?;
739
740        assert_optimized_plan_equal!(plan, @r"
741        Distinct:
742          Union
743            Filter: t1.a = Int32(1)
744              TableScan: t1
745            Filter: t2.a = Int32(2)
746              TableScan: t2
747        ")?;
748        Ok(())
749    }
750
751    #[test]
752    fn keep_union_distinct_with_volatile_predicate() -> Result<()> {
753        let scan = test_table_scan_with_name("t")?;
754        let left = LogicalPlanBuilder::from(scan.clone())
755            .filter(volatile_expr().gt(lit(0.5_f64)))?
756            .build()?;
757        let right = LogicalPlanBuilder::from(scan)
758            .filter(col("a").eq(lit(2)))?
759            .build()?;
760
761        let plan = LogicalPlanBuilder::from(left)
762            .union_distinct(right)?
763            .build()?;
764
765        assert_optimized_plan_equal!(plan, @r"
766        Distinct:
767          Union
768            Filter: volatile_test() > Float64(0.5)
769              TableScan: t
770            Filter: t.a = Int32(2)
771              TableScan: t
772        ")?;
773        Ok(())
774    }
775
776    #[test]
777    fn rewrite_union_distinct_with_matching_projection_prefix() -> Result<()> {
778        let scan = test_table_scan_with_name("emp")?;
779        let left = LogicalPlanBuilder::from(scan.clone())
780            .project(vec![col("a").alias("mgr"), col("b").alias("comm")])?
781            .build()?;
782        let right = LogicalPlanBuilder::from(scan)
783            .filter(col("b").eq(lit(5)))?
784            .project(vec![col("a").alias("mgr"), col("b").alias("comm")])?
785            .build()?;
786
787        let plan = LogicalPlanBuilder::from(left)
788            .union_distinct(right)?
789            .build()?;
790
791        assert_optimized_plan_equal!(plan, @r"
792        Distinct:
793          Projection: emp.a AS mgr, emp.b AS comm
794            Filter: Boolean(true) OR emp.b = Int32(5)
795              TableScan: emp
796        ")?;
797        Ok(())
798    }
799
800    #[test]
801    fn keep_union_distinct_with_computed_projection_below_filter() -> Result<()> {
802        let scan = test_table_scan_with_name("prices")?;
803        let left = LogicalPlanBuilder::from(scan.clone())
804            .project(vec![(col("a") + lit(100)).alias("amount")])?
805            .alias("prices")?
806            .filter(col("amount").gt(lit(0)))?
807            .project(vec![col("amount")])?
808            .build()?;
809        let right = LogicalPlanBuilder::from(scan)
810            .project(vec![(col("a") + lit(200)).alias("amount")])?
811            .alias("prices")?
812            .filter(col("amount").gt(lit(1)))?
813            .project(vec![col("amount")])?
814            .build()?;
815
816        let plan = LogicalPlanBuilder::from(left)
817            .union_distinct(right)?
818            .build()?;
819
820        assert_optimized_plan_equal!(plan, @r"
821        Distinct:
822          Union
823            Projection: prices.amount
824              Filter: prices.amount > Int32(0)
825                SubqueryAlias: prices
826                  Projection: prices.a + Int32(100) AS amount
827                    TableScan: prices
828            Projection: prices.amount
829              Filter: prices.amount > Int32(1)
830                SubqueryAlias: prices
831                  Projection: prices.a + Int32(200) AS amount
832                    TableScan: prices
833        ")?;
834        Ok(())
835    }
836
837    /// A volatile expression in the **projection** (SELECT list) must block the
838    /// rewrite.  Each original branch evaluates it independently; merging them
839    /// would evaluate it once per combined row, changing the row set.
840    #[test]
841    fn keep_union_distinct_with_volatile_projection() -> Result<()> {
842        // Both branches project volatile_test() AS v over the same source.
843        let scan = test_table_scan_with_name("t")?;
844        let left = LogicalPlanBuilder::from(scan.clone())
845            .filter(col("a").eq(lit(1)))?
846            .project(vec![volatile_expr().alias("v"), col("a")])?
847            .build()?;
848        let right = LogicalPlanBuilder::from(scan)
849            .filter(col("a").eq(lit(2)))?
850            .project(vec![volatile_expr().alias("v"), col("a")])?
851            .build()?;
852
853        let plan = LogicalPlanBuilder::from(left)
854            .union_distinct(right)?
855            .build()?;
856
857        assert_optimized_plan_equal!(plan, @r"
858        Distinct:
859          Union
860            Projection: volatile_test() AS v, t.a
861              Filter: t.a = Int32(1)
862                TableScan: t
863            Projection: volatile_test() AS v, t.a
864              Filter: t.a = Int32(2)
865                TableScan: t
866        ")?;
867        Ok(())
868    }
869
870    /// A scalar subquery in the **projection** must also block the rewrite.
871    #[test]
872    fn keep_union_distinct_with_subquery_in_projection() -> Result<()> {
873        use datafusion_expr::scalar_subquery;
874
875        // Build a simple scalar subquery: (SELECT t2.b FROM t2 WHERE t2.a = t.a)
876        let t2 = test_table_scan_with_name("t2")?;
877        let subquery_plan = Arc::new(
878            LogicalPlanBuilder::from(t2)
879                .filter(col("t2.a").eq(col("t.a")))?
880                .project(vec![col("t2.b")])?
881                .build()?,
882        );
883        let sq = scalar_subquery(subquery_plan);
884
885        let scan = test_table_scan_with_name("t")?;
886        let left = LogicalPlanBuilder::from(scan.clone())
887            .filter(col("a").eq(lit(1)))?
888            .project(vec![sq.clone().alias("sub"), col("a")])?
889            .build()?;
890        let right = LogicalPlanBuilder::from(scan)
891            .filter(col("a").eq(lit(2)))?
892            .project(vec![sq.alias("sub"), col("a")])?
893            .build()?;
894
895        let plan = LogicalPlanBuilder::from(left)
896            .union_distinct(right)?
897            .build()?;
898
899        // Plan should be left untouched because the projection contains a subquery.
900        let optimized = {
901            let mut options = datafusion_common::config::ConfigOptions::default();
902            options.optimizer.enable_unions_to_filter = true;
903            let optimizer_ctx =
904                OptimizerContext::new_with_config_options(Arc::new(options))
905                    .with_max_passes(1);
906            let rules: Vec<Arc<dyn OptimizerRule + Send + Sync>> =
907                vec![Arc::new(UnionsToFilter::new())];
908            crate::Optimizer::with_rules(rules).optimize(
909                plan.clone(),
910                &optimizer_ctx,
911                |_, _| {},
912            )?
913        };
914        // The Distinct(Union(...)) structure must be preserved.
915        assert!(
916            matches!(
917                &optimized,
918                LogicalPlan::Distinct(Distinct::All(inner))
919                if matches!(inner.as_ref(), LogicalPlan::Union(_))
920            ),
921            "expected Distinct(Union(...)) to be preserved, got:\n{optimized:?}"
922        );
923        Ok(())
924    }
925
926    /// A UNION where both branches have a LIMIT must **not** be rewritten.
927    /// Each branch independently restricts the row-set; collapsing them into a
928    /// single branch would lose the per-branch LIMIT semantics.
929    #[test]
930    fn keep_union_distinct_with_limit_branches() -> Result<()> {
931        let scan = test_table_scan_with_name("emp")?;
932        let left = LogicalPlanBuilder::from(scan.clone())
933            .project(vec![col("a").alias("mgr"), col("b").alias("comm")])?
934            .limit(0, Some(2))?
935            .build()?;
936        let right = LogicalPlanBuilder::from(scan)
937            .project(vec![col("a").alias("mgr"), col("b").alias("comm")])?
938            .limit(0, Some(2))?
939            .build()?;
940
941        let plan = LogicalPlanBuilder::from(left)
942            .union_distinct(right)?
943            .build()?;
944
945        assert_optimized_plan_equal!(plan, @r"
946        Distinct:
947          Union
948            Limit: skip=0, fetch=2
949              Projection: emp.a AS mgr, emp.b AS comm
950                TableScan: emp
951            Limit: skip=0, fetch=2
952              Projection: emp.a AS mgr, emp.b AS comm
953                TableScan: emp
954        ")?;
955        Ok(())
956    }
957
958    /// A UNION where both branches have an ORDER BY (Sort) must **not** be
959    /// rewritten.  ORDER BY inside a UNION subquery does not guarantee ordering
960    /// in the result; merging the branches would silently discard the Sort.
961    #[test]
962    fn keep_union_distinct_with_sort_branches() -> Result<()> {
963        let scan = test_table_scan_with_name("emp")?;
964        let left = LogicalPlanBuilder::from(scan.clone())
965            .project(vec![col("a").alias("mgr"), col("b").alias("comm")])?
966            .sort(vec![col("a").sort(true, true)])?
967            .build()?;
968        let right = LogicalPlanBuilder::from(scan)
969            .project(vec![col("a").alias("mgr"), col("b").alias("comm")])?
970            .sort(vec![col("a").sort(true, true)])?
971            .build()?;
972
973        let plan = LogicalPlanBuilder::from(left)
974            .union_distinct(right)?
975            .build()?;
976
977        assert_optimized_plan_equal!(plan, @r"
978        Distinct:
979          Union
980            Projection: mgr, comm
981              Sort: emp.a ASC NULLS FIRST
982                Projection: emp.a AS mgr, emp.b AS comm, emp.a
983                  TableScan: emp
984            Projection: mgr, comm
985              Sort: emp.a ASC NULLS FIRST
986                Projection: emp.a AS mgr, emp.b AS comm, emp.a
987                  TableScan: emp
988        ")?;
989        Ok(())
990    }
991}