Skip to main content

datafusion_optimizer/
eliminate_join.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//! [`EliminateJoin`] rewrites joins to simpler forms to make them cheaper
6//! to evaluate. We implement three distinct rewrites:
7//!
8//! * An inner join can be rewritten to an empty relation if the join condition
9//!   is trivially false.
10//!
11//! * An inner join `L ⋈ R` can be rewritten to a left semi join `L ⋉ R`
12//!   (`LeftSemi`), which keeps the rows of L that have a match in R and outputs
13//!   only L's columns. The rewrite to `L ⋉ R` is valid when both of the
14//!   following are true:
15//!
16//!     1. None of R's columns are referenced above the join.
17//!     2. R does not observably multiply L's rows. This holds when either the
18//!        join's ancestors are duplicate-insensitive (e.g., DISTINCT) and its
19//!        conditions are repeatable, or we can use functional dependencies to
20//!        prove that each L row matches at most one R row (R is provably unique
21//!        on the join keys).
22//!
23//! * A left outer join `L ⟕ R` can be removed entirely, i.e. replaced by `L`,
24//!   under the same two conditions. Unlike an inner join, a left join
25//!   preserves every row of L whether or not it has a match in R, so when R's
26//!   columns are unused and R cannot multiply L's rows the join has no
27//!   observable effect at all. Such joins commonly appear in generated SQL
28//!   and in queries over views that join in lookup tables the query does not
29//!   read. A repeatable join filter does not prevent this rewrite: for a left
30//!   join it only decides whether a left row is matched or null-padded, and
31//!   either way the row is emitted. Symmetrically, a right outer join `L ⟖ R`
32//!   can be replaced by `R` when L's columns are unused and L cannot multiply
33//!   R's rows.
34//!
35//! # Overview
36//!
37//! `rewrite_subtree` walks the plan top-down, threading two pieces of context
38//! down to each join:
39//!
40//! * `live` — which of the join's output columns are referenced above it. It is
41//!   propagated top-down: each node asks its children only for the columns it
42//!   needs from them, so a projection or aggregate asks for just the columns its
43//!   expressions reference, dropping the rest (the narrowing); a join splits the
44//!   set across its two inputs.
45//! * `duplicate_insensitive` — whether emitting each row once instead of many
46//!   times will not change the output. A duplicate-collapsing node (e.g.,
47//!   DISTINCT, an `Aggregate` plan node whose aggregate expressions all ignore
48//!   duplicate input rows, or the existence side of a semi/anti/mark join) sets
49//!   it `true` for its subtree, and it propagates downward until a node that
50//!   makes the row count observable again (a `LIMIT`, a top-N sort, an
51//!   expression that is not repeatable such as `random()` or a subquery, ...)
52//!   clears it. It is therefore fixed by the nearest such node, not by the
53//!   whole ancestor chain: a collapsing node shields its subtree,
54//!   so a duplicate-sensitive node further above does not matter.
55//!
56//! At each join, `rewritten_join_type` combines this context with the side's
57//! functional dependencies to choose `Inner`, `LeftSemi`, or `RightSemi`, or
58//! to eliminate the join entirely in favor of its preserved input. Most
59//! node types just forward the context to their single child via
60//! `rewrite_single_input`; nodes that alter column requirements or
61//! duplicate-sensitivity (projection, aggregate, sort, ...) adjust it first.
62use crate::utils::{
63    for_each_referenced_index, is_duplicate_insensitive_aggregate, is_repeatable,
64};
65use crate::{OptimizerConfig, OptimizerRule};
66use datafusion_common::tree_node::{Transformed, TreeNode};
67use datafusion_common::{
68    DFSchema, Dependency, HashSet, NullEquality, Result, ScalarValue,
69};
70use datafusion_expr::{
71    Expr, JoinType,
72    logical_plan::{
73        Aggregate, Distinct, DistinctOn, EmptyRelation, Filter, Join, Limit, LogicalPlan,
74        Partitioning, Projection, Repartition, Sort, SubqueryAlias,
75    },
76};
77use std::sync::Arc;
78
79/// The columns that are "live" at a plan node, i.e., which of its output
80/// columns are referenced by an ancestor node. Represented as a set of column
81/// indices, relative to the node's schema.
82///
83/// See the module-level docs for how this set is threaded down the plan and
84/// narrowed or split at each node.
85#[derive(Debug, Default, Clone)]
86struct LiveColumns(HashSet<usize>);
87
88impl LiveColumns {
89    fn new() -> Self {
90        Self(HashSet::new())
91    }
92
93    /// Every column of `schema` is live.
94    fn all(schema: &DFSchema) -> Self {
95        Self((0..schema.fields().len()).collect())
96    }
97
98    /// The columns of `schema` referenced by any of `exprs`.
99    fn try_new<'a>(
100        exprs: impl IntoIterator<Item = &'a Expr>,
101        schema: &DFSchema,
102    ) -> Result<Self> {
103        let mut live = Self::new();
104        live.extend_from(exprs, schema)?;
105        Ok(live)
106    }
107
108    /// Inserts the index, within `schema`, of every column referenced by any of
109    /// `exprs`, including columns reached through correlated subquery outer
110    /// references.
111    fn extend_from<'a>(
112        &mut self,
113        exprs: impl IntoIterator<Item = &'a Expr>,
114        schema: &DFSchema,
115    ) -> Result<()> {
116        for expr in exprs {
117            for_each_referenced_index(expr, schema, |idx| {
118                self.0.insert(idx);
119            })?;
120        }
121        Ok(())
122    }
123
124    fn insert(&mut self, idx: usize) {
125        self.0.insert(idx);
126    }
127
128    fn is_empty(&self) -> bool {
129        self.0.is_empty()
130    }
131
132    /// Splits live columns spanning a join's combined output (the left input's
133    /// columns first, then the right input's) into the per-side sets, rebasing
134    /// the right side's indices to start at zero. `left_len` is the number of
135    /// columns contributed by the left input.
136    fn split_at(&self, left_len: usize) -> (Self, Self) {
137        let mut left = Self::new();
138        let mut right = Self::new();
139        for &idx in &self.0 {
140            if idx < left_len {
141                left.insert(idx);
142            } else {
143                right.insert(idx - left_len);
144            }
145        }
146        (left, right)
147    }
148}
149
150/// Rewrites an inner join to a semi join when one input only filters the
151/// other, removes an outer join whose non-preserved side is unused and cannot
152/// multiply the preserved side's rows, and replaces an always-false inner join
153/// with an empty relation.
154#[derive(Default, Debug)]
155pub struct EliminateJoin;
156
157impl EliminateJoin {
158    pub fn new() -> Self {
159        Self {}
160    }
161}
162
163impl OptimizerRule for EliminateJoin {
164    fn name(&self) -> &str {
165        "eliminate_join"
166    }
167
168    fn rewrite(
169        &self,
170        plan: LogicalPlan,
171        _config: &dyn OptimizerConfig,
172    ) -> Result<Transformed<LogicalPlan>> {
173        let live = LiveColumns::all(plan.schema());
174        rewrite_subtree(plan, live, false)
175    }
176}
177
178/// Rewrites `plan` and everything below it, including joins nested inside
179/// subquery expressions.
180///
181/// [`rewrite_node`] handles the node itself and recurses into its plan
182/// children; this wrapper additionally descends into the node's own subquery
183/// expressions.  Each subquery is seeded as a fresh root, since its columns are
184/// independent of the enclosing plan's `live` set.
185fn rewrite_subtree(
186    plan: LogicalPlan,
187    live: LiveColumns,
188    duplicate_insensitive: bool,
189) -> Result<Transformed<LogicalPlan>> {
190    rewrite_node(plan, live, duplicate_insensitive)?.transform_data(|plan| {
191        plan.map_subqueries(|subquery| {
192            let live = LiveColumns::all(subquery.schema());
193            rewrite_subtree(subquery, live, false)
194        })
195    })
196}
197
198fn rewrite_node(
199    plan: LogicalPlan,
200    live: LiveColumns,
201    duplicate_insensitive: bool,
202) -> Result<Transformed<LogicalPlan>> {
203    match plan {
204        // The only arm that rewrites a join; the rest just thread context down to one.
205        LogicalPlan::Join(join) => rewrite_join(join, &live, duplicate_insensitive),
206        LogicalPlan::Projection(Projection {
207            expr,
208            input,
209            schema,
210            ..
211        }) => {
212            // Narrows `live` to the columns the projection's expressions reference.
213            let child_live = LiveColumns::try_new(&expr, input.schema())?;
214            let child_duplicate_insensitive =
215                duplicate_insensitive && expr.iter().all(is_repeatable);
216            rewrite_single_input(
217                input,
218                child_live,
219                child_duplicate_insensitive,
220                |input| {
221                    Ok(LogicalPlan::Projection(Projection::try_new_with_schema(
222                        expr, input, schema,
223                    )?))
224                },
225            )
226        }
227        LogicalPlan::Filter(Filter {
228            predicate, input, ..
229        }) => {
230            // Adds the predicate's columns to `live` (a side used only by the filter stays live).
231            let mut child_live = live;
232            child_live.extend_from([&predicate], input.schema())?;
233            let child_duplicate_insensitive =
234                duplicate_insensitive && is_repeatable(&predicate);
235            rewrite_single_input(
236                input,
237                child_live,
238                child_duplicate_insensitive,
239                |input| Ok(LogicalPlan::Filter(Filter::new(predicate, input))),
240            )
241        }
242        LogicalPlan::Aggregate(Aggregate {
243            input,
244            group_expr,
245            aggr_expr,
246            schema,
247            ..
248        }) => {
249            // Narrows `live` to the grouping and aggregate expressions' columns.
250            let child_live = LiveColumns::try_new(
251                group_expr.iter().chain(&aggr_expr),
252                input.schema(),
253            )?;
254
255            // The input can ignore repeated rows when grouping expressions are
256            // repeatable and every aggregate ignores duplicates, either by
257            // nature (`min`) or because it deduplicates its own input
258            // (`count(DISTINCT x)`). This covers grouping-only and global
259            // aggregates. One sensitive aggregate makes input multiplicity
260            // observable, even beneath an insensitive ancestor.
261            let child_duplicate_insensitive =
262                aggr_expr.iter().all(is_duplicate_insensitive_aggregate)
263                    && group_expr.iter().all(is_repeatable);
264
265            rewrite_single_input(
266                input,
267                child_live,
268                child_duplicate_insensitive,
269                |input| {
270                    Ok(LogicalPlan::Aggregate(Aggregate::try_new_with_schema(
271                        input, group_expr, aggr_expr, schema,
272                    )?))
273                },
274            )
275        }
276        LogicalPlan::Distinct(Distinct::All(input)) => {
277            // `SELECT DISTINCT *` is equivalent to a no-aggregate `GROUP BY`
278            // over every input column, so the input is duplicate-insensitive,
279            // but every column is part of the dedup key.
280            let child_live = LiveColumns::all(input.schema());
281            rewrite_single_input(input, child_live, true, |input| {
282                Ok(LogicalPlan::Distinct(Distinct::All(input)))
283            })
284        }
285        LogicalPlan::Distinct(Distinct::On(DistinctOn {
286            on_expr,
287            select_expr,
288            sort_expr,
289            input,
290            schema,
291        })) => {
292            // `DISTINCT ON (on) select [ORDER BY sort]` is a no-aggregate
293            // `GROUP BY` on the columns it reads, so its input is duplicate-
294            // insensitive; the live columns are exactly those of the
295            // ON/SELECT/ORDER BY expressions.
296            let exprs = || {
297                on_expr
298                    .iter()
299                    .chain(&select_expr)
300                    .chain(sort_expr.iter().flatten().map(|sort| &sort.expr))
301            };
302            let child_live = LiveColumns::try_new(exprs(), input.schema())?;
303            let child_duplicate_insensitive = exprs().all(is_repeatable);
304            rewrite_single_input(
305                input,
306                child_live,
307                child_duplicate_insensitive,
308                |input| {
309                    Ok(LogicalPlan::Distinct(Distinct::On(DistinctOn {
310                        on_expr,
311                        select_expr,
312                        sort_expr,
313                        input,
314                        schema,
315                    })))
316                },
317            )
318        }
319        LogicalPlan::Sort(Sort { expr, input, fetch }) => {
320            // Adds the sort-key columns to `live`.
321            let mut child_live = live;
322            child_live.extend_from(expr.iter().map(|s| &s.expr), input.schema())?;
323
324            // A `fetch` (top-N) makes the row count observable, so duplicate-
325            // insensitivity does not survive past it.
326            let child_duplicate_insensitive = duplicate_insensitive
327                && fetch.is_none()
328                && expr.iter().all(|sort| is_repeatable(&sort.expr));
329            rewrite_single_input(
330                input,
331                child_live,
332                child_duplicate_insensitive,
333                |input| Ok(LogicalPlan::Sort(Sort { expr, input, fetch })),
334            )
335        }
336        LogicalPlan::Limit(Limit { skip, fetch, input }) => {
337            // LIMIT makes the row count observable, so it clears duplicate-insensitivity.
338            rewrite_single_input(input, live, false, |input| {
339                Ok(LogicalPlan::Limit(Limit { skip, fetch, input }))
340            })
341        }
342        LogicalPlan::SubqueryAlias(SubqueryAlias { input, alias, .. }) => {
343            // Re-aliases columns 1:1, so `live` and duplicate-sensitivity pass through unchanged.
344            rewrite_single_input(input, live, duplicate_insensitive, |input| {
345                Ok(LogicalPlan::SubqueryAlias(SubqueryAlias::try_new(
346                    input, alias,
347                )?))
348            })
349        }
350        LogicalPlan::Repartition(Repartition {
351            input,
352            partitioning_scheme,
353        }) => {
354            // Adds any partitioning-key columns to `live`; duplicate-sensitivity is unchanged.
355            let mut child_live = live;
356            match &partitioning_scheme {
357                Partitioning::Hash(exprs, _) | Partitioning::DistributeBy(exprs) => {
358                    child_live.extend_from(exprs, input.schema())?;
359                }
360                Partitioning::Range(range) => {
361                    child_live.extend_from(
362                        range.ordering().iter().map(|sort_expr| &sort_expr.expr),
363                        input.schema(),
364                    )?;
365                }
366                Partitioning::RoundRobinBatch(_) => {}
367            }
368            rewrite_single_input(input, child_live, duplicate_insensitive, |input| {
369                Ok(LogicalPlan::Repartition(Repartition {
370                    input,
371                    partitioning_scheme,
372                }))
373            })
374        }
375        // Conservatively treat any other plan node as a fresh root, since we are
376        // not sure of its semantics with respect to duplicates or live columns.
377        _ => plan.map_children(|child| {
378            let live = LiveColumns::all(child.schema());
379            rewrite_subtree(child, live, false)
380        }),
381    }
382}
383
384/// Recurses into a single-input node's child, threading `child_live` and
385/// `duplicate_insensitive` down, then rebuilds the node from the (possibly
386/// rewritten) child via `rebuild`. The child's `Transformed` flag is preserved,
387/// so the node is reported as changed exactly when its child changed.
388fn rewrite_single_input<F>(
389    input: Arc<LogicalPlan>,
390    child_live: LiveColumns,
391    duplicate_insensitive: bool,
392    rebuild: F,
393) -> Result<Transformed<LogicalPlan>>
394where
395    F: FnOnce(Arc<LogicalPlan>) -> Result<LogicalPlan>,
396{
397    rewrite_subtree(
398        Arc::unwrap_or_clone(input),
399        child_live,
400        duplicate_insensitive,
401    )?
402    .map_data(|input| rebuild(Arc::new(input)))
403}
404
405fn rewrite_join(
406    join: Join,
407    live: &LiveColumns,
408    duplicate_insensitive: bool,
409) -> Result<Transformed<LogicalPlan>> {
410    if join.join_type == JoinType::Inner
411        && join.on.is_empty()
412        && matches!(
413            join.filter.as_ref(),
414            Some(Expr::Literal(ScalarValue::Boolean(Some(false)), _))
415        )
416    {
417        return Ok(Transformed::yes(LogicalPlan::EmptyRelation(
418            EmptyRelation {
419                produce_one_row: false,
420                schema: join.schema,
421            },
422        )));
423    }
424
425    let (visible_left, visible_right) = split_join_output_columns(&join, live);
426
427    // A semi join may stop evaluating conditions after finding a match.
428    // If the conditions are not repeatable, skipping evaluations can change
429    // later matches. Removing duplicate input rows can have the same effect.
430    // Require repeatable conditions for this join and rewrites of its inputs.
431    let repeatable = join
432        .on
433        .iter()
434        .all(|(left, right)| is_repeatable(left) && is_repeatable(right))
435        && join.filter.iter().all(is_repeatable);
436    let duplicate_insensitive = duplicate_insensitive && repeatable;
437
438    let rewritten_join_type = match rewritten_join_type(
439        &join,
440        &visible_left,
441        &visible_right,
442        duplicate_insensitive,
443    ) {
444        JoinRewrite::ReplaceWithLeft => {
445            let left = rewrite_subtree(
446                Arc::unwrap_or_clone(join.left),
447                visible_left,
448                duplicate_insensitive,
449            )?;
450            return Ok(Transformed::yes(left.data));
451        }
452        JoinRewrite::ReplaceWithRight => {
453            let right = rewrite_subtree(
454                Arc::unwrap_or_clone(join.right),
455                visible_right,
456                duplicate_insensitive,
457            )?;
458            return Ok(Transformed::yes(right.data));
459        }
460        JoinRewrite::Join(join_type) => join_type,
461    };
462
463    let (mut left_live, mut right_live) = match rewritten_join_type {
464        JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => {
465            (visible_left, LiveColumns::new())
466        }
467        JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark => {
468            (LiveColumns::new(), visible_right)
469        }
470        _ => (visible_left, visible_right),
471    };
472
473    add_join_condition_columns(&join, &mut left_live, &mut right_live)?;
474
475    let (left_dup_insensitive, right_dup_insensitive) = child_duplicate_insensitivity(
476        rewritten_join_type,
477        duplicate_insensitive,
478        repeatable,
479    );
480
481    let left = rewrite_subtree(
482        Arc::unwrap_or_clone(join.left),
483        left_live,
484        left_dup_insensitive,
485    )?;
486    let right = rewrite_subtree(
487        Arc::unwrap_or_clone(join.right),
488        right_live,
489        right_dup_insensitive,
490    )?;
491
492    let changed =
493        left.transformed || right.transformed || rewritten_join_type != join.join_type;
494    let left = Arc::new(left.data);
495    let right = Arc::new(right.data);
496
497    if changed {
498        // The join type or an input changed, so the output schema may have
499        // narrowed; recompute it via `try_new`.
500        Ok(Transformed::yes(LogicalPlan::Join(
501            Join::try_new(
502                left,
503                right,
504                join.on,
505                join.filter,
506                rewritten_join_type,
507                join.join_constraint,
508                join.null_equality,
509                join.null_aware,
510            )?
511            .with_null_aware_value_keys(join.null_aware_value_keys),
512        )))
513    } else {
514        // Nothing changed; reassemble the join reusing its existing schema rather
515        // than recomputing it.
516        Ok(Transformed::no(LogicalPlan::Join(Join {
517            left,
518            right,
519            on: join.on,
520            filter: join.filter,
521            join_type: join.join_type,
522            join_constraint: join.join_constraint,
523            schema: join.schema,
524            null_equality: join.null_equality,
525            null_aware: join.null_aware,
526            null_aware_value_keys: join.null_aware_value_keys,
527        })))
528    }
529}
530
531/// Returns which join inputs can safely ignore duplicate rows from their own
532/// descendants. For semi/anti/mark joins, duplicates from the existence side do
533/// not change the result even when the parent itself is duplicate-sensitive,
534/// provided the join conditions are `repeatable`: removing duplicate rows
535/// changes how often the conditions are evaluated.
536fn child_duplicate_insensitivity(
537    join_type: JoinType,
538    duplicate_insensitive: bool,
539    repeatable: bool,
540) -> (bool, bool) {
541    match join_type {
542        JoinType::Inner => (duplicate_insensitive, duplicate_insensitive),
543        JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => {
544            (duplicate_insensitive, repeatable)
545        }
546        JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark => {
547            (repeatable, duplicate_insensitive)
548        }
549        JoinType::Left | JoinType::Right | JoinType::Full => (false, false),
550    }
551}
552
553/// The rewrite chosen for a join by [`rewritten_join_type`].
554enum JoinRewrite {
555    /// Keep the join, with this (possibly rewritten) join type.
556    Join(JoinType),
557    /// The join has no observable effect; replace it with its left input.
558    ReplaceWithLeft,
559    /// The join has no observable effect; replace it with its right input.
560    ReplaceWithRight,
561}
562
563/// Chooses a cheaper form for a join: removes an outer join whose non-preserved
564/// side is redundant, or rewrites an inner join to a semi join when the
565/// removed side has no parent-visible columns and either the parent ignores
566/// duplicate output rows or the removed side is unique on the join keys.
567fn rewritten_join_type(
568    join: &Join,
569    visible_left: &LiveColumns,
570    visible_right: &LiveColumns,
571    duplicate_insensitive: bool,
572) -> JoinRewrite {
573    // A side is redundant when nothing above the join references its columns
574    // and it cannot multiply the other side's rows (the ancestors are
575    // duplicate-insensitive, or the side is unique on the join keys).
576    let can_remove_right = visible_right.is_empty()
577        && (duplicate_insensitive
578            || side_unique_on_join(
579                join.right.schema(),
580                join.on.iter().map(|(_, right)| right),
581                join.null_equality,
582            ));
583
584    // A LEFT JOIN preserves every left row, so with a redundant right side the
585    // join has no observable effect and can be replaced by its left input.
586    // A filter only decides whether a row is matched or null-padded. When
587    // relying on duplicate-insensitivity, the caller has already required
588    // repeatable join conditions.
589    if join.join_type == JoinType::Left && can_remove_right {
590        return JoinRewrite::ReplaceWithLeft;
591    }
592    let can_remove_left = visible_left.is_empty()
593        && (duplicate_insensitive
594            || side_unique_on_join(
595                join.left.schema(),
596                join.on.iter().map(|(left, _)| left),
597                join.null_equality,
598            ));
599
600    // Symmetrical rule for RIGHT JOIN removal (same explanation as above for the left-join case)
601    if join.join_type == JoinType::Right && can_remove_left {
602        return JoinRewrite::ReplaceWithRight;
603    }
604
605    if join.join_type != JoinType::Inner || join.on.is_empty() {
606        return JoinRewrite::Join(join.join_type);
607    }
608
609    if can_remove_right {
610        return JoinRewrite::Join(JoinType::LeftSemi);
611    }
612    if can_remove_left {
613        return JoinRewrite::Join(JoinType::RightSemi);
614    }
615
616    JoinRewrite::Join(JoinType::Inner)
617}
618
619fn add_join_condition_columns(
620    join: &Join,
621    left_live: &mut LiveColumns,
622    right_live: &mut LiveColumns,
623) -> Result<()> {
624    left_live.extend_from(join.on.iter().map(|(l, _)| l), join.left.schema())?;
625    right_live.extend_from(join.on.iter().map(|(_, r)| r), join.right.schema())?;
626
627    if let Some(filter) = &join.filter {
628        left_live.extend_from([filter], join.left.schema())?;
629        right_live.extend_from([filter], join.right.schema())?;
630    }
631
632    Ok(())
633}
634
635fn split_join_output_columns(
636    join: &Join,
637    live: &LiveColumns,
638) -> (LiveColumns, LiveColumns) {
639    let left_len = join.left.schema().fields().len();
640    match join.join_type {
641        JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
642            live.split_at(left_len)
643        }
644        // A semi/anti/mark join outputs only the surviving side's columns, with
645        // the same index space, so `live` passes straight through to that side.
646        JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => {
647            (live.clone(), LiveColumns::new())
648        }
649        JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark => {
650            (LiveColumns::new(), live.clone())
651        }
652    }
653}
654
655fn side_unique_on_join<'a>(
656    schema: &DFSchema,
657    join_exprs: impl Iterator<Item = &'a Expr>,
658    null_equality: NullEquality,
659) -> bool {
660    let join_key_indices = join_exprs
661        .filter_map(|expr| match expr {
662            Expr::Alias(alias) => alias.expr.as_ref().try_as_col(),
663            _ => expr.try_as_col(),
664        })
665        .filter_map(|column| schema.maybe_index_of_column(column))
666        .collect::<Vec<usize>>();
667
668    schema.functional_dependencies().iter().any(|dependency| {
669        dependency.mode == Dependency::Single
670            && (!dependency.nullable || null_equality == NullEquality::NullEqualsNothing)
671            && dependency
672                .source_indices
673                .iter()
674                .all(|idx| join_key_indices.contains(idx))
675    })
676}
677
678#[cfg(test)]
679mod tests {
680    use crate::OptimizerContext;
681    use crate::OptimizerRule;
682    use crate::assert_optimized_plan_eq_snapshot;
683    use crate::eliminate_join::EliminateJoin;
684    use crate::test::udfs::{DistinctHandlingTestUDAF, PlacementTestUDF};
685    use arrow::datatypes::{DataType, Field, Schema};
686    use datafusion_common::tree_node::Transformed;
687    use datafusion_common::{
688        Constraint, Constraints, NullEquality, Result, ScalarValue, SplitPoint,
689    };
690    use datafusion_expr::JoinType::Inner;
691    use datafusion_expr::{
692        AggregateUDF, DistinctHandling, Expr, ExprFunctionExt, JoinType, LogicalPlan,
693        Partitioning, RangePartitioning, ScalarUDF, Volatility, col, exists, lit,
694        logical_plan::builder::{
695            LogicalPlanBuilder, table_scan, table_source_with_constraints,
696        },
697        out_ref_col, scalar_subquery,
698    };
699    use datafusion_functions_aggregate::expr_fn::{
700        corr, count, count_distinct, max, min, regr_count, stddev,
701    };
702    use std::sync::Arc;
703
704    macro_rules! assert_optimized_plan_equal {
705        (
706            $plan:expr,
707            @ $expected:literal $(,)?
708        ) => {{
709            let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
710            let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(EliminateJoin::new())];
711            assert_optimized_plan_eq_snapshot!(
712                optimizer_ctx,
713                rules,
714                $plan,
715                @ $expected,
716            )
717        }};
718    }
719
720    fn rewrite(plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
721        EliminateJoin::new().rewrite(plan, &OptimizerContext::new())
722    }
723
724    fn assert_not_rewritten(plan: LogicalPlan) -> Result<()> {
725        assert!(!rewrite(plan)?.transformed);
726        Ok(())
727    }
728
729    /// A scalar UDF with the given volatility.
730    fn test_udf(volatility: Volatility) -> ScalarUDF {
731        ScalarUDF::from(PlacementTestUDF::new().with_volatility(volatility))
732    }
733
734    #[test]
735    fn join_on_false() -> Result<()> {
736        let plan = LogicalPlanBuilder::empty(false)
737            .join_on(
738                LogicalPlanBuilder::empty(false).build()?,
739                Inner,
740                Some(lit(false)),
741            )?
742            .build()?;
743
744        assert_optimized_plan_equal!(plan, @"EmptyRelation: rows=0")
745    }
746
747    #[test]
748    fn inner_to_left_semi_when_removed_side_is_unique() -> Result<()> {
749        let plan = left_join_right_with_constraints(primary_key_on_id())?
750            .project(vec![col("l.x")])?
751            .build()?;
752
753        assert_optimized_plan_equal!(plan, @r"
754        Projection: l.x
755          LeftSemi Join: l.id = r.id
756            TableScan: l
757            TableScan: r
758        ")
759    }
760
761    #[test]
762    fn inner_to_left_semi_when_removed_side_is_unique_with_join_filter() -> Result<()> {
763        let right = scan("r", &test_schema(), primary_key_on_id())?;
764        let plan =
765            LogicalPlanBuilder::from(scan("l", &test_schema(), Constraints::default())?)
766                .join(
767                    right,
768                    Inner,
769                    (vec!["l.id"], vec!["r.id"]),
770                    Some(col("r.y").gt(col("l.x"))),
771                )?
772                .project(vec![col("l.x")])?
773                .build()?;
774
775        assert_optimized_plan_equal!(plan, @r"
776        Projection: l.x
777          LeftSemi Join: l.id = r.id Filter: r.y > l.x
778            TableScan: l
779            TableScan: r
780        ")
781    }
782
783    #[test]
784    fn inner_to_right_semi_when_removed_side_is_unique() -> Result<()> {
785        let plan = left_with_constraints_join_right(primary_key_on_id())?
786            .project(vec![col("r.y")])?
787            .build()?;
788
789        assert_optimized_plan_equal!(plan, @r"
790        Projection: r.y
791          RightSemi Join: l.id = r.id
792            TableScan: l
793            TableScan: r
794        ")
795    }
796
797    #[test]
798    fn inner_to_left_semi_for_duplicate_insensitive_parent() -> Result<()> {
799        let plan = left_join_right()?
800            .aggregate(vec![col("l.x")], Vec::<Expr>::new())?
801            .build()?;
802
803        assert_optimized_plan_equal!(plan, @r"
804        Aggregate: groupBy=[[l.x]], aggr=[[]]
805          LeftSemi Join: l.id = r.id
806            TableScan: l
807            TableScan: r
808        ")
809    }
810
811    #[test]
812    fn count_is_not_duplicate_insensitive() -> Result<()> {
813        // COUNT observes how many rows fall in each group. With a non-unique
814        // right side the join must stay an inner join: collapsing it to a semi
815        // join would drop matching duplicates and undercount `count(l.id)`.
816        let plan = left_join_right()?
817            .aggregate(vec![col("l.x")], vec![count(col("l.id"))])?
818            .build()?;
819
820        assert_optimized_plan_equal!(plan, @r"
821        Aggregate: groupBy=[[l.x]], aggr=[[count(l.id)]]
822          Inner Join: l.id = r.id
823            TableScan: l
824            TableScan: r
825        ")
826    }
827
828    #[test]
829    fn insensitive_aggregates_enable_semi_joins() -> Result<()> {
830        for column in ["l.x", "r.x"] {
831            let aggr_expr = vec![
832                min(col(column)).alias("minimum"),
833                max(col(column)).distinct().build()?,
834            ];
835            // Both global and grouped aggregates ignore duplicate input rows.
836            for group_expr in [vec![], vec![col(column)]] {
837                let plan = left_join_right()?
838                    .aggregate(group_expr, aggr_expr.clone())?
839                    .build()?;
840                let result = rewrite(plan)?;
841                assert!(result.transformed);
842                let LogicalPlan::Aggregate(aggregate) = result.data else {
843                    panic!("expected aggregate");
844                };
845                assert_eq!(aggregate.aggr_expr, aggr_expr);
846                let LogicalPlan::Join(join) = aggregate.input.as_ref() else {
847                    panic!("expected join");
848                };
849                assert_eq!(
850                    join.join_type,
851                    if column == "l.x" {
852                        JoinType::LeftSemi
853                    } else {
854                        JoinType::RightSemi
855                    }
856                );
857            }
858        }
859        Ok(())
860    }
861
862    #[test]
863    fn global_min_removes_unused_outer_join() -> Result<()> {
864        for (join_type, column, table) in
865            [(JoinType::Left, "l.x", "l"), (JoinType::Right, "r.x", "r")]
866        {
867            let left = scan("l", &test_schema(), Constraints::default())?;
868            let right = scan("r", &test_schema(), Constraints::default())?;
869            let plan = LogicalPlanBuilder::from(left)
870                .join(right, join_type, (vec!["l.id"], vec!["r.id"]), None)?
871                .aggregate(Vec::<Expr>::new(), vec![min(col(column))])?
872                .build()?;
873            let optimized = rewrite(plan)?.data;
874            let expected = LogicalPlanBuilder::from(scan(
875                table,
876                &test_schema(),
877                Constraints::default(),
878            )?)
879            .aggregate(Vec::<Expr>::new(), vec![min(col(column))])?
880            .build()?;
881            assert_eq!(optimized, expected);
882        }
883        Ok(())
884    }
885
886    #[test]
887    fn distinct_sensitive_aggregates_enable_semi_joins() -> Result<()> {
888        // A `Sensitive` function called with DISTINCT deduplicates its own
889        // input, so it cannot observe rows repeated by the join.
890        for aggr_expr in [
891            vec![count_distinct(col("l.x"))],
892            vec![count_distinct(col("l.x")), count_distinct(col("l.y"))],
893            vec![
894                min(col("l.x")),
895                count(col("l.x"))
896                    .distinct()
897                    .filter(col("l.y").gt(lit(0)))
898                    .build()?,
899            ],
900        ] {
901            let plan = left_join_right()?
902                .aggregate(vec![col("l.id")], aggr_expr)?
903                .build()?;
904            let result = rewrite(plan)?;
905            assert!(result.transformed);
906            let LogicalPlan::Aggregate(aggregate) = result.data else {
907                panic!("expected aggregate");
908            };
909            let LogicalPlan::Join(join) = aggregate.input.as_ref() else {
910                panic!("expected join");
911            };
912            assert_eq!(join.join_type, JoinType::LeftSemi);
913        }
914        Ok(())
915    }
916
917    #[test]
918    fn duplicate_sensitive_aggregates_block_rewrite() -> Result<()> {
919        // One aggregate that observes repeated rows keeps the join, even
920        // beside aggregates that do not. DISTINCT does not qualify an
921        // `Unsupported` function: its accumulator does not deduplicate, and
922        // may silently compute the non-distinct answer.
923        for sensitive in [
924            count(col("l.x")),
925            stddev(col("l.x")).distinct().build()?,
926            corr(col("l.x"), col("l.y")).distinct().build()?,
927            regr_count(col("l.x"), col("l.y")).distinct().build()?,
928        ] {
929            let plan = left_join_right()?
930                .aggregate(
931                    Vec::<Expr>::new(),
932                    vec![min(col("l.x")), count_distinct(col("l.x")), sensitive],
933                )?
934                .build()?;
935            assert_not_rewritten(plan)?;
936        }
937        Ok(())
938    }
939
940    #[test]
941    fn sensitive_aggregate_blocks_insensitive_ancestor() -> Result<()> {
942        let plan = left_join_right()?
943            .aggregate(vec![col("l.x")], vec![count(col("l.id")).alias("n")])?
944            .aggregate(Vec::<Expr>::new(), vec![min(col("n"))])?
945            .build()?;
946        assert_not_rewritten(plan)?;
947        Ok(())
948    }
949
950    #[test]
951    fn subquery_aggregate_argument_blocks_rewrite() -> Result<()> {
952        // Expr's usual volatility check does not descend into a subquery plan.
953        let volatile = test_udf(Volatility::Volatile).call(vec![lit(1)]);
954        let subquery = LogicalPlanBuilder::empty(true)
955            .project(vec![volatile])?
956            .build()?;
957        let plan = left_join_right()?
958            .aggregate(
959                vec![col("l.x")],
960                vec![min(scalar_subquery(Arc::new(subquery)))],
961            )?
962            .build()?;
963        assert_not_rewritten(plan)?;
964        Ok(())
965    }
966
967    #[test]
968    fn aggregate_filter_and_ordering_keep_columns_live() -> Result<()> {
969        for aggr in [
970            min(col("l.x")).filter(col("r.y").gt(lit(0))).build()?,
971            min(col("l.x"))
972                .order_by(vec![col("r.y").sort(true, false)])
973                .build()?,
974        ] {
975            let plan = left_join_right()?
976                .aggregate(Vec::<Expr>::new(), vec![aggr])?
977                .build()?;
978            assert_not_rewritten(plan)?;
979        }
980
981        let plan = left_join_right()?
982            .aggregate(
983                Vec::<Expr>::new(),
984                vec![min(col("l.x")).filter(col("l.y").gt(lit(0))).build()?],
985            )?
986            .build()?;
987        assert_optimized_plan_equal!(plan, @r"
988        Aggregate: groupBy=[[]], aggr=[[min(l.x) FILTER (WHERE l.y > Int32(0))]]
989          LeftSemi Join: l.id = r.id
990            TableScan: l
991            TableScan: r
992        ")
993    }
994
995    #[test]
996    fn volatile_aggregate_expressions_block_rewrite() -> Result<()> {
997        // `Stable` is the control: the same plan with a repeatable expression
998        // is rewritten.
999        for volatility in [Volatility::Stable, Volatility::Volatile] {
1000            let expr = test_udf(volatility).call(vec![col("l.x")]);
1001            for (group_expr, aggr) in [
1002                (vec![], min(expr.clone())),
1003                (vec![expr.clone()], min(col("l.x"))),
1004                (
1005                    vec![],
1006                    min(col("l.x"))
1007                        .filter(expr.clone().gt(lit(0_u32)))
1008                        .build()?,
1009                ),
1010                (
1011                    vec![],
1012                    min(col("l.x"))
1013                        .order_by(vec![expr.clone().sort(true, false)])
1014                        .build()?,
1015                ),
1016            ] {
1017                let plan = left_join_right()?
1018                    .aggregate(group_expr, vec![aggr])?
1019                    .build()?;
1020                let result = rewrite(plan.clone())?;
1021                assert_eq!(
1022                    result.transformed,
1023                    volatility != Volatility::Volatile,
1024                    "{volatility:?}: {}",
1025                    plan.display_indent(),
1026                );
1027            }
1028        }
1029        Ok(())
1030    }
1031
1032    #[test]
1033    fn volatile_intervening_expressions_block_rewrite() -> Result<()> {
1034        // `Stable` is the control: the same plan with a repeatable expression
1035        // is rewritten.
1036        for volatility in [Volatility::Stable, Volatility::Volatile] {
1037            let expr = test_udf(volatility).call(vec![col("l.x")]);
1038            for input in [
1039                left_join_right()?.project(vec![col("l.x"), expr.clone().alias("v")])?,
1040                left_join_right()?.filter(expr.clone().gt(lit(0_u32)))?,
1041                left_join_right()?.sort(vec![expr.clone().sort(true, false)])?,
1042            ] {
1043                let plan = input
1044                    .aggregate(Vec::<Expr>::new(), vec![min(col("l.x"))])?
1045                    .build()?;
1046                let result = rewrite(plan.clone())?;
1047                assert_eq!(
1048                    result.transformed,
1049                    volatility != Volatility::Volatile,
1050                    "{volatility:?}: {}",
1051                    plan.display_indent(),
1052                );
1053            }
1054        }
1055        Ok(())
1056    }
1057
1058    #[test]
1059    fn join_conditions_must_be_repeatable() -> Result<()> {
1060        for volatility in [Volatility::Stable, Volatility::Volatile] {
1061            let udf = test_udf(volatility);
1062            for (left_key, right_key, filter) in [
1063                (udf.call(vec![col("l.id")]), col("r.id"), None),
1064                (col("l.id"), udf.call(vec![col("r.id")]), None),
1065                (
1066                    col("l.id"),
1067                    col("r.id"),
1068                    Some(udf.call(vec![col("l.x")]).gt(lit(0_u32))),
1069                ),
1070            ] {
1071                let plan = LogicalPlanBuilder::from(scan(
1072                    "l",
1073                    &test_schema(),
1074                    Constraints::default(),
1075                )?)
1076                .join_with_expr_keys(
1077                    scan("r", &test_schema(), Constraints::default())?,
1078                    Inner,
1079                    (vec![left_key], vec![right_key]),
1080                    filter,
1081                )?
1082                .aggregate(Vec::<Expr>::new(), vec![min(col("l.x"))])?
1083                .build()?;
1084                let result = rewrite(plan.clone())?;
1085                assert_eq!(
1086                    result.transformed,
1087                    volatility != Volatility::Volatile,
1088                    "{volatility:?}: {}",
1089                    plan.display_indent(),
1090                );
1091            }
1092        }
1093        Ok(())
1094    }
1095
1096    #[test]
1097    fn existence_side_rewrites_require_repeatable_join_conditions() -> Result<()> {
1098        // There is no duplicate-insensitive ancestor. Only the semi join's
1099        // existence side can make the nested inner join eligible for rewriting.
1100        for join_type in [JoinType::LeftSemi, JoinType::RightSemi] {
1101            for volatility in [Volatility::Stable, Volatility::Volatile] {
1102                let inner = left_join_right()?.build()?;
1103                let other = scan("s", &test_schema(), Constraints::default())?;
1104                let (left, right, keys) = if join_type == JoinType::LeftSemi {
1105                    (other, inner, (vec!["s.id"], vec!["l.id"]))
1106                } else {
1107                    (inner, other, (vec!["l.id"], vec!["s.id"]))
1108                };
1109                let predicate =
1110                    test_udf(volatility).call(vec![col("l.x")]).gt(lit(0_u32));
1111                let plan = LogicalPlanBuilder::from(left)
1112                    .join(right, join_type, keys, Some(predicate))?
1113                    .build()?;
1114                let result = rewrite(plan)?;
1115                let repeatable = volatility != Volatility::Volatile;
1116                assert_eq!(
1117                    result.transformed, repeatable,
1118                    "{join_type:?}, {volatility:?}"
1119                );
1120                let LogicalPlan::Join(join) = result.data else {
1121                    panic!("expected semi join");
1122                };
1123                assert_eq!(join.join_type, join_type);
1124                let existence_side = if join_type == JoinType::LeftSemi {
1125                    join.right
1126                } else {
1127                    join.left
1128                };
1129                let LogicalPlan::Join(nested) = existence_side.as_ref() else {
1130                    panic!("expected nested join");
1131                };
1132                assert_eq!(
1133                    nested.join_type,
1134                    if repeatable {
1135                        JoinType::LeftSemi
1136                    } else {
1137                        Inner
1138                    },
1139                );
1140            }
1141        }
1142        Ok(())
1143    }
1144
1145    #[test]
1146    fn distinct_only_qualifies_sensitive_udaf() -> Result<()> {
1147        for (distinct_handling, distinct, expect_rewrite) in [
1148            (DistinctHandling::Insensitive, false, true),
1149            (DistinctHandling::Insensitive, true, true),
1150            (DistinctHandling::Sensitive, false, false),
1151            // The accumulator deduplicates its own input.
1152            (DistinctHandling::Sensitive, true, true),
1153            (DistinctHandling::Unsupported, false, false),
1154            // The accumulator does not implement DISTINCT, so the input's
1155            // repeated rows stay observable.
1156            (DistinctHandling::Unsupported, true, false),
1157        ] {
1158            let udf = AggregateUDF::from(DistinctHandlingTestUDAF::new(
1159                "custom_udaf",
1160                distinct_handling,
1161            ));
1162            let mut aggr = udf.call(vec![col("l.x")]);
1163            if distinct {
1164                aggr = aggr.distinct().build()?;
1165            }
1166            let plan = left_join_right()?
1167                .aggregate(Vec::<Expr>::new(), vec![aggr])?
1168                .build()?;
1169            let result = rewrite(plan)?;
1170            assert_eq!(
1171                result.transformed, expect_rewrite,
1172                "{distinct_handling:?}, distinct={distinct}"
1173            );
1174        }
1175        Ok(())
1176    }
1177
1178    #[test]
1179    fn aliased_udaf_uses_declared_handling() -> Result<()> {
1180        for volatility in [
1181            Volatility::Immutable,
1182            Volatility::Stable,
1183            Volatility::Volatile,
1184        ] {
1185            let udf = AggregateUDF::from(
1186                DistinctHandlingTestUDAF::new(
1187                    "custom_udaf",
1188                    DistinctHandling::Insensitive,
1189                )
1190                .with_volatility(volatility),
1191            )
1192            .with_aliases(["custom_alias"]);
1193            let plan = left_join_right()?
1194                .aggregate(
1195                    Vec::<Expr>::new(),
1196                    vec![udf.call(vec![col("l.x")]).alias("result")],
1197                )?
1198                .build()?;
1199            let result = rewrite(plan)?;
1200            assert_eq!(result.transformed, volatility != Volatility::Volatile);
1201        }
1202        Ok(())
1203    }
1204
1205    #[test]
1206    fn duplicate_insensitive_context_propagates_through_join_tree() -> Result<()> {
1207        let left = scan("l", &test_schema(), Constraints::default())?;
1208        let middle = scan("m", &test_schema(), Constraints::default())?;
1209        let right = scan("r", &test_schema(), Constraints::default())?;
1210
1211        let left_join_middle = LogicalPlanBuilder::from(left)
1212            .join(middle, Inner, (vec!["l.id"], vec!["m.id"]), None)?
1213            .build()?;
1214
1215        let plan = LogicalPlanBuilder::from(left_join_middle)
1216            .join(right, Inner, (vec!["l.id"], vec!["r.id"]), None)?
1217            .aggregate(vec![col("l.x")], Vec::<Expr>::new())?
1218            .build()?;
1219
1220        assert_optimized_plan_equal!(plan, @r"
1221        Aggregate: groupBy=[[l.x]], aggr=[[]]
1222          LeftSemi Join: l.id = r.id
1223            LeftSemi Join: l.id = m.id
1224              TableScan: l
1225              TableScan: m
1226            TableScan: r
1227        ")
1228    }
1229
1230    #[test]
1231    fn projection_does_not_rewrite_without_uniqueness() -> Result<()> {
1232        let plan = left_join_right()?.project(vec![col("l.x")])?.build()?;
1233
1234        assert_optimized_plan_equal!(plan, @r"
1235        Projection: l.x
1236          Inner Join: l.id = r.id
1237            TableScan: l
1238            TableScan: r
1239        ")
1240    }
1241
1242    #[test]
1243    fn required_filter_column_prevents_duplicate_insensitive_rewrite() -> Result<()> {
1244        let plan = left_join_right()?
1245            .filter(col("r.y").gt(lit(10_i32)))?
1246            .aggregate(vec![col("l.x")], Vec::<Expr>::new())?
1247            .build()?;
1248
1249        assert_optimized_plan_equal!(plan, @r"
1250        Aggregate: groupBy=[[l.x]], aggr=[[]]
1251          Filter: r.y > Int32(10)
1252            Inner Join: l.id = r.id
1253              TableScan: l
1254              TableScan: r
1255        ")
1256    }
1257
1258    #[test]
1259    fn distinct_star_keeps_unreferenced_side() -> Result<()> {
1260        // `SELECT DISTINCT *` deduplicates on every join-output column, including
1261        // the right side's. With a non-unique right side the inner join can
1262        // multiply left rows into distinct `(l, r)` combinations, so the join
1263        // must not be rewritten to a semi join (which would drop the right
1264        // columns from the DISTINCT key and undercount the result). This holds
1265        // even when the right side is unique on the join keys: its columns are
1266        // part of the DISTINCT key regardless.
1267        let plan = left_join_right()?
1268            .distinct()?
1269            .project(vec![col("l.x")])?
1270            .build()?;
1271
1272        assert_optimized_plan_equal!(plan, @r"
1273        Projection: l.x
1274          Distinct:
1275            Inner Join: l.id = r.id
1276              TableScan: l
1277              TableScan: r
1278        ")
1279    }
1280
1281    #[test]
1282    fn distinct_drops_unreferenced_side_when_projected() -> Result<()> {
1283        // `SELECT DISTINCT l.x` projects the right side away below the DISTINCT,
1284        // leaving it outside the dedup key. Like a no-aggregate `GROUP BY l.x`,
1285        // the DISTINCT makes the input duplicate-insensitive, so the inner join
1286        // collapses to a semi join even though the right side is not unique.
1287        let plan = left_join_right()?
1288            .project(vec![col("l.x")])?
1289            .distinct()?
1290            .build()?;
1291
1292        assert_optimized_plan_equal!(plan, @r"
1293        Distinct:
1294          Projection: l.x
1295            LeftSemi Join: l.id = r.id
1296              TableScan: l
1297              TableScan: r
1298        ")
1299    }
1300
1301    #[test]
1302    fn correlated_subquery_outer_ref_prevents_rewrite() -> Result<()> {
1303        // The right side is unique, so the subquery's repeatability barrier
1304        // alone cannot prevent a semi-join rewrite. Tracking the correlated
1305        // `r.y` reference must keep the right side live and the join inner.
1306        let subquery =
1307            LogicalPlanBuilder::from(scan("s", &test_schema(), Constraints::default())?)
1308                .filter(col("s.id").eq(out_ref_col(DataType::Int32, "r.y")))?
1309                .project(vec![lit(1)])?
1310                .build()?;
1311
1312        let plan = left_join_right_with_constraints(primary_key_on_id())?
1313            .filter(exists(Arc::new(subquery)))?
1314            .aggregate(vec![col("l.x")], Vec::<Expr>::new())?
1315            .build()?;
1316
1317        assert_optimized_plan_equal!(plan, @r"
1318        Aggregate: groupBy=[[l.x]], aggr=[[]]
1319          Filter: EXISTS (<subquery>)
1320            Subquery:
1321              Projection: Int32(1)
1322                Filter: s.id = outer_ref(r.y)
1323                  TableScan: s
1324            Inner Join: l.id = r.id
1325              TableScan: l
1326              TableScan: r
1327        ")
1328    }
1329
1330    #[test]
1331    fn inner_to_semi_inside_uncorrelated_subquery() -> Result<()> {
1332        // A join nested inside a (not-yet-decorrelated) subquery is still
1333        // rewritten, because `rewrite_subtree` descends into subquery plans
1334        // itself via `map_subqueries`. Here the subquery's projection keeps
1335        // only `l.x` and the removed side `r` is unique (PK), so the inner join
1336        // collapses to a semi join.
1337        let subquery = left_join_right_with_constraints(primary_key_on_id())?
1338            .project(vec![col("l.x")])?
1339            .build()?;
1340
1341        let plan = LogicalPlanBuilder::from(scan(
1342            "outer",
1343            &test_schema(),
1344            Constraints::default(),
1345        )?)
1346        .filter(exists(Arc::new(subquery)))?
1347        .build()?;
1348
1349        assert_optimized_plan_equal!(plan, @r"
1350        Filter: EXISTS (<subquery>)
1351          Subquery:
1352            Projection: l.x
1353              LeftSemi Join: l.id = r.id
1354                TableScan: l
1355                TableScan: r
1356          TableScan: outer
1357        ")
1358    }
1359
1360    #[test]
1361    fn inner_to_semi_inside_correlated_subquery() -> Result<()> {
1362        // `map_subqueries` descends into correlated subqueries too, not just
1363        // uncorrelated ones, so a join inside one is still rewritten. The
1364        // subquery correlates on `outer.id` (via the filter), but that reference
1365        // and the projection touch only `l`; `r` is unique (PK) and unreferenced,
1366        // so the inner join inside the subquery collapses to a semi join.
1367        let subquery = left_join_right_with_constraints(primary_key_on_id())?
1368            .filter(col("l.x").eq(out_ref_col(DataType::Int32, "outer.id")))?
1369            .project(vec![col("l.x")])?
1370            .build()?;
1371
1372        let plan = LogicalPlanBuilder::from(scan(
1373            "outer",
1374            &test_schema(),
1375            Constraints::default(),
1376        )?)
1377        .filter(exists(Arc::new(subquery)))?
1378        .build()?;
1379
1380        assert_optimized_plan_equal!(plan, @r"
1381        Filter: EXISTS (<subquery>)
1382          Subquery:
1383            Projection: l.x
1384              Filter: l.x = outer_ref(outer.id)
1385                LeftSemi Join: l.id = r.id
1386                  TableScan: l
1387                  TableScan: r
1388          TableScan: outer
1389        ")
1390    }
1391
1392    #[test]
1393    fn nullable_unique_rewrites_under_null_equals_nothing() -> Result<()> {
1394        // A `UNIQUE` (rather than `PRIMARY KEY`) constraint marks the key as
1395        // nullable. Under the default `NullEqualsNothing` join semantics a null
1396        // key matches nothing, so a unique side still yields at most one match
1397        // per left row and the inner join can become a semi join.
1398        let left = scan("l", &test_schema(), Constraints::default())?;
1399        let right = scan("r", &test_schema(), unique_on_x())?;
1400        let plan = LogicalPlanBuilder::from(left)
1401            .join(right, Inner, (vec!["l.x"], vec!["r.x"]), None)?
1402            .project(vec![col("l.id")])?
1403            .build()?;
1404
1405        assert_optimized_plan_equal!(plan, @r"
1406        Projection: l.id
1407          LeftSemi Join: l.x = r.x
1408            TableScan: l
1409            TableScan: r
1410        ")
1411    }
1412
1413    #[test]
1414    fn nullable_unique_does_not_rewrite_under_null_equals_null() -> Result<()> {
1415        // With `NullEqualsNull` semantics two null keys compare equal, so a
1416        // nullable `UNIQUE` key no longer guarantees at most one match per left
1417        // row: several null-keyed right rows could match a null-keyed left row.
1418        // Uniqueness on the join keys is therefore not established and the inner
1419        // join must be preserved.
1420        let left = scan("l", &test_schema(), Constraints::default())?;
1421        let right = scan("r", &test_schema(), unique_on_x())?;
1422        let plan = LogicalPlanBuilder::from(left)
1423            .join_detailed(
1424                right,
1425                Inner,
1426                (vec!["l.x"], vec!["r.x"]),
1427                None,
1428                NullEquality::NullEqualsNull,
1429            )?
1430            .project(vec![col("l.id")])?
1431            .build()?;
1432
1433        assert_optimized_plan_equal!(plan, @r"
1434        Projection: l.id
1435          Inner Join: l.x = r.x
1436            TableScan: l
1437            TableScan: r
1438        ")
1439    }
1440
1441    #[test]
1442    fn composite_unique_rewrites_when_join_covers_all_key_columns() -> Result<()> {
1443        // The removed side is unique on the composite key `(id, x)`. The join
1444        // equates both key columns, so each left row matches at most one right
1445        // row and the inner join can become a semi join.
1446        let left = scan("l", &test_schema(), Constraints::default())?;
1447        let right = scan("r", &test_schema(), composite_primary_key_on_id_x())?;
1448        let plan = LogicalPlanBuilder::from(left)
1449            .join(
1450                right,
1451                Inner,
1452                (vec!["l.id", "l.x"], vec!["r.id", "r.x"]),
1453                None,
1454            )?
1455            .project(vec![col("l.y")])?
1456            .build()?;
1457
1458        assert_optimized_plan_equal!(plan, @r"
1459        Projection: l.y
1460          LeftSemi Join: l.id = r.id, l.x = r.x
1461            TableScan: l
1462            TableScan: r
1463        ")
1464    }
1465
1466    #[test]
1467    fn composite_unique_does_not_rewrite_when_join_misses_a_key_column() -> Result<()> {
1468        // The removed side is unique only on the *composite* key `(id, x)`. The
1469        // join equates `id` but not `x`, so a left row may match many right rows
1470        // (those sharing its `id` but differing in `x`). Uniqueness on the join
1471        // keys is not established, so the inner join must be preserved. This
1472        // guards the requirement that the join cover *every* column of the
1473        // unique key, not just some.
1474        let left = scan("l", &test_schema(), Constraints::default())?;
1475        let right = scan("r", &test_schema(), composite_primary_key_on_id_x())?;
1476        let plan = LogicalPlanBuilder::from(left)
1477            .join(right, Inner, (vec!["l.id"], vec!["r.id"]), None)?
1478            .project(vec![col("l.y")])?
1479            .build()?;
1480
1481        assert_optimized_plan_equal!(plan, @r"
1482        Projection: l.y
1483          Inner Join: l.id = r.id
1484            TableScan: l
1485            TableScan: r
1486        ")
1487    }
1488
1489    #[test]
1490    fn top_n_sort_blocks_duplicate_insensitive_rewrite() -> Result<()> {
1491        // A top-N `Sort` (one with a `fetch`) makes the row count observable, so
1492        // the duplicate-insensitivity established by the `GROUP BY` does not survive
1493        // past it. With a non-unique right side the join must stay an inner join: a
1494        // semi join could drop matching duplicates and change which rows fall within
1495        // the top N.
1496        let plan = left_join_right()?
1497            .sort_with_limit(vec![col("l.x").sort(true, false)], Some(5))?
1498            .aggregate(vec![col("l.x")], Vec::<Expr>::new())?
1499            .build()?;
1500
1501        assert_optimized_plan_equal!(plan, @r"
1502        Aggregate: groupBy=[[l.x]], aggr=[[]]
1503          Sort: l.x ASC NULLS LAST, fetch=5
1504            Inner Join: l.id = r.id
1505              TableScan: l
1506              TableScan: r
1507        ")
1508    }
1509
1510    #[test]
1511    fn sort_without_fetch_preserves_duplicate_insensitive_rewrite() -> Result<()> {
1512        // A `Sort` without a `fetch` does not make the row count observable, so it
1513        // forwards the parent's duplicate-insensitivity to the join unchanged
1514        // (sorting before or after duplicate removal is equivalent). The non-unique
1515        // right side is unreferenced, so the inner join collapses to a semi join.
1516        let plan = left_join_right()?
1517            .sort(vec![col("l.x").sort(true, false)])?
1518            .aggregate(vec![col("l.x")], Vec::<Expr>::new())?
1519            .build()?;
1520
1521        assert_optimized_plan_equal!(plan, @r"
1522        Aggregate: groupBy=[[l.x]], aggr=[[]]
1523          Sort: l.x ASC NULLS LAST
1524            LeftSemi Join: l.id = r.id
1525              TableScan: l
1526              TableScan: r
1527        ")
1528    }
1529
1530    #[test]
1531    fn limit_blocks_duplicate_insensitive_rewrite() -> Result<()> {
1532        // `LIMIT` makes the row count observable, clearing the duplicate-
1533        // insensitivity established by the `GROUP BY`. With a non-unique right side
1534        // the join must stay an inner join, since a semi join could drop matching
1535        // duplicates and change which rows the limit returns.
1536        let plan = left_join_right()?
1537            .limit(0, Some(5))?
1538            .aggregate(vec![col("l.x")], Vec::<Expr>::new())?
1539            .build()?;
1540
1541        assert_optimized_plan_equal!(plan, @r"
1542        Aggregate: groupBy=[[l.x]], aggr=[[]]
1543          Limit: skip=0, fetch=5
1544            Inner Join: l.id = r.id
1545              TableScan: l
1546              TableScan: r
1547        ")
1548    }
1549
1550    #[test]
1551    fn repartition_hash_key_keeps_removed_side_live() -> Result<()> {
1552        // The projection keeps only `l.x`, and the right side is unique (PK), so
1553        // absent any other use of `r` the inner join would collapse to a semi join.
1554        // But the `Repartition` hashes on `r.y`, which keeps the right side live, so
1555        // the join must stay an inner join to preserve `r.y` for the partitioning.
1556        let plan = left_join_right_with_constraints(primary_key_on_id())?
1557            .repartition(Partitioning::Hash(vec![col("r.y")], 4))?
1558            .project(vec![col("l.x")])?
1559            .build()?;
1560
1561        assert_optimized_plan_equal!(plan, @r"
1562        Projection: l.x
1563          Repartition: Hash(r.y) partition_count=4
1564            Inner Join: l.id = r.id
1565              TableScan: l
1566              TableScan: r
1567        ")
1568    }
1569
1570    #[test]
1571    fn repartition_range_key_keeps_removed_side_live() -> Result<()> {
1572        // The projection keeps only `l.x`, and the right side is unique (PK), so
1573        // absent any other use of `r` the inner join would collapse to a semi join.
1574        // But the `Repartition` ranges on `r.y`, which keeps the right side live, so
1575        // the join must stay an inner join to preserve `r.y` for the partitioning.
1576        let plan = left_join_right_with_constraints(primary_key_on_id())?
1577            .repartition(Partitioning::Range(RangePartitioning::try_new(
1578                vec![col("r.y").sort(true, true)],
1579                vec![SplitPoint::new(vec![ScalarValue::Int32(Some(10))])],
1580            )?))?
1581            .project(vec![col("l.x")])?
1582            .build()?;
1583
1584        assert_optimized_plan_equal!(plan, @r"
1585        Projection: l.x
1586          Repartition: Range([r.y ASC NULLS FIRST], [(10)], 2)
1587            Inner Join: l.id = r.id
1588              TableScan: l
1589              TableScan: r
1590        ")
1591    }
1592
1593    #[test]
1594    fn distinct_on_enables_semi_join_rewrite() -> Result<()> {
1595        // `DISTINCT ON (l.x)` is a no-aggregate `GROUP BY` on the columns it reads,
1596        // so it makes its input duplicate-insensitive. The non-unique right side is
1597        // unreferenced, so the inner join collapses to a semi join.
1598        let plan = left_join_right()?
1599            .distinct_on(vec![col("l.x")], vec![col("l.x")], None)?
1600            .build()?;
1601
1602        assert_optimized_plan_equal!(plan, @r"
1603        DistinctOn: on_expr=[[l.x]], select_expr=[[l.x]], sort_expr=[[]]
1604          LeftSemi Join: l.id = r.id
1605            TableScan: l
1606            TableScan: r
1607        ")
1608    }
1609
1610    #[test]
1611    fn distinct_on_expressions_must_be_repeatable() -> Result<()> {
1612        for volatility in [Volatility::Stable, Volatility::Volatile] {
1613            let expr = test_udf(volatility).call(vec![col("l.x")]);
1614            for (on_expr, select_expr, sort_expr) in [
1615                (vec![expr.clone()], vec![col("l.x")], None),
1616                (vec![col("l.x")], vec![expr.clone()], None),
1617                (
1618                    vec![col("l.x")],
1619                    vec![col("l.x")],
1620                    Some(vec![col("l.x").sort(true, false), expr.sort(true, false)]),
1621                ),
1622            ] {
1623                let plan = left_join_right()?
1624                    .distinct_on(on_expr, select_expr, sort_expr)?
1625                    .build()?;
1626                let result = rewrite(plan.clone())?;
1627                assert_eq!(
1628                    result.transformed,
1629                    volatility != Volatility::Volatile,
1630                    "{volatility:?}: {}",
1631                    plan.display_indent(),
1632                );
1633            }
1634        }
1635        Ok(())
1636    }
1637
1638    #[test]
1639    fn existing_semi_join_passes_through_unchanged() -> Result<()> {
1640        // A join that is already a semi join is threaded through unchanged: the rule
1641        // only rewrites inner joins. This exercises the context-propagation paths for
1642        // a non-inner join type, whose existence side contributes no live columns.
1643        let left = scan("l", &test_schema(), Constraints::default())?;
1644        let right = scan("r", &test_schema(), Constraints::default())?;
1645        let plan = LogicalPlanBuilder::from(left)
1646            .join(
1647                right,
1648                JoinType::LeftSemi,
1649                (vec!["l.id"], vec!["r.id"]),
1650                None,
1651            )?
1652            .project(vec![col("l.x")])?
1653            .build()?;
1654
1655        assert_optimized_plan_equal!(plan, @r"
1656        Projection: l.x
1657          LeftSemi Join: l.id = r.id
1658            TableScan: l
1659            TableScan: r
1660        ")
1661    }
1662
1663    fn left_join_right() -> Result<LogicalPlanBuilder> {
1664        left_join_right_with_constraints(Constraints::default())
1665    }
1666
1667    fn left_join_right_with_constraints(
1668        right_constraints: Constraints,
1669    ) -> Result<LogicalPlanBuilder> {
1670        let left = scan("l", &test_schema(), Constraints::default())?;
1671        let right = scan("r", &test_schema(), right_constraints)?;
1672
1673        LogicalPlanBuilder::from(left).join(
1674            right,
1675            Inner,
1676            (vec!["l.id"], vec!["r.id"]),
1677            None,
1678        )
1679    }
1680
1681    fn left_with_constraints_join_right(
1682        left_constraints: Constraints,
1683    ) -> Result<LogicalPlanBuilder> {
1684        let left = scan("l", &test_schema(), left_constraints)?;
1685        let right = scan("r", &test_schema(), Constraints::default())?;
1686
1687        LogicalPlanBuilder::from(left).join(
1688            right,
1689            Inner,
1690            (vec!["l.id"], vec!["r.id"]),
1691            None,
1692        )
1693    }
1694
1695    fn scan(
1696        name: &str,
1697        schema: &Schema,
1698        constraints: Constraints,
1699    ) -> Result<LogicalPlan> {
1700        if constraints.is_empty() {
1701            table_scan(Some(name), schema, None)?.build()
1702        } else {
1703            LogicalPlanBuilder::scan(
1704                name,
1705                table_source_with_constraints(schema, constraints),
1706                None,
1707            )?
1708            .build()
1709        }
1710    }
1711
1712    fn test_schema() -> Schema {
1713        Schema::new(vec![
1714            Field::new("id", DataType::Int32, false),
1715            Field::new("x", DataType::Int32, true),
1716            Field::new("y", DataType::Int32, true),
1717        ])
1718    }
1719
1720    fn primary_key_on_id() -> Constraints {
1721        Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])])
1722    }
1723
1724    /// A nullable unique key on column `x` (index 1). `Unique` (unlike
1725    /// `PrimaryKey`) marks the dependency as nullable, which is what gates the
1726    /// rewrite on the join's `null_equality`.
1727    fn unique_on_x() -> Constraints {
1728        Constraints::new_unverified(vec![Constraint::Unique(vec![1])])
1729    }
1730
1731    /// A composite primary key spanning columns `id` and `x` (indices 0 and 1).
1732    fn composite_primary_key_on_id_x() -> Constraints {
1733        Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0, 1])])
1734    }
1735}