Skip to main content

datafusion_optimizer/
decorrelate_predicate_subquery.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//! [`DecorrelatePredicateSubquery`] converts `IN`/`EXISTS` subquery predicates to `SEMI`/`ANTI` joins
6use std::collections::BTreeSet;
7use std::ops::Deref;
8use std::sync::Arc;
9
10use crate::analyzer::type_coercion::TypeCoercionRewriter;
11use crate::decorrelate::{
12    PullUpCorrelatedExpr, UN_MATCHED_ROW_INDICATOR, build_join_filter,
13};
14use crate::extract_equijoin_predicate::split_eq_and_noneq_join_predicate;
15use crate::optimizer::ApplyOrder;
16use crate::{OptimizerConfig, OptimizerRule};
17
18use datafusion_common::alias::AliasGenerator;
19use datafusion_common::tree_node::{
20    Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
21};
22use datafusion_common::{
23    Column, DFSchema, NullEquality, Result, ScalarValue, assert_or_internal_err,
24    internal_datafusion_err, internal_err, not_impl_err, plan_err,
25};
26use datafusion_expr::expr::{Exists, InSubquery, in_subquery_tuple_values};
27use datafusion_expr::expr_rewriter::{
28    create_col_from_scalar_expr, strip_outer_reference,
29};
30use datafusion_expr::logical_plan::{JoinType, Subquery};
31use datafusion_expr::utils::{conjunction, expr_to_columns, split_conjunction_owned};
32use datafusion_expr::{
33    BinaryExpr, Expr, ExprSchemable, Filter, LogicalPlan, LogicalPlanBuilder, Operator,
34    exists, in_subquery, lit, not, not_exists, not_in_subquery, when,
35};
36
37use log::debug;
38
39/// Optimizer rule for rewriting predicate(IN/EXISTS) subquery to left semi/anti joins
40#[derive(Default, Debug)]
41pub struct DecorrelatePredicateSubquery {}
42
43impl DecorrelatePredicateSubquery {
44    #[expect(missing_docs)]
45    pub fn new() -> Self {
46        Self::default()
47    }
48}
49
50impl OptimizerRule for DecorrelatePredicateSubquery {
51    fn rewrite(
52        &self,
53        plan: LogicalPlan,
54        config: &dyn OptimizerConfig,
55    ) -> Result<Transformed<LogicalPlan>> {
56        let plan = plan
57            .map_subqueries(|subquery| {
58                subquery.transform_down(|p| self.rewrite(p, config))
59            })?
60            .data;
61
62        if let LogicalPlan::Projection(projection) = plan {
63            if !projection.expr.iter().any(has_subquery) {
64                return Ok(Transformed::no(LogicalPlan::Projection(projection)));
65            }
66
67            let original_projection = projection.clone();
68            let mut cur_input = Arc::unwrap_or_clone(projection.input);
69            let mut rewritten_exprs = Vec::with_capacity(projection.expr.len());
70            for expr in projection.expr {
71                let original_name = expr.schema_name().to_string();
72                let (new_input, mut rewritten_expr) =
73                    rewrite_inner_subqueries(cur_input, expr, config, true, true)?;
74                if has_subquery(&rewritten_expr) {
75                    return Ok(Transformed::no(LogicalPlan::Projection(
76                        original_projection,
77                    )));
78                }
79                cur_input = new_input;
80
81                if rewritten_expr.schema_name().to_string() != original_name {
82                    rewritten_expr = rewritten_expr.alias(original_name);
83                }
84                rewritten_exprs.push(rewritten_expr);
85            }
86
87            let new_plan = LogicalPlanBuilder::from(cur_input)
88                .project(rewritten_exprs)?
89                .build()?;
90            return Ok(Transformed::yes(new_plan));
91        }
92
93        let LogicalPlan::Filter(filter) = plan else {
94            return Ok(Transformed::no(plan));
95        };
96
97        if !has_subquery(&filter.predicate) {
98            return Ok(Transformed::no(LogicalPlan::Filter(filter)));
99        }
100
101        let (with_subqueries, mut other_exprs): (Vec<_>, Vec<_>) =
102            split_conjunction_owned(filter.predicate)
103                .into_iter()
104                .partition(has_subquery);
105
106        assert_or_internal_err!(
107            !with_subqueries.is_empty(),
108            "can not find expected subqueries in DecorrelatePredicateSubquery"
109        );
110
111        // iterate through all exists clauses in predicate, turning each into a join
112        let mut cur_input = Arc::unwrap_or_clone(filter.input);
113        let original_schema = cur_input.schema().columns();
114        for subquery_expr in with_subqueries {
115            match extract_subquery_info(subquery_expr) {
116                // The subquery expression is at the top level of the filter
117                SubqueryPredicate::Top(subquery) => {
118                    match build_join_top(&subquery, &cur_input, config.alias_generator())?
119                    {
120                        Some(plan) => cur_input = plan,
121                        // The subquery cannot become a semi or anti join. A
122                        // `NOT IN` may still become mark joins that
123                        // materialize its three-valued result, see
124                        // `in_subquery_value_mark_join`. Any other subquery
125                        // expression goes back into the filter as it is.
126                        None => match subquery.expr() {
127                            expr @ Expr::InSubquery(InSubquery {
128                                negated: true, ..
129                            }) => {
130                                let (plan, expr) = rewrite_inner_subqueries(
131                                    cur_input, expr, config, true, true,
132                                )?;
133                                cur_input = plan;
134                                other_exprs.push(expr);
135                            }
136                            expr => other_exprs.push(expr),
137                        },
138                    }
139                }
140                // The subquery expression is embedded within another expression
141                SubqueryPredicate::Embedded(expr) => {
142                    let (plan, expr_without_subqueries) =
143                        rewrite_filter_subqueries(cur_input, expr, config)?;
144                    cur_input = plan;
145                    other_exprs.push(expr_without_subqueries);
146                }
147            }
148        }
149
150        let expr = conjunction(other_exprs);
151        if let Some(expr) = expr {
152            let new_filter = Filter::try_new(expr, Arc::new(cur_input))?;
153            cur_input = LogicalPlan::Filter(new_filter);
154        }
155
156        if cur_input.schema().fields().len() != original_schema.len() {
157            cur_input = LogicalPlanBuilder::from(cur_input)
158                .project(original_schema.into_iter().map(Expr::from))?
159                .build()?;
160        }
161
162        Ok(Transformed::yes(cur_input))
163    }
164
165    fn name(&self) -> &str {
166        "decorrelate_predicate_subquery"
167    }
168
169    fn apply_order(&self) -> Option<ApplyOrder> {
170        Some(ApplyOrder::TopDown)
171    }
172}
173
174/// Rewrites the subqueries of one embedded `Filter` conjunct, deciding for each
175/// occurrence whether its mark join has to be null-aware.
176///
177/// A `Filter` keeps a row only when the predicate is TRUE, and `AND`/`OR` make
178/// TRUE only out of TRUE. A NULL mark therefore acts exactly like a FALSE mark
179/// under them, so a non-negated `IN` reached through nothing but `AND`/`OR`
180/// does not need the more expensive null-aware join. Every other context can
181/// tell NULL from FALSE and gets one.
182///
183/// The decision is taken at the occurrence rather than once for the whole
184/// conjunct, so a sibling's shape cannot change it, and any expression this
185/// function does not name falls through to the null-aware branch.
186fn rewrite_filter_subqueries(
187    outer: LogicalPlan,
188    expr: Expr,
189    config: &dyn OptimizerConfig,
190) -> Result<(LogicalPlan, Expr)> {
191    match expr {
192        Expr::BinaryExpr(BinaryExpr {
193            left,
194            op: op @ (Operator::And | Operator::Or),
195            right,
196        }) => {
197            let (outer, left) = rewrite_filter_subqueries(outer, *left, config)?;
198            let (outer, right) = rewrite_filter_subqueries(outer, *right, config)?;
199            Ok((
200                outer,
201                Expr::BinaryExpr(BinaryExpr::new(Box::new(left), op, Box::new(right))),
202            ))
203        }
204        Expr::InSubquery(in_subquery) => {
205            // A subquery in the `IN` value is compared, not used as a filter
206            // truth value, so its own mark is observable there.
207            let needs_null_aware_mark =
208                in_subquery.negated || has_subquery(&in_subquery.expr);
209            rewrite_inner_subqueries(
210                outer,
211                Expr::InSubquery(in_subquery),
212                config,
213                false,
214                needs_null_aware_mark,
215            )
216        }
217        other => rewrite_inner_subqueries(outer, other, config, false, true),
218    }
219}
220
221/// `needs_null_aware_mark` is `false` only when the caller can prove that a NULL
222/// mark and a FALSE mark give the same answer. See [`rewrite_filter_subqueries`].
223fn rewrite_inner_subqueries(
224    outer: LogicalPlan,
225    expr: Expr,
226    config: &dyn OptimizerConfig,
227    materialize_in_value: bool,
228    needs_null_aware_mark: bool,
229) -> Result<(LogicalPlan, Expr)> {
230    let mut cur_input = outer;
231    let alias = config.alias_generator();
232    let expr_without_subqueries = expr.transform(|e| match e {
233        Expr::Exists(Exists {
234            subquery: Subquery { subquery, .. },
235            negated,
236        }) => match mark_join(
237            &cur_input,
238            &subquery,
239            None,
240            negated,
241            alias,
242            needs_null_aware_mark,
243        )? {
244            Some(MarkJoin {
245                plan,
246                mark: exists_expr,
247                ..
248            }) => {
249                cur_input = plan;
250                Ok(Transformed::yes(exists_expr))
251            }
252            None if negated => Ok(Transformed::no(not_exists(subquery))),
253            None => Ok(Transformed::no(exists(subquery))),
254        },
255        Expr::InSubquery(InSubquery {
256            expr,
257            subquery: Subquery { subquery, .. },
258            negated,
259        }) => {
260            let rewritten = if materialize_in_value {
261                in_subquery_value_mark_join(
262                    &cur_input,
263                    &subquery,
264                    *expr.clone(),
265                    negated,
266                    alias,
267                )?
268            } else {
269                let in_predicate = subquery
270                    .head_output_expr()?
271                    .map_or(plan_err!("single expression required."), |output_expr| {
272                        Ok(Expr::eq(*expr.clone(), output_expr))
273                    })?;
274                mark_join(
275                    &cur_input,
276                    &subquery,
277                    Some(&in_predicate),
278                    negated,
279                    alias,
280                    needs_null_aware_mark,
281                )?
282                .map(|join| (join.plan, join.mark))
283            };
284            match rewritten {
285                Some((plan, exists_expr)) => {
286                    cur_input = plan;
287                    Ok(Transformed::yes(exists_expr))
288                }
289                None if negated => Ok(Transformed::no(not_in_subquery(*expr, subquery))),
290                None => Ok(Transformed::no(in_subquery(*expr, subquery))),
291            }
292        }
293        _ => Ok(Transformed::no(e)),
294    })?;
295    Ok((cur_input, expr_without_subqueries.data))
296}
297
298/// Rewrites an `IN` subquery that gives a value, for example in a SELECT list.
299/// The value follows SQL three-valued logic: TRUE for a match, FALSE for a miss
300/// and NULL (UNKNOWN) when the answer depends on a NULL.
301///
302/// There are two paths:
303///
304/// * One mark join. When the mark column is already exact under three-valued
305///   logic (see [`MarkJoin::three_valued_exact`]), the mark column is the
306///   answer and this single join is the full rewrite. This is the usual case.
307/// * Three mark joins. In the other case the mark column only tells TRUE from
308///   not-TRUE, so the UNKNOWN cases must be materialized: one more join tells
309///   if the subquery gives a NULL, and one more tells if the subquery gives
310///   any row. A `CASE` expression puts the three marks together. The two extra
311///   joins have no join predicate, so use them only when the first path
312///   cannot apply.
313fn in_subquery_value_mark_join(
314    left: &LogicalPlan,
315    subquery: &LogicalPlan,
316    expr: Expr,
317    negated: bool,
318    alias: &Arc<AliasGenerator>,
319) -> Result<Option<(LogicalPlan, Expr)>> {
320    let output_expr = subquery
321        .head_output_expr()?
322        .map_or(plan_err!("single expression required."), Ok)?;
323    let in_predicate = Expr::eq(expr.clone(), output_expr.clone());
324    let Some(MarkJoin {
325        plan: matched_plan,
326        mark: matched,
327        three_valued_exact,
328    }) = mark_join(left, subquery, Some(&in_predicate), false, alias, true)?
329    else {
330        return Ok(None);
331    };
332
333    // The mark column is the full answer when it is exact. Negation does not
334    // change that, because NOT UNKNOWN is UNKNOWN.
335    if three_valued_exact {
336        return Ok(Some((
337            matched_plan,
338            if negated { not(matched) } else { matched },
339        )));
340    }
341
342    // The fallback below compares the `IN` value as a single value, which a
343    // multi-column `(a, b) IN (SELECT x, y ...)` is not. `build_join` rejects
344    // the tuples whose mark cannot be exact, so this is not reached for them.
345    if in_subquery_tuple_values(&expr, subquery)?.is_some() {
346        return internal_err!(
347            "a multi-column IN subquery needs a three-valued exact mark join"
348        );
349    }
350    // SQL IN needs three facts per outer row to distinguish FALSE from UNKNOWN.
351    let null_subquery = LogicalPlanBuilder::from(subquery.clone())
352        .filter(output_expr.is_null())?
353        .build()?;
354    let Some(MarkJoin {
355        plan: null_plan,
356        mark: subquery_has_null,
357        ..
358    }) = mark_join(&matched_plan, &null_subquery, None, false, alias, true)?
359    else {
360        return Ok(None);
361    };
362    let Some(MarkJoin {
363        plan: final_plan,
364        mark: subquery_non_empty,
365        ..
366    }) = mark_join(&null_plan, subquery, None, false, alias, true)?
367    else {
368        return Ok(None);
369    };
370
371    let unknown = subquery_has_null.or(expr.is_null().and(subquery_non_empty));
372    let result = when(matched, lit(true))
373        .when(unknown, lit(ScalarValue::Boolean(None)))
374        .otherwise(lit(false))?;
375    Ok(Some((
376        final_plan,
377        if negated { not(result) } else { result },
378    )))
379}
380
381enum SubqueryPredicate {
382    // The subquery expression is at the top level of the filter and can be fully replaced by a
383    // semi/anti join
384    Top(SubqueryInfo),
385    // The subquery expression is embedded within another expression and is replaced using an
386    // existence join
387    Embedded(Expr),
388}
389
390fn extract_subquery_info(expr: Expr) -> SubqueryPredicate {
391    match expr {
392        Expr::Not(not_expr) => match *not_expr {
393            Expr::InSubquery(InSubquery {
394                expr,
395                subquery,
396                negated,
397            }) => SubqueryPredicate::Top(SubqueryInfo::new_with_in_expr(
398                subquery, *expr, !negated,
399            )),
400            Expr::Exists(Exists { subquery, negated }) => {
401                SubqueryPredicate::Top(SubqueryInfo::new(subquery, !negated))
402            }
403            expr => SubqueryPredicate::Embedded(not(expr)),
404        },
405        Expr::InSubquery(InSubquery {
406            expr,
407            subquery,
408            negated,
409        }) => SubqueryPredicate::Top(SubqueryInfo::new_with_in_expr(
410            subquery, *expr, negated,
411        )),
412        Expr::Exists(Exists { subquery, negated }) => {
413            SubqueryPredicate::Top(SubqueryInfo::new(subquery, negated))
414        }
415        expr => SubqueryPredicate::Embedded(expr),
416    }
417}
418
419fn has_subquery(expr: &Expr) -> bool {
420    expr.exists(|e| match e {
421        Expr::InSubquery(_) | Expr::Exists(_) => Ok(true),
422        _ => Ok(false),
423    })
424    .unwrap()
425}
426
427/// Optimize the subquery to left-anti/left-semi join.
428/// If the subquery is a correlated subquery, we need extract the join predicate from the subquery.
429///
430/// For example, given a query like:
431/// `select t1.a, t1.b from t1 where t1 in (select t2.a from t2 where t1.b = t2.b and t1.c > t2.c)`
432///
433/// The optimized plan will be:
434///
435/// ```text
436/// Projection: t1.a, t1.b
437///   LeftSemi Join:  Filter: t1.a = __correlated_sq_1.a AND t1.b = __correlated_sq_1.b AND t1.c > __correlated_sq_1.c
438///     TableScan: t1
439///     SubqueryAlias: __correlated_sq_1
440///       Projection: t2.a, t2.b, t2.c
441///         TableScan: t2
442/// ```
443///
444/// Given another query like:
445/// `select t1.id from t1 where exists(SELECT t2.id FROM t2 WHERE t1.id = t2.id)`
446///
447/// The optimized plan will be:
448///
449/// ```text
450/// Projection: t1.id
451///   LeftSemi Join:  Filter: t1.id = __correlated_sq_1.id
452///     TableScan: t1
453///     SubqueryAlias: __correlated_sq_1
454///       Projection: t2.id
455///         TableScan: t2
456/// ```
457fn build_join_top(
458    query_info: &SubqueryInfo,
459    left: &LogicalPlan,
460    alias: &Arc<AliasGenerator>,
461) -> Result<Option<LogicalPlan>> {
462    let where_in_expr_opt = &query_info.where_in_expr;
463    let in_predicate_opt = where_in_expr_opt
464        .clone()
465        .map(|where_in_expr| {
466            query_info
467                .query
468                .subquery
469                .head_output_expr()?
470                .map_or(plan_err!("single expression required."), |expr| {
471                    Ok(Expr::eq(where_in_expr, expr))
472                })
473        })
474        .map_or(Ok(None), |v| v.map(Some))?;
475
476    let join_type = match query_info.negated {
477        true => JoinType::LeftAnti,
478        false => JoinType::LeftSemi,
479    };
480    let subquery = query_info.query.subquery.as_ref();
481    let subquery_alias = alias.next("__correlated_sq");
482    Ok(build_join(
483        left,
484        subquery,
485        in_predicate_opt.as_ref(),
486        join_type,
487        &subquery_alias,
488        true,
489    )?
490    .map(|join| join.plan))
491}
492
493/// This is used to handle the case when the subquery is embedded in a more complex boolean
494/// expression like and OR. For example
495///
496/// `select t1.id from t1 where t1.id < 0 OR exists(SELECT t2.id FROM t2 WHERE t1.id = t2.id)`
497///
498/// The optimized plan will be:
499///
500/// ```text
501/// Projection: t1.id
502///   Filter: t1.id < 0 OR __correlated_sq_1.mark
503///     LeftMark Join:  Filter: t1.id = __correlated_sq_1.id
504///       TableScan: t1
505///       SubqueryAlias: __correlated_sq_1
506///         Projection: t2.id
507///           TableScan: t2
508fn mark_join(
509    left: &LogicalPlan,
510    subquery: &LogicalPlan,
511    in_predicate_opt: Option<&Expr>,
512    negated: bool,
513    alias_generator: &Arc<AliasGenerator>,
514    needs_null_aware_mark: bool,
515) -> Result<Option<MarkJoin>> {
516    let alias = alias_generator.next("__correlated_sq");
517
518    let exists_col = Expr::Column(Column::new(Some(alias.clone()), "mark"));
519    let exists_expr = if negated { !exists_col } else { exists_col };
520
521    Ok(build_join(
522        left,
523        subquery,
524        in_predicate_opt,
525        JoinType::LeftMark,
526        &alias,
527        needs_null_aware_mark,
528    )?
529    .map(|join| MarkJoin {
530        plan: join.plan,
531        mark: exists_expr,
532        three_valued_exact: join.mark_is_three_valued_exact,
533    }))
534}
535
536/// A [`JoinType::LeftMark`] join that replaces a subquery predicate.
537struct MarkJoin {
538    /// The outer plan with the subquery joined into it.
539    plan: LogicalPlan,
540    /// Reads the mark column of the join, negated if the caller asked for it.
541    mark: Expr,
542    /// True when the mark column already gives SQL three-valued `IN`
543    /// semantics: TRUE for a match, FALSE for a miss and NULL for UNKNOWN.
544    ///
545    /// A plain mark is exact when neither side of the `IN` predicate can be
546    /// NULL in scope. Otherwise the join must be null-aware, and the `IN`
547    /// equality must be its first key, which is where the null-aware hash join
548    /// reads the `IN` value. That join also applies a residual non-equality
549    /// filter when it decides whether a NULL makes the mark UNKNOWN.
550    ///
551    /// In any other case the caller materializes the UNKNOWN rows with more
552    /// joins, see [`in_subquery_value_mark_join`].
553    three_valued_exact: bool,
554}
555
556/// Are the `IN` equalities, in order, the first equalities of `join_filter`
557/// that the hash join can use as keys? A null-aware hash join reads its first
558/// `V` keys as the `IN` values (one per tuple element of a multi-column
559/// `IN`) and the other keys as the correlation.
560fn values_are_first_keys(
561    in_values: &[InValue],
562    join_filter: &Expr,
563    left_schema: &DFSchema,
564    right_schema: &DFSchema,
565) -> Result<bool> {
566    let (equijoin_keys, _) = split_eq_and_noneq_join_predicate(
567        join_filter.clone(),
568        left_schema,
569        right_schema,
570    )?;
571    Ok(equijoin_keys.len() >= in_values.len()
572        && equijoin_keys
573            .iter()
574            .zip(in_values)
575            .all(|((value, column), in_value)| {
576                value == &in_value.value && column == &in_value.subquery_column
577            }))
578}
579
580/// The two sides of an `IN` predicate, `value IN (SELECT output_expr ..)`, or
581/// of one tuple element of a multi-column `(a, b) IN (SELECT x, y ..)`.
582struct InValue {
583    /// The value from the outer plan, as the join filter refers to it. This is
584    /// a projected column when `value_as_written` is a constant.
585    value: Expr,
586    /// The subquery output, as the join filter refers to it: a column of the
587    /// aliased subquery.
588    subquery_column: Expr,
589    /// The value as the query writes it.
590    value_as_written: Expr,
591    /// The subquery output expression as the query writes it.
592    output_expr: Expr,
593}
594
595impl InValue {
596    /// Can either side be NULL for a row inside the scope of an outer row?
597    /// See [`key_may_be_null_in_scope`]. The correlated filters name the
598    /// expressions as the query writes them, so the test matches on those.
599    ///
600    /// Only then can `IN` be UNKNOWN, so only then does the join need
601    /// null-aware semantics. A correlation key that is NULL just empties the
602    /// scope, which makes `IN` FALSE.
603    fn may_be_null_in_scope(
604        &self,
605        left_schema: &DFSchema,
606        right_schema: &DFSchema,
607        scope_filters: &[Expr],
608    ) -> Result<bool> {
609        Ok(key_may_be_null_in_scope(
610            self.value.nullable(left_schema)?,
611            &self.value_as_written,
612            true,
613            scope_filters,
614        ) || key_may_be_null_in_scope(
615            self.subquery_column.nullable(right_schema)?,
616            &self.output_expr,
617            false,
618            scope_filters,
619        ))
620    }
621}
622
623/// Can this join key be NULL for a row inside the scope of an outer row?
624///
625/// `nullable` is what the schema says about the key. The key is a full
626/// expression, not only a column. An expression can be NULL although none of
627/// its columns is nullable: `NULLIF(id, 1)`, `TRY_CAST(s AS INT)`, a `CASE`
628/// with no `ELSE` branch, or a scalar function that does not declare its
629/// nullability. So the caller asks the key expression itself, against the
630/// schema of its own side.
631///
632/// The subquery can still keep every NULL out of its result. A correlated
633/// conjunct such as `y = x`, `y > x` or `y IS NOT NULL` is never TRUE for a
634/// NULL `y`, so no row with a NULL `y` is in the scope of any outer row, and
635/// an outer row with a NULL `x` has an empty scope. Neither can make `IN`
636/// UNKNOWN, so such a key does not need null-aware semantics. The usual shape
637/// is a correlation that repeats the `IN` predicate, `x IN (SELECT y FROM t
638/// WHERE y = x)`: the pull up drops that conjunct from the join filter, but
639/// it still bounds the subquery result
640/// (<https://github.com/apache/datafusion/issues/25480>).
641///
642/// This is a sufficient test, not an exact one. A conjunct counts only if it
643/// is a comparison or an `IS NOT NULL` on the key expression itself, casts
644/// aside. Any other conjunct is assumed to let a NULL through, which keeps
645/// the join null-aware.
646///
647/// `key_is_outer` tells on which side of the join the key is. The scope
648/// filters keep their outer references, and a side of a conjunct matches an
649/// outer key only if it names outer columns alone. A subquery column can have
650/// the same qualified name as an outer column (`FROM t AS a` inside a query
651/// over `a`), and it must not be read as the outer key.
652fn key_may_be_null_in_scope(
653    nullable: bool,
654    key: &Expr,
655    key_is_outer: bool,
656    scope_filters: &[Expr],
657) -> bool {
658    if !nullable {
659        return false;
660    }
661    let key = strip_casts(key);
662    !scope_filters
663        .iter()
664        .any(|filter| filter_rejects_null(filter, key, key_is_outer))
665}
666
667/// Is `filter` never TRUE when `key` is NULL? See
668/// [`key_may_be_null_in_scope`] for `key_is_outer`.
669fn filter_rejects_null(filter: &Expr, key: &Expr, key_is_outer: bool) -> bool {
670    let is_key = |side: &Expr| {
671        let side = strip_casts(side);
672        if key_is_outer {
673            side.contains_outer()
674                && side.column_refs().is_empty()
675                && &strip_outer_reference(side.clone()) == key
676        } else {
677            !side.contains_outer() && side == key
678        }
679    };
680    match filter {
681        Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
682            matches!(
683                op,
684                Operator::Eq
685                    | Operator::NotEq
686                    | Operator::Lt
687                    | Operator::LtEq
688                    | Operator::Gt
689                    | Operator::GtEq
690            ) && (is_key(left) || is_key(right))
691        }
692        Expr::IsNotNull(expr) => is_key(expr),
693        _ => false,
694    }
695}
696
697/// `CAST(NULL)` is NULL and `CAST(x)` is not NULL for a non-null `x`, so a
698/// conjunct on `x` says the same about `CAST(x)`, and the other way round.
699/// Type coercion adds such casts on one side only. `TRY_CAST` can make a NULL
700/// from a value, so it is not unwrapped.
701fn strip_casts(expr: &Expr) -> &Expr {
702    let mut expr = expr;
703    while let Expr::Cast(cast) = expr {
704        expr = cast.expr.as_ref();
705    }
706    expr
707}
708
709/// Combines the `IN`/`NOT IN` equalities, one per value, with the correlation
710/// predicates, if any.
711///
712/// The equalities stay the leading conjuncts, in order, so that they become
713/// `on[..V]`, the key positions a null-aware hash join reads as the `NOT IN`
714/// value keys (see `HashJoinExec::null_aware`).
715fn in_join_filter(in_values: &[InValue], correlation: Option<Expr>) -> Result<Expr> {
716    conjunction(
717        in_values
718            .iter()
719            .map(|in_value| {
720                Expr::eq(in_value.value.clone(), in_value.subquery_column.clone())
721            })
722            .chain(correlation),
723    )
724    .ok_or_else(|| internal_datafusion_err!("an `IN` predicate has at least one value"))
725}
726
727/// The `i`-th output expression of `subquery`, as the query writes it.
728fn subquery_output_expr(subquery: &LogicalPlan, i: usize) -> Result<Expr> {
729    match subquery {
730        _ if i == 0 => subquery
731            .head_output_expr()?
732            .ok_or_else(|| internal_datafusion_err!("subquery has no output expression")),
733        LogicalPlan::Projection(projection) => Ok(projection.expr[i].clone()),
734        _ => Ok(Expr::Column(Column::from(
735            subquery.schema().qualified_field(i),
736        ))),
737    }
738}
739
740/// Sets [`Join::null_aware_value_keys`](datafusion_expr::Join::null_aware_value_keys)
741/// on a null-aware join built by [`build_join`]. Only a null-aware join reads
742/// the count, so any other join keeps it unset, as [`Join::try_new`] leaves
743/// it, and equal joins compare equal however they were built.
744///
745/// [`Join::try_new`]: datafusion_expr::Join::try_new
746fn with_null_aware_value_keys(
747    plan: LogicalPlan,
748    null_aware_value_keys: usize,
749) -> Result<LogicalPlan> {
750    let LogicalPlan::Join(join) = plan else {
751        return internal_err!("expected a join, got {}", plan.display());
752    };
753    if !join.null_aware {
754        return Ok(LogicalPlan::Join(join));
755    }
756    Ok(LogicalPlan::Join(
757        join.with_null_aware_value_keys(null_aware_value_keys),
758    ))
759}
760
761fn subquery_operands_are_bare_columns(
762    join_filters: &[Expr],
763    subquery_cols: &BTreeSet<Column>,
764) -> bool {
765    join_filters.iter().all(|filter| {
766        let mut bare = true;
767        filter
768            .apply(|e| {
769                let refs = e.column_refs();
770                // `column_refs` skips outer references, which the join filters keep, so check them separately.
771                if !refs.is_empty()
772                    && !e.contains_outer()
773                    && refs.iter().all(|c| subquery_cols.contains(*c))
774                {
775                    bare = matches!(e, Expr::Column(_));
776                    return Ok(if bare {
777                        TreeNodeRecursion::Jump
778                    } else {
779                        TreeNodeRecursion::Stop
780                    });
781                }
782                Ok(TreeNodeRecursion::Continue)
783            })
784            .expect("infallible");
785        bare
786    })
787}
788
789/// The outcome of [`build_join`].
790struct BuiltJoin {
791    /// The outer plan with the subquery joined into it.
792    plan: LogicalPlan,
793    /// See [`MarkJoin::three_valued_exact`]. This is always false unless the
794    /// join is a [`JoinType::LeftMark`] join built for an `IN` predicate.
795    mark_is_three_valued_exact: bool,
796}
797
798fn build_join(
799    left: &LogicalPlan,
800    subquery: &LogicalPlan,
801    in_predicate_opt: Option<&Expr>,
802    join_type: JoinType,
803    alias: &str,
804    needs_null_aware_mark: bool,
805) -> Result<Option<BuiltJoin>> {
806    let exists_sub_query = in_predicate_opt.is_none();
807    let rewrite =
808        |handle_count_bug: bool| -> Result<(LogicalPlan, PullUpCorrelatedExpr)> {
809            let mut pull_up = PullUpCorrelatedExpr::new()
810                .with_in_predicate_opt(in_predicate_opt.cloned())
811                .with_exists_sub_query(exists_sub_query)
812                .with_need_handle_count_bug(handle_count_bug);
813            let new_plan = subquery.clone().rewrite(&mut pull_up).data()?;
814            Ok((new_plan, pull_up))
815        };
816    let (mut new_plan, mut pull_up) = rewrite(exists_sub_query)?;
817
818    let mut count_bug_compensation = pull_up
819        .collected_count_expr_map
820        .get(&new_plan)
821        .filter(|m| !m.is_empty())
822        .cloned();
823    // A HAVING-failure miss looks identical to an absent group once compensated, so bail if the join filter reads the aggregate's own output.
824    let reads_agg_output = count_bug_compensation.as_ref().is_some_and(|expr_map| {
825        pull_up
826            .join_filters
827            .iter()
828            .flat_map(|f| f.column_refs())
829            .any(|c| expr_map.contains_key(&c.name))
830    });
831    let subquery_cols: BTreeSet<Column> = pull_up
832        .correlated_subquery_cols_map
833        .values()
834        .flatten()
835        .cloned()
836        .collect();
837    let keys_are_bare = count_bug_compensation.is_none()
838        || subquery_operands_are_bare_columns(&pull_up.join_filters, &subquery_cols);
839    // Fall back to the uncompensated rewrite whenever compensation can't safely apply, so a HAVING never gets silently dropped.
840    let compensable = pull_up.can_pull_up
841        && !reads_agg_output
842        && keys_are_bare
843        && (count_bug_compensation.is_some() || pull_up.pull_up_having_expr.is_none());
844    if exists_sub_query && !compensable {
845        (new_plan, pull_up) = rewrite(false)?;
846        count_bug_compensation = None;
847    }
848    if !pull_up.can_pull_up {
849        return Ok(None);
850    }
851    // TODO(#24960): stopgap until count-bug compensation covers `IN`/`NOT IN`.
852    // The subquery stays correlated unless an outer row with no match gets the
853    // right answer anyway.
854    if !exists_sub_query && pull_up.pulled_up_scalar_agg {
855        let null_reads_as_false = match join_type {
856            JoinType::LeftSemi => true,
857            JoinType::LeftMark => !needs_null_aware_mark,
858            _ => false,
859        };
860        let count_bug_is_harmless = match rewrite(true) {
861            Ok((plan, pull_up)) => pull_up
862                .collected_count_expr_map
863                .get(&plan)
864                .filter(|m| !m.is_empty())
865                .is_none_or(|empty_input_values| {
866                    null_reads_as_false
867                        && empty_input_values
868                            .get(subquery.schema().field(0).name())
869                            .is_some_and(|value| {
870                                matches!(value, Expr::Literal(v, _) if v.is_null())
871                            })
872                }),
873            // Count-bug handling errors on some shapes it cannot compensate.
874            Err(_) => false,
875        };
876        if !count_bug_is_harmless {
877            return Ok(None);
878        }
879    }
880
881    let sub_query_alias = LogicalPlanBuilder::from(new_plan)
882        .alias(alias.to_string())?
883        .build()?;
884    let join_filter_opt = build_join_filter(
885        pull_up.join_filters,
886        pull_up.correlated_subquery_cols_map.values().flatten(),
887        alias,
888    )?;
889
890    if let Some(expr_map) = count_bug_compensation
891        && !expr_map.is_empty()
892    {
893        return build_join_with_count_bug(
894            left,
895            sub_query_alias,
896            join_filter_opt,
897            join_type,
898            alias,
899            &expr_map,
900            pull_up.pull_up_having_expr.as_ref(),
901        )
902        .map(|plan| {
903            Some(BuiltJoin {
904                plan,
905                mark_is_three_valued_exact: false,
906            })
907        });
908    }
909
910    // The two sides of the `IN` predicate: the value from the outer plan and
911    // the subquery output it is compared with, renamed to the alias. A
912    // multi-column `(a, b) IN (SELECT x, y ...)` has one pair per tuple
913    // element; its `in_predicate` compares the whole tuple with the first
914    // subquery output, so each element is paired with its own output here.
915    // `EXISTS` has none.
916    let in_values = match in_predicate_opt {
917        Some(Expr::BinaryExpr(BinaryExpr {
918            left,
919            op: Operator::Eq,
920            right,
921        })) => {
922            let values = match in_subquery_tuple_values(left, subquery)? {
923                Some(values) => values.into_owned(),
924                None => vec![left.deref().clone()],
925            };
926            values
927                .into_iter()
928                .enumerate()
929                .map(|(i, value)| {
930                    let output_expr = if i == 0 {
931                        right.deref().clone()
932                    } else {
933                        subquery_output_expr(subquery, i)?
934                    };
935                    let right_col =
936                        create_col_from_scalar_expr(&output_expr, alias.to_string())?;
937                    Ok(InValue {
938                        value: value.clone(),
939                        subquery_column: Expr::Column(right_col),
940                        value_as_written: value,
941                        output_expr,
942                    })
943                })
944                .collect::<Result<Vec<_>>>()?
945        }
946        Some(_) => return Ok(None),
947        None => vec![],
948    };
949
950    // True if an `IN` value or the subquery column it is compared with can be
951    // NULL inside the scope of an outer row.
952    let mut value_may_be_null = false;
953    for in_value in &in_values {
954        value_may_be_null |= in_value.may_be_null_in_scope(
955            left.schema(),
956            sub_query_alias.schema(),
957            &pull_up.correlated_filters,
958        )?;
959    }
960
961    // Whether this join needs null-aware (`NOT IN` three-valued) semantics.
962    // Decided once: the constant projection below, the mark branch and the anti
963    // branch all depend on the same answer. `NOT EXISTS` is two-valued and has
964    // no `IN` value, so it never qualifies.
965    //
966    // The left projection below only adds a column for a constant value and
967    // the right projection only drops unreferenced columns, so neither changes
968    // the nullability this looks at.
969    let null_aware = value_may_be_null
970        && match join_type {
971            JoinType::LeftAnti => true,
972            JoinType::LeftMark => needs_null_aware_mark,
973            _ => false,
974        };
975
976    // `<constant> IN/NOT IN (<subquery>)`: the outer value expression holds no
977    // column reference, so `<constant> = __correlated_sq.col` is not a valid
978    // equi-join key (see `find_valid_equijoin_key_pair`) and stays in the join
979    // filter. Two things then go wrong for a null-aware join: the filter is
980    // right-only, so `push_down_filter` moves it into the subquery and drops the
981    // very NULLs that make `NOT IN` UNKNOWN, and a join without equi-join keys
982    // is planned as a nested loop join, which has no null-aware implementation.
983    // A correlated subquery hits a third problem: its correlation predicate is a
984    // valid equi-join key, so it takes `on[0]`, the position the null-aware hash
985    // join reads as the `NOT IN` value key.
986    // Projecting the constant as a column of the outer side turns the predicate
987    // into a real equi-join key, which fixes all three. It only pays for itself
988    // on a join that ends up null-aware.
989    //
990    // Every constant element of a tuple is projected the same way, so that all
991    // value keys lead the equi-join keys in order.
992    let mut projected_left = None;
993    let mut in_values = in_values;
994    if null_aware
995        && in_values
996            .iter()
997            .any(|in_value| in_value.value.column_refs().is_empty())
998    {
999        let left_schema = left.schema();
1000        let mut projections = left_schema
1001            .columns()
1002            .into_iter()
1003            .map(Expr::from)
1004            .collect::<Vec<_>>();
1005        let is_tuple = in_values.len() > 1;
1006        for (i, in_value) in in_values.iter_mut().enumerate() {
1007            if !in_value.value.column_refs().is_empty() {
1008                continue;
1009            }
1010            // The projected column is unqualified, so a left field that already
1011            // has this name — however unlikely — would make the reference
1012            // ambiguous.
1013            let mut value_name = if is_tuple {
1014                format!("{alias}_value_{i}")
1015            } else {
1016                format!("{alias}_value")
1017            };
1018            while left_schema.fields().iter().any(|f| f.name() == &value_name) {
1019                value_name.push('_');
1020            }
1021            let value_col = Column::new_unqualified(value_name);
1022            let constant =
1023                std::mem::replace(&mut in_value.value, Expr::Column(value_col.clone()));
1024            projections.push(constant.alias(value_col.name()));
1025        }
1026        projected_left = Some(
1027            LogicalPlanBuilder::from(left.clone())
1028                .project(projections)?
1029                .build()?,
1030        );
1031    }
1032    let left = projected_left.as_ref().unwrap_or(left);
1033
1034    let join_filter = match (in_values.is_empty(), join_filter_opt) {
1035        (false, correlation_opt) => in_join_filter(&in_values, correlation_opt)?,
1036        (true, Some(correlation)) => correlation,
1037        (true, None) => lit(true),
1038    };
1039
1040    // Only a null-aware join reads the key order.
1041    let value_is_first_key = null_aware
1042        && values_are_first_keys(
1043            &in_values,
1044            &join_filter,
1045            left.schema(),
1046            sub_query_alias.schema(),
1047        )?;
1048
1049    // A multi-column `IN` has no fallback that materializes the UNKNOWN rows
1050    // (see below), so a tuple element that does not become its key, for
1051    // example because its type is not hashable, is rejected instead of being
1052    // read in the wrong key position.
1053    if null_aware && !value_is_first_key && in_values.len() > 1 {
1054        return not_impl_err!(
1055            "Multi-column NOT IN subquery is not supported when a tuple element is not a hashable equi-join key: {join_filter}"
1056        );
1057    }
1058    // The first `V` keys of a null-aware join are its `NOT IN` value keys.
1059    let null_aware_value_keys = in_values.len().max(1);
1060
1061    // A `NOT IN` in a filter builds a `LeftAnti` join. The null-aware hash
1062    // join reads its first key as the `NOT IN` value and the other keys as the
1063    // scope of the outer row (see `HashJoinExec::null_aware`). If the `IN`
1064    // equality did not become that first key, give up here. The caller then
1065    // materializes the UNKNOWN rows with more joins, see
1066    // `in_subquery_value_mark_join`.
1067    if join_type == JoinType::LeftAnti && null_aware && !value_is_first_key {
1068        return Ok(None);
1069    }
1070
1071    if matches!(join_type, JoinType::LeftMark | JoinType::RightMark) {
1072        let right_schema = sub_query_alias.schema();
1073
1074        // Gather all columns needed for the join filter + predicates
1075        let mut needed = std::collections::HashSet::new();
1076        expr_to_columns(&join_filter, &mut needed)?;
1077        if let Some(in_pred) = in_predicate_opt {
1078            expr_to_columns(in_pred, &mut needed)?;
1079        }
1080
1081        // Keep only columns that actually belong to the RIGHT child, and sort by their
1082        // position in the right schema for deterministic order.
1083        let mut right_col_indices: Vec<usize> = needed
1084            .into_iter()
1085            .filter_map(|column| right_schema.index_of_column(&column).ok())
1086            .collect();
1087
1088        right_col_indices.sort_unstable();
1089        right_col_indices.dedup();
1090
1091        let right_proj_exprs: Vec<Expr> = right_col_indices
1092            .into_iter()
1093            .map(|index| Expr::Column(Column::from(right_schema.qualified_field(index))))
1094            .collect();
1095
1096        let right_projected = if !right_proj_exprs.is_empty() {
1097            LogicalPlanBuilder::from(sub_query_alias.clone())
1098                .project(right_proj_exprs)?
1099                .build()?
1100        } else {
1101            // Degenerate case: no right columns referenced by the predicate(s)
1102            sub_query_alias.clone()
1103        };
1104
1105        // For scalar NOT IN mark joins, propagate null-aware semantics into the
1106        // nullable mark column. A non-equality correlation stays behind as a
1107        // join filter, which the hash join also applies when it decides
1108        // whether a NULL makes the mark UNKNOWN.
1109        let mark_is_three_valued_exact = !in_values.is_empty()
1110            && (!value_may_be_null || (null_aware && value_is_first_key));
1111
1112        let new_plan = with_null_aware_value_keys(
1113            LogicalPlanBuilder::from(left.clone())
1114                .join_detailed_with_options(
1115                    right_projected,
1116                    join_type,
1117                    (Vec::<Column>::new(), Vec::<Column>::new()),
1118                    Some(join_filter),
1119                    NullEquality::NullEqualsNothing,
1120                    null_aware,
1121                )?
1122                .build()?,
1123            null_aware_value_keys,
1124        )?;
1125
1126        debug!(
1127            "predicate subquery optimized:\n{}",
1128            new_plan.display_indent()
1129        );
1130
1131        return Ok(Some(BuiltJoin {
1132            plan: new_plan,
1133            mark_is_three_valued_exact,
1134        }));
1135    }
1136
1137    // join our sub query into the main plan
1138    let new_plan = if null_aware {
1139        // Use join_detailed_with_options to set null_aware flag
1140        with_null_aware_value_keys(
1141            LogicalPlanBuilder::from(left.clone())
1142                .join_detailed_with_options(
1143                    sub_query_alias,
1144                    join_type,
1145                    (Vec::<Column>::new(), Vec::<Column>::new()), // No equijoin keys, filter-based join
1146                    Some(join_filter),
1147                    NullEquality::NullEqualsNothing,
1148                    true, // null_aware
1149                )?
1150                .build()?,
1151            null_aware_value_keys,
1152        )?
1153    } else {
1154        LogicalPlanBuilder::from(left.clone())
1155            .join_on(sub_query_alias, join_type, Some(join_filter))?
1156            .build()?
1157    };
1158    debug!(
1159        "predicate subquery optimized:\n{}",
1160        new_plan.display_indent()
1161    );
1162    Ok(Some(BuiltJoin {
1163        plan: new_plan,
1164        mark_is_three_valued_exact: false,
1165    }))
1166}
1167
1168/// Builds the join for a correlated `EXISTS` subquery whose groupless
1169/// aggregate requires count-bug compensation.
1170fn build_join_with_count_bug(
1171    left: &LogicalPlan,
1172    sub_query_alias: LogicalPlan,
1173    join_filter_opt: Option<Expr>,
1174    join_type: JoinType,
1175    alias: &str,
1176    expr_map: &crate::decorrelate::ExprResultMap,
1177    pull_up_having_expr: Option<&Expr>,
1178) -> Result<LogicalPlan> {
1179    let pull_up_having_expr = pull_up_having_expr
1180        .map(|f| {
1181            f.clone()
1182                .transform_up(|e| match e {
1183                    Expr::Column(c) => Ok(Transformed::yes(Expr::Column(Column::new(
1184                        Some(alias),
1185                        c.name,
1186                    )))),
1187                    _ => Ok(Transformed::no(e)),
1188                })
1189                .data()
1190        })
1191        .transpose()?;
1192    let pull_up_having_expr = pull_up_having_expr.as_ref();
1193
1194    let joined = LogicalPlanBuilder::from(left.clone())
1195        .join_on(sub_query_alias, JoinType::Left, join_filter_opt)?
1196        .build()?;
1197
1198    let left_projection: Vec<Expr> = left
1199        .schema()
1200        .columns()
1201        .into_iter()
1202        .map(Expr::from)
1203        .collect();
1204
1205    let indicator_col = Expr::Column(Column::new(Some(alias), UN_MATCHED_ROW_INDICATOR));
1206
1207    let having_arm = pull_up_having_expr.map(|f| f.clone().is_not_true());
1208
1209    let mut expr_rewrite = TypeCoercionRewriter::new(joined.schema());
1210
1211    // The subquery's HAVING clause, evaluated against an unmatched row's
1212    // default aggregate values (e.g. count(*) defaults to 0, sum(x) to
1213    // NULL), is usually `true`, but not once a second filter is combined
1214    // into it, so it cannot be assumed.
1215    let unmatched_having_default = match pull_up_having_expr {
1216        Some(f) => f
1217            .clone()
1218            .transform_up(|e| {
1219                if let Expr::Column(Column { name, .. }) = &e
1220                    && let Some(default_value) = expr_map.get(name)
1221                {
1222                    return Ok(Transformed::yes(default_value.clone()));
1223                }
1224                Ok(Transformed::no(e))
1225            })
1226            .data()
1227            .and_then(|simplified| simplified.rewrite(&mut expr_rewrite).data())?,
1228        None => lit(true),
1229    };
1230
1231    // EXISTS is true by default (the groupless aggregate always
1232    // produces a row), unless one of three cases holds:
1233    // (1) the outer row joined against an inner group whose HAVING
1234    //     predicate failed,
1235    // (2) an unmatched outer row's own default aggregate values fail
1236    //     that same HAVING clause.
1237    let exists_expr = match having_arm {
1238        Some(when_expr) => when(
1239            indicator_col.clone().is_null(),
1240            unmatched_having_default.is_true(),
1241        )
1242        .when(when_expr, lit(false))
1243        .otherwise(lit(true))?
1244        .rewrite(&mut expr_rewrite)
1245        .data()?,
1246        None => lit(true),
1247    };
1248
1249    let new_plan = match join_type {
1250        JoinType::LeftMark | JoinType::RightMark => {
1251            let mut proj_exprs = left_projection;
1252            proj_exprs.push(exists_expr.alias_qualified(Some(alias), "mark"));
1253            LogicalPlanBuilder::from(joined)
1254                .project(proj_exprs)?
1255                .build()?
1256        }
1257        JoinType::LeftAnti => LogicalPlanBuilder::from(joined)
1258            .filter(not(exists_expr))?
1259            .project(left_projection)?
1260            .build()?,
1261        JoinType::LeftSemi => LogicalPlanBuilder::from(joined)
1262            .filter(exists_expr)?
1263            .project(left_projection)?
1264            .build()?,
1265        _ => {
1266            return internal_err!("unsupported join type {join_type:?}");
1267        }
1268    };
1269
1270    debug!(
1271        "predicate subquery (count bug) optimized:\n{}",
1272        new_plan.display_indent()
1273    );
1274
1275    Ok(new_plan)
1276}
1277
1278#[derive(Debug)]
1279struct SubqueryInfo {
1280    query: Subquery,
1281    where_in_expr: Option<Expr>,
1282    negated: bool,
1283}
1284
1285impl SubqueryInfo {
1286    pub fn new(query: Subquery, negated: bool) -> Self {
1287        Self {
1288            query,
1289            where_in_expr: None,
1290            negated,
1291        }
1292    }
1293
1294    pub fn new_with_in_expr(query: Subquery, expr: Expr, negated: bool) -> Self {
1295        Self {
1296            query,
1297            where_in_expr: Some(expr),
1298            negated,
1299        }
1300    }
1301
1302    pub fn expr(self) -> Expr {
1303        match self.where_in_expr {
1304            Some(expr) => match self.negated {
1305                true => not_in_subquery(expr, self.query.subquery),
1306                false => in_subquery(expr, self.query.subquery),
1307            },
1308            None => match self.negated {
1309                true => not_exists(self.query.subquery),
1310                false => exists(self.query.subquery),
1311            },
1312        }
1313    }
1314}
1315
1316#[cfg(test)]
1317mod tests {
1318    use std::ops::Add;
1319
1320    use super::*;
1321    use crate::test::*;
1322
1323    use crate::assert_optimized_plan_eq_display_indent_snapshot;
1324    use arrow::datatypes::{DataType, Field, Schema};
1325    use datafusion_expr::builder::table_source;
1326    use datafusion_expr::{
1327        TableScanBuilder, and, binary_expr, col, cube, grouping_set, out_ref_col, rollup,
1328        table_scan,
1329    };
1330    use datafusion_functions_aggregate::count::count_udaf;
1331
1332    macro_rules! assert_optimized_plan_equal {
1333        (
1334            $plan:expr,
1335            @ $expected:literal $(,)?
1336        ) => {{
1337            let rule: Arc<dyn crate::OptimizerRule + Send + Sync> = Arc::new(DecorrelatePredicateSubquery::new());
1338            assert_optimized_plan_eq_display_indent_snapshot!(
1339                rule,
1340                $plan,
1341                @ $expected,
1342            )
1343        }};
1344    }
1345
1346    fn test_subquery_with_name(name: &str) -> Result<Arc<LogicalPlan>> {
1347        let table_scan = test_table_scan_with_name(name)?;
1348        Ok(Arc::new(
1349            LogicalPlanBuilder::from(table_scan)
1350                .project(vec![col("c")])?
1351                .build()?,
1352        ))
1353    }
1354
1355    fn nullable_scalar_mark_scan(name: &str) -> Result<LogicalPlan> {
1356        let schema = Schema::new(vec![
1357            Field::new("id", DataType::Int32, true),
1358            Field::new("grp", DataType::Int32, true),
1359        ]);
1360        table_scan(Some(name), &schema, None)?.build()
1361    }
1362
1363    /// `CASE WHEN test.c = 1 THEN NULL ELSE test.c END`: an expression that can
1364    /// be NULL although `test.c` is not nullable. `NULLIF(c, 1)` and
1365    /// `TRY_CAST(c AS INT)` have the same shape, but the optimizer crate cannot
1366    /// depend on the function crates.
1367    fn nullable_key_expr() -> Result<Expr> {
1368        when(col("test.c").eq(lit(1u32)), lit(ScalarValue::UInt32(None)))
1369            .otherwise(col("test.c"))
1370    }
1371
1372    fn has_null_aware_left_mark_join(plan: &LogicalPlan) -> bool {
1373        if let LogicalPlan::Join(join) = plan
1374            && join.join_type == JoinType::LeftMark
1375        {
1376            return join.null_aware;
1377        }
1378
1379        plan.inputs().into_iter().any(has_null_aware_left_mark_join)
1380    }
1381
1382    fn has_non_null_aware_left_mark_join(plan: &LogicalPlan) -> bool {
1383        if let LogicalPlan::Join(join) = plan
1384            && join.join_type == JoinType::LeftMark
1385        {
1386            return !join.null_aware;
1387        }
1388
1389        plan.inputs()
1390            .into_iter()
1391            .any(has_non_null_aware_left_mark_join)
1392    }
1393
1394    fn optimize_with_decorrelate(plan: LogicalPlan) -> Result<LogicalPlan> {
1395        let optimizer = crate::Optimizer::with_rules(vec![Arc::new(
1396            DecorrelatePredicateSubquery::new(),
1397        )]);
1398        optimizer.optimize(plan, &crate::OptimizerContext::new(), |_, _| {})
1399    }
1400
1401    /// A grouping set subquery for the tests below: `SELECT c FROM <name> WHERE
1402    /// c = test.c GROUP BY <group_expr>`.
1403    fn correlated_grouping_set_subquery(
1404        name: &str,
1405        group_expr: Expr,
1406    ) -> Result<Arc<LogicalPlan>> {
1407        Ok(Arc::new(
1408            LogicalPlanBuilder::from(test_table_scan_with_name(name)?)
1409                .filter(
1410                    col(format!("{name}.c")).eq(out_ref_col(DataType::UInt32, "test.c")),
1411                )?
1412                .aggregate(vec![group_expr], Vec::<Expr>::new())?
1413                .project(vec![col(format!("{name}.c"))])?
1414                .build()?,
1415        ))
1416    }
1417
1418    /// `ROLLUP(c)` is `GROUPING SETS ((c), ())`. Adding the correlated column to
1419    /// every set drops the empty one, so the subquery is left correlated.
1420    /// <https://github.com/apache/datafusion/issues/25519>
1421    #[test]
1422    fn exists_subquery_with_rollup_is_not_decorrelated() -> Result<()> {
1423        let subquery = correlated_grouping_set_subquery("sq", rollup(vec![col("sq.c")]))?;
1424        let plan = LogicalPlanBuilder::from(test_table_scan()?)
1425            .filter(exists(subquery))?
1426            .project(vec![col("test.b")])?
1427            .build()?;
1428
1429        assert_optimized_plan_equal!(
1430            plan,
1431            @r"
1432        Projection: test.b [b:UInt32]
1433          Filter: EXISTS (<subquery>) [a:UInt32, b:UInt32, c:UInt32]
1434            Subquery: [c:UInt32;N]
1435              Projection: sq.c [c:UInt32;N]
1436                Aggregate: groupBy=[[ROLLUP (sq.c)]], aggr=[[]] [c:UInt32;N, __grouping_id:UInt8]
1437                  Filter: sq.c = outer_ref(test.c) [a:UInt32, b:UInt32, c:UInt32]
1438                    TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
1439            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1440        "
1441        )
1442    }
1443
1444    /// `CUBE(c)` holds the empty set for the same reason. The correlation is on
1445    /// `a` rather than on the `IN` key, so it stays a filter of its own instead
1446    /// of being folded into the `IN` predicate.
1447    /// <https://github.com/apache/datafusion/issues/25519>
1448    #[test]
1449    fn in_subquery_with_cube_is_not_decorrelated() -> Result<()> {
1450        let subquery = Arc::new(
1451            LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
1452                .filter(col("sq.a").eq(out_ref_col(DataType::UInt32, "test.a")))?
1453                .aggregate(vec![cube(vec![col("sq.c")])], Vec::<Expr>::new())?
1454                .project(vec![col("sq.c")])?
1455                .build()?,
1456        );
1457        let plan = LogicalPlanBuilder::from(test_table_scan()?)
1458            .filter(in_subquery(col("test.c"), subquery))?
1459            .project(vec![col("test.b")])?
1460            .build()?;
1461
1462        assert_optimized_plan_equal!(
1463            plan,
1464            @r"
1465        Projection: test.b [b:UInt32]
1466          Filter: test.c IN (<subquery>) [a:UInt32, b:UInt32, c:UInt32]
1467            Subquery: [c:UInt32;N]
1468              Projection: sq.c [c:UInt32;N]
1469                Aggregate: groupBy=[[CUBE (sq.c)]], aggr=[[]] [c:UInt32;N, __grouping_id:UInt8]
1470                  Filter: sq.a = outer_ref(test.a) [a:UInt32, b:UInt32, c:UInt32]
1471                    TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
1472            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1473        "
1474        )
1475    }
1476
1477    /// A set that groups by another column does not carry the correlated one.
1478    /// <https://github.com/apache/datafusion/issues/25519>
1479    #[test]
1480    fn exists_subquery_with_partial_grouping_set_is_not_decorrelated() -> Result<()> {
1481        let subquery = correlated_grouping_set_subquery(
1482            "sq",
1483            grouping_set(vec![vec![col("sq.c")], vec![col("sq.b")]]),
1484        )?;
1485        let plan = LogicalPlanBuilder::from(test_table_scan()?)
1486            .filter(exists(subquery))?
1487            .project(vec![col("test.b")])?
1488            .build()?;
1489
1490        assert_optimized_plan_equal!(
1491            plan,
1492            @r"
1493        Projection: test.b [b:UInt32]
1494          Filter: EXISTS (<subquery>) [a:UInt32, b:UInt32, c:UInt32]
1495            Subquery: [c:UInt32;N]
1496              Projection: sq.c [c:UInt32;N]
1497                Aggregate: groupBy=[[GROUPING SETS ((sq.c), (sq.b))]], aggr=[[]] [c:UInt32;N, b:UInt32;N, __grouping_id:UInt8]
1498                  Filter: sq.c = outer_ref(test.c) [a:UInt32, b:UInt32, c:UInt32]
1499                    TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
1500            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1501        "
1502        )
1503    }
1504
1505    /// Every set already groups by the correlated column, so the pull up adds
1506    /// nothing and the subquery decorrelates as it did before.
1507    /// <https://github.com/apache/datafusion/issues/25519>
1508    #[test]
1509    fn exists_subquery_with_covering_grouping_set_is_decorrelated() -> Result<()> {
1510        let subquery = correlated_grouping_set_subquery(
1511            "sq",
1512            grouping_set(vec![vec![col("sq.c")], vec![col("sq.c"), col("sq.b")]]),
1513        )?;
1514        let plan = LogicalPlanBuilder::from(test_table_scan()?)
1515            .filter(exists(subquery))?
1516            .project(vec![col("test.b")])?
1517            .build()?;
1518
1519        assert_optimized_plan_equal!(
1520            plan,
1521            @r"
1522        Projection: test.b [b:UInt32]
1523          LeftSemi Join:  Filter: __correlated_sq_1.c = test.c [a:UInt32, b:UInt32, c:UInt32]
1524            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1525            SubqueryAlias: __correlated_sq_1 [c:UInt32;N]
1526              Projection: sq.c [c:UInt32;N]
1527                Aggregate: groupBy=[[GROUPING SETS ((sq.c), (sq.c, sq.b))]], aggr=[[]] [c:UInt32;N, b:UInt32;N, __grouping_id:UInt8]
1528                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
1529        "
1530        )
1531    }
1532
1533    /// Test for several IN subquery expressions
1534    #[test]
1535    fn in_subquery_multiple() -> Result<()> {
1536        let table_scan = test_table_scan()?;
1537        let plan = LogicalPlanBuilder::from(table_scan)
1538            .filter(and(
1539                in_subquery(col("c"), test_subquery_with_name("sq_1")?),
1540                in_subquery(col("b"), test_subquery_with_name("sq_2")?),
1541            ))?
1542            .project(vec![col("test.b")])?
1543            .build()?;
1544
1545        assert_optimized_plan_equal!(
1546            plan,
1547            @r"
1548        Projection: test.b [b:UInt32]
1549          LeftSemi Join:  Filter: test.b = __correlated_sq_2.c [a:UInt32, b:UInt32, c:UInt32]
1550            LeftSemi Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
1551              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1552              SubqueryAlias: __correlated_sq_1 [c:UInt32]
1553                Projection: sq_1.c [c:UInt32]
1554                  TableScan: sq_1 [a:UInt32, b:UInt32, c:UInt32]
1555            SubqueryAlias: __correlated_sq_2 [c:UInt32]
1556              Projection: sq_2.c [c:UInt32]
1557                TableScan: sq_2 [a:UInt32, b:UInt32, c:UInt32]
1558        "
1559        )
1560    }
1561
1562    /// Test for IN subquery with additional AND filter
1563    #[test]
1564    fn in_subquery_with_and_filters() -> Result<()> {
1565        let table_scan = test_table_scan()?;
1566        let plan = LogicalPlanBuilder::from(table_scan)
1567            .filter(and(
1568                in_subquery(col("c"), test_subquery_with_name("sq")?),
1569                and(
1570                    binary_expr(col("a"), Operator::Eq, lit(1_u32)),
1571                    binary_expr(col("b"), Operator::Lt, lit(30_u32)),
1572                ),
1573            ))?
1574            .project(vec![col("test.b")])?
1575            .build()?;
1576
1577        assert_optimized_plan_equal!(
1578            plan,
1579            @r"
1580        Projection: test.b [b:UInt32]
1581          Filter: test.a = UInt32(1) AND test.b < UInt32(30) [a:UInt32, b:UInt32, c:UInt32]
1582            LeftSemi Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
1583              TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1584              SubqueryAlias: __correlated_sq_1 [c:UInt32]
1585                Projection: sq.c [c:UInt32]
1586                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
1587        "
1588        )
1589    }
1590
1591    /// Test for nested IN subqueries
1592    #[test]
1593    fn in_subquery_nested() -> Result<()> {
1594        let table_scan = test_table_scan()?;
1595
1596        let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
1597            .filter(in_subquery(col("a"), test_subquery_with_name("sq_nested")?))?
1598            .project(vec![col("a")])?
1599            .build()?;
1600
1601        let plan = LogicalPlanBuilder::from(table_scan)
1602            .filter(in_subquery(col("b"), Arc::new(subquery)))?
1603            .project(vec![col("test.b")])?
1604            .build()?;
1605
1606        assert_optimized_plan_equal!(
1607            plan,
1608            @r"
1609        Projection: test.b [b:UInt32]
1610          LeftSemi Join:  Filter: test.b = __correlated_sq_2.a [a:UInt32, b:UInt32, c:UInt32]
1611            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
1612            SubqueryAlias: __correlated_sq_2 [a:UInt32]
1613              Projection: sq.a [a:UInt32]
1614                LeftSemi Join:  Filter: sq.a = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
1615                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
1616                  SubqueryAlias: __correlated_sq_1 [c:UInt32]
1617                    Projection: sq_nested.c [c:UInt32]
1618                      TableScan: sq_nested [a:UInt32, b:UInt32, c:UInt32]
1619        "
1620        )
1621    }
1622
1623    /// Test multiple correlated subqueries
1624    /// See subqueries.rs where_in_multiple()
1625    #[test]
1626    fn multiple_subqueries() -> Result<()> {
1627        let orders = Arc::new(
1628            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1629                .filter(
1630                    col("orders.o_custkey")
1631                        .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
1632                )?
1633                .project(vec![col("orders.o_custkey")])?
1634                .build()?,
1635        );
1636        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1637            .filter(
1638                in_subquery(col("customer.c_custkey"), Arc::clone(&orders))
1639                    .and(in_subquery(col("customer.c_custkey"), orders)),
1640            )?
1641            .project(vec![col("customer.c_custkey")])?
1642            .build()?;
1643        debug!("plan to optimize:\n{}", plan.display_indent());
1644
1645        assert_optimized_plan_equal!(
1646                plan,
1647                @r"
1648        Projection: customer.c_custkey [c_custkey:Int64]
1649          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_2.o_custkey [c_custkey:Int64, c_name:Utf8]
1650            LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
1651              TableScan: customer [c_custkey:Int64, c_name:Utf8]
1652              SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
1653                Projection: orders.o_custkey [o_custkey:Int64]
1654                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1655            SubqueryAlias: __correlated_sq_2 [o_custkey:Int64]
1656              Projection: orders.o_custkey [o_custkey:Int64]
1657                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1658        "
1659        )
1660    }
1661
1662    /// Test recursive correlated subqueries
1663    /// See subqueries.rs where_in_recursive()
1664    #[test]
1665    fn recursive_subqueries() -> Result<()> {
1666        let lineitem = Arc::new(
1667            LogicalPlanBuilder::from(scan_tpch_table("lineitem"))
1668                .filter(
1669                    col("lineitem.l_orderkey")
1670                        .eq(out_ref_col(DataType::Int64, "orders.o_orderkey")),
1671                )?
1672                .project(vec![col("lineitem.l_orderkey")])?
1673                .build()?,
1674        );
1675
1676        let orders = Arc::new(
1677            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1678                .filter(
1679                    in_subquery(col("orders.o_orderkey"), lineitem).and(
1680                        col("orders.o_custkey")
1681                            .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
1682                    ),
1683                )?
1684                .project(vec![col("orders.o_custkey")])?
1685                .build()?,
1686        );
1687
1688        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1689            .filter(in_subquery(col("customer.c_custkey"), orders))?
1690            .project(vec![col("customer.c_custkey")])?
1691            .build()?;
1692
1693        assert_optimized_plan_equal!(
1694            plan,
1695            @r"
1696        Projection: customer.c_custkey [c_custkey:Int64]
1697          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_2.o_custkey [c_custkey:Int64, c_name:Utf8]
1698            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1699            SubqueryAlias: __correlated_sq_2 [o_custkey:Int64]
1700              Projection: orders.o_custkey [o_custkey:Int64]
1701                LeftSemi Join:  Filter: orders.o_orderkey = __correlated_sq_1.l_orderkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1702                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1703                  SubqueryAlias: __correlated_sq_1 [l_orderkey:Int64]
1704                    Projection: lineitem.l_orderkey [l_orderkey:Int64]
1705                      TableScan: lineitem [l_orderkey:Int64, l_partkey:Int64, l_suppkey:Int64, l_linenumber:Int32, l_quantity:Float64, l_extendedprice:Float64]
1706        "
1707        )
1708    }
1709
1710    /// Test for correlated IN subquery filter with additional subquery filters
1711    #[test]
1712    fn in_subquery_with_subquery_filters() -> Result<()> {
1713        let sq = Arc::new(
1714            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1715                .filter(
1716                    out_ref_col(DataType::Int64, "customer.c_custkey")
1717                        .eq(col("orders.o_custkey"))
1718                        .and(col("o_orderkey").eq(lit(1))),
1719                )?
1720                .project(vec![col("orders.o_custkey")])?
1721                .build()?,
1722        );
1723
1724        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1725            .filter(in_subquery(col("customer.c_custkey"), sq))?
1726            .project(vec![col("customer.c_custkey")])?
1727            .build()?;
1728
1729        assert_optimized_plan_equal!(
1730            plan,
1731            @r"
1732        Projection: customer.c_custkey [c_custkey:Int64]
1733          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
1734            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1735            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
1736              Projection: orders.o_custkey [o_custkey:Int64]
1737                Filter: orders.o_orderkey = Int32(1) [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1738                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1739        "
1740        )
1741    }
1742
1743    /// Test for correlated IN subquery with no columns in schema
1744    #[test]
1745    fn in_subquery_no_cols() -> Result<()> {
1746        let sq = Arc::new(
1747            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1748                .filter(
1749                    out_ref_col(DataType::Int64, "customer.c_custkey")
1750                        .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
1751                )?
1752                .project(vec![col("orders.o_custkey")])?
1753                .build()?,
1754        );
1755
1756        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1757            .filter(in_subquery(col("customer.c_custkey"), sq))?
1758            .project(vec![col("customer.c_custkey")])?
1759            .build()?;
1760
1761        assert_optimized_plan_equal!(
1762            plan,
1763            @r"
1764        Projection: customer.c_custkey [c_custkey:Int64]
1765          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
1766            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1767            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
1768              Projection: orders.o_custkey [o_custkey:Int64]
1769                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1770        "
1771        )
1772    }
1773
1774    /// Test for IN subquery with both columns in schema
1775    #[test]
1776    fn in_subquery_with_no_correlated_cols() -> Result<()> {
1777        let sq = Arc::new(
1778            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1779                .filter(col("orders.o_custkey").eq(col("orders.o_custkey")))?
1780                .project(vec![col("orders.o_custkey")])?
1781                .build()?,
1782        );
1783
1784        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1785            .filter(in_subquery(col("customer.c_custkey"), sq))?
1786            .project(vec![col("customer.c_custkey")])?
1787            .build()?;
1788
1789        assert_optimized_plan_equal!(
1790            plan,
1791            @r"
1792        Projection: customer.c_custkey [c_custkey:Int64]
1793          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
1794            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1795            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
1796              Projection: orders.o_custkey [o_custkey:Int64]
1797                Filter: orders.o_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1798                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1799        "
1800        )
1801    }
1802
1803    /// Test for correlated IN subquery not equal
1804    #[test]
1805    fn in_subquery_where_not_eq() -> Result<()> {
1806        let sq = Arc::new(
1807            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1808                .filter(
1809                    out_ref_col(DataType::Int64, "customer.c_custkey")
1810                        .not_eq(col("orders.o_custkey")),
1811                )?
1812                .project(vec![col("orders.o_custkey")])?
1813                .build()?,
1814        );
1815
1816        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1817            .filter(in_subquery(col("customer.c_custkey"), sq))?
1818            .project(vec![col("customer.c_custkey")])?
1819            .build()?;
1820
1821        assert_optimized_plan_equal!(
1822            plan,
1823            @r"
1824        Projection: customer.c_custkey [c_custkey:Int64]
1825          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey AND customer.c_custkey != __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
1826            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1827            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
1828              Projection: orders.o_custkey [o_custkey:Int64]
1829                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1830        "
1831        )
1832    }
1833
1834    /// Test for correlated IN subquery less than
1835    #[test]
1836    fn in_subquery_where_less_than() -> Result<()> {
1837        let sq = Arc::new(
1838            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1839                .filter(
1840                    out_ref_col(DataType::Int64, "customer.c_custkey")
1841                        .lt(col("orders.o_custkey")),
1842                )?
1843                .project(vec![col("orders.o_custkey")])?
1844                .build()?,
1845        );
1846
1847        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1848            .filter(in_subquery(col("customer.c_custkey"), sq))?
1849            .project(vec![col("customer.c_custkey")])?
1850            .build()?;
1851
1852        assert_optimized_plan_equal!(
1853            plan,
1854            @r"
1855        Projection: customer.c_custkey [c_custkey:Int64]
1856          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey AND customer.c_custkey < __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
1857            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1858            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
1859              Projection: orders.o_custkey [o_custkey:Int64]
1860                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1861        "
1862        )
1863    }
1864
1865    /// Test for correlated IN subquery filter with subquery disjunction
1866    #[test]
1867    fn in_subquery_with_subquery_disjunction() -> Result<()> {
1868        let sq = Arc::new(
1869            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1870                .filter(
1871                    out_ref_col(DataType::Int64, "customer.c_custkey")
1872                        .eq(col("orders.o_custkey"))
1873                        .or(col("o_orderkey").eq(lit(1))),
1874                )?
1875                .project(vec![col("orders.o_custkey")])?
1876                .build()?,
1877        );
1878
1879        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1880            .filter(in_subquery(col("customer.c_custkey"), sq))?
1881            .project(vec![col("customer.c_custkey")])?
1882            .build()?;
1883
1884        assert_optimized_plan_equal!(
1885            plan,
1886            @"
1887        Projection: customer.c_custkey [c_custkey:Int64]
1888          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey AND (customer.c_custkey = __correlated_sq_1.o_custkey OR __correlated_sq_1.o_orderkey = Int32(1)) [c_custkey:Int64, c_name:Utf8]
1889            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1890            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64, o_orderkey:Int64]
1891              Projection: orders.o_custkey, orders.o_orderkey [o_custkey:Int64, o_orderkey:Int64]
1892                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1893        "
1894        )
1895    }
1896
1897    /// Test for correlated IN without projection
1898    #[test]
1899    fn in_subquery_no_projection() -> Result<()> {
1900        let sq = Arc::new(
1901            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1902                .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?
1903                .build()?,
1904        );
1905
1906        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1907            .filter(in_subquery(col("customer.c_custkey"), sq))?
1908            .project(vec![col("customer.c_custkey")])?
1909            .build()?;
1910
1911        // Maybe okay if the table only has a single column?
1912        let expected = "Invalid (non-executable) plan after Analyzer\
1913        \ncaused by\
1914        \nError during planning: InSubquery should only return one column, but found 4";
1915        assert_analyzer_check_err(vec![], plan, expected);
1916
1917        Ok(())
1918    }
1919
1920    /// Test for correlated IN subquery join on expression
1921    #[test]
1922    fn in_subquery_join_expr() -> Result<()> {
1923        let sq = Arc::new(
1924            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1925                .filter(
1926                    out_ref_col(DataType::Int64, "customer.c_custkey")
1927                        .eq(col("orders.o_custkey")),
1928                )?
1929                .project(vec![col("orders.o_custkey")])?
1930                .build()?,
1931        );
1932
1933        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1934            .filter(in_subquery(col("customer.c_custkey").add(lit(1)), sq))?
1935            .project(vec![col("customer.c_custkey")])?
1936            .build()?;
1937
1938        assert_optimized_plan_equal!(
1939            plan,
1940            @r"
1941        Projection: customer.c_custkey [c_custkey:Int64]
1942          LeftSemi Join:  Filter: customer.c_custkey + Int32(1) = __correlated_sq_1.o_custkey AND customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
1943            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1944            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
1945              Projection: orders.o_custkey [o_custkey:Int64]
1946                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1947        "
1948        )
1949    }
1950
1951    /// Test for correlated IN expressions
1952    #[test]
1953    fn in_subquery_project_expr() -> Result<()> {
1954        let sq = Arc::new(
1955            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1956                .filter(
1957                    out_ref_col(DataType::Int64, "customer.c_custkey")
1958                        .eq(col("orders.o_custkey")),
1959                )?
1960                .project(vec![col("orders.o_custkey").add(lit(1))])?
1961                .build()?,
1962        );
1963
1964        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1965            .filter(in_subquery(col("customer.c_custkey"), sq))?
1966            .project(vec![col("customer.c_custkey")])?
1967            .build()?;
1968
1969        assert_optimized_plan_equal!(
1970            plan,
1971            @r"
1972        Projection: customer.c_custkey [c_custkey:Int64]
1973          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.orders.o_custkey + Int32(1) AND customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
1974            TableScan: customer [c_custkey:Int64, c_name:Utf8]
1975            SubqueryAlias: __correlated_sq_1 [orders.o_custkey + Int32(1):Int64, o_custkey:Int64]
1976              Projection: orders.o_custkey + Int32(1), orders.o_custkey [orders.o_custkey + Int32(1):Int64, o_custkey:Int64]
1977                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
1978        "
1979        )
1980    }
1981
1982    /// Test for correlated IN subquery multiple projected columns
1983    #[test]
1984    fn in_subquery_multi_col() -> Result<()> {
1985        let sq = Arc::new(
1986            LogicalPlanBuilder::from(scan_tpch_table("orders"))
1987                .filter(
1988                    out_ref_col(DataType::Int64, "customer.c_custkey")
1989                        .eq(col("orders.o_custkey")),
1990                )?
1991                .project(vec![col("orders.o_custkey"), col("orders.o_orderkey")])?
1992                .build()?,
1993        );
1994
1995        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
1996            .filter(
1997                in_subquery(col("customer.c_custkey"), sq)
1998                    .and(col("c_custkey").eq(lit(1))),
1999            )?
2000            .project(vec![col("customer.c_custkey")])?
2001            .build()?;
2002
2003        let expected = "Invalid (non-executable) plan after Analyzer\
2004        \ncaused by\
2005        \nError during planning: InSubquery should only return one column";
2006        assert_analyzer_check_err(vec![], plan, expected);
2007
2008        Ok(())
2009    }
2010
2011    /// Test for correlated IN subquery filter with additional filters
2012    #[test]
2013    fn should_support_additional_filters() -> Result<()> {
2014        let sq = Arc::new(
2015            LogicalPlanBuilder::from(scan_tpch_table("orders"))
2016                .filter(
2017                    out_ref_col(DataType::Int64, "customer.c_custkey")
2018                        .eq(col("orders.o_custkey")),
2019                )?
2020                .project(vec![col("orders.o_custkey")])?
2021                .build()?,
2022        );
2023
2024        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
2025            .filter(
2026                in_subquery(col("customer.c_custkey"), sq)
2027                    .and(col("c_custkey").eq(lit(1))),
2028            )?
2029            .project(vec![col("customer.c_custkey")])?
2030            .build()?;
2031
2032        assert_optimized_plan_equal!(
2033            plan,
2034            @r"
2035        Projection: customer.c_custkey [c_custkey:Int64]
2036          Filter: customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8]
2037            LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
2038              TableScan: customer [c_custkey:Int64, c_name:Utf8]
2039              SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
2040                Projection: orders.o_custkey [o_custkey:Int64]
2041                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2042        "
2043        )
2044    }
2045
2046    /// Test for correlated IN subquery filter
2047    #[test]
2048    fn in_subquery_correlated() -> Result<()> {
2049        let sq = Arc::new(
2050            LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
2051                .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?
2052                .project(vec![col("c")])?
2053                .build()?,
2054        );
2055
2056        let plan = LogicalPlanBuilder::from(test_table_scan_with_name("test")?)
2057            .filter(in_subquery(col("c"), sq))?
2058            .project(vec![col("test.b")])?
2059            .build()?;
2060
2061        assert_optimized_plan_equal!(
2062            plan,
2063            @r"
2064        Projection: test.b [b:UInt32]
2065          LeftSemi Join:  Filter: test.c = __correlated_sq_1.c AND test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
2066            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2067            SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
2068              Projection: sq.c, sq.a [c:UInt32, a:UInt32]
2069                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2070        "
2071        )
2072    }
2073
2074    /// Test for single IN subquery filter
2075    #[test]
2076    fn in_subquery_simple() -> Result<()> {
2077        let table_scan = test_table_scan()?;
2078        let plan = LogicalPlanBuilder::from(table_scan)
2079            .filter(in_subquery(col("c"), test_subquery_with_name("sq")?))?
2080            .project(vec![col("test.b")])?
2081            .build()?;
2082
2083        assert_optimized_plan_equal!(
2084            plan,
2085            @r"
2086        Projection: test.b [b:UInt32]
2087          LeftSemi Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
2088            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2089            SubqueryAlias: __correlated_sq_1 [c:UInt32]
2090              Projection: sq.c [c:UInt32]
2091                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2092        "
2093        )
2094    }
2095
2096    #[test]
2097    fn in_subquery_in_projection() -> Result<()> {
2098        let plan = LogicalPlanBuilder::from(test_table_scan()?)
2099            .project(vec![
2100                in_subquery(col("c"), test_subquery_with_name("sq")?).alias("is_present"),
2101            ])?
2102            .build()?;
2103
2104        assert_optimized_plan_equal!(
2105            plan,
2106            @r"
2107        Projection: __correlated_sq_1.mark AS is_present [is_present:Boolean;N]
2108          LeftMark Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32, mark:Boolean;N]
2109            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2110            Projection: __correlated_sq_1.c [c:UInt32]
2111              SubqueryAlias: __correlated_sq_1 [c:UInt32]
2112                Projection: sq.c [c:UInt32]
2113                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2114        "
2115        )
2116    }
2117
2118    /// A residual non-equality correlation stays on the one mark join. The
2119    /// null-aware hash join applies it when it decides whether a NULL makes
2120    /// the mark UNKNOWN, so the mark is still exact.
2121    #[test]
2122    fn in_subquery_in_projection_with_residual_filter() -> Result<()> {
2123        let subquery = Arc::new(
2124            LogicalPlanBuilder::from(nullable_scalar_mark_scan("inner_t")?)
2125                .filter(
2126                    out_ref_col(DataType::Int32, "outer_t.grp").gt(col("inner_t.grp")),
2127                )?
2128                .project(vec![col("inner_t.id")])?
2129                .build()?,
2130        );
2131
2132        let plan = LogicalPlanBuilder::from(nullable_scalar_mark_scan("outer_t")?)
2133            .project(vec![
2134                in_subquery(col("outer_t.id"), subquery).alias("is_present"),
2135            ])?
2136            .build()?;
2137
2138        assert_optimized_plan_equal!(
2139            plan,
2140            @r"
2141        Projection: __correlated_sq_1.mark AS is_present [is_present:Boolean;N]
2142          LeftMark Join:  Filter: outer_t.id = __correlated_sq_1.id AND outer_t.grp > __correlated_sq_1.grp null_aware [id:Int32;N, grp:Int32;N, mark:Boolean;N]
2143            TableScan: outer_t [id:Int32;N, grp:Int32;N]
2144            Projection: __correlated_sq_1.id, __correlated_sq_1.grp [id:Int32;N, grp:Int32;N]
2145              SubqueryAlias: __correlated_sq_1 [id:Int32;N, grp:Int32;N]
2146                Projection: inner_t.id, inner_t.grp [id:Int32;N, grp:Int32;N]
2147                  TableScan: inner_t [id:Int32;N, grp:Int32;N]
2148        "
2149        )
2150    }
2151
2152    /// `NOT IN` reads the same mark column, negated. The keys are nullable here,
2153    /// so the join is null-aware and the mark is NULL for the UNKNOWN rows.
2154    #[test]
2155    fn not_in_subquery_in_projection() -> Result<()> {
2156        let subquery = Arc::new(
2157            LogicalPlanBuilder::from(nullable_scalar_mark_scan("inner_t")?)
2158                .project(vec![col("inner_t.id")])?
2159                .build()?,
2160        );
2161
2162        let plan = LogicalPlanBuilder::from(nullable_scalar_mark_scan("outer_t")?)
2163            .project(vec![
2164                not_in_subquery(col("outer_t.id"), subquery).alias("is_absent"),
2165            ])?
2166            .build()?;
2167
2168        assert_optimized_plan_equal!(
2169            plan,
2170            @r"
2171        Projection: NOT __correlated_sq_1.mark AS is_absent [is_absent:Boolean;N]
2172          LeftMark Join:  Filter: outer_t.id = __correlated_sq_1.id null_aware [id:Int32;N, grp:Int32;N, mark:Boolean;N]
2173            TableScan: outer_t [id:Int32;N, grp:Int32;N]
2174            Projection: __correlated_sq_1.id [id:Int32;N]
2175              SubqueryAlias: __correlated_sq_1 [id:Int32;N]
2176                Projection: inner_t.id [id:Int32;N]
2177                  TableScan: inner_t [id:Int32;N, grp:Int32;N]
2178        "
2179        )
2180    }
2181
2182    /// A key expression can be NULL although none of its columns is nullable.
2183    /// The mark join must then be null-aware, so the mark is NULL for the rows
2184    /// that give UNKNOWN.
2185    #[test]
2186    fn in_subquery_in_projection_with_nullable_key_expr() -> Result<()> {
2187        let plan = LogicalPlanBuilder::from(test_table_scan()?)
2188            .project(vec![
2189                in_subquery(nullable_key_expr()?, test_subquery_with_name("sq")?)
2190                    .alias("is_present"),
2191            ])?
2192            .build()?;
2193
2194        assert_optimized_plan_equal!(
2195            plan,
2196            @r"
2197        Projection: __correlated_sq_1.mark AS is_present [is_present:Boolean;N]
2198          LeftMark Join:  Filter: CASE WHEN test.c = UInt32(1) THEN UInt32(NULL) ELSE test.c END = __correlated_sq_1.c null_aware [a:UInt32, b:UInt32, c:UInt32, mark:Boolean;N]
2199            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2200            Projection: __correlated_sq_1.c [c:UInt32]
2201              SubqueryAlias: __correlated_sq_1 [c:UInt32]
2202                Projection: sq.c [c:UInt32]
2203                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2204        "
2205        )
2206    }
2207
2208    /// The `NOT IN` filter path builds a `LeftAnti` join. It reads the key
2209    /// nullability the same way, so a nullable key expression over columns that
2210    /// are not nullable also makes that join null-aware.
2211    #[test]
2212    fn not_in_subquery_filter_with_nullable_key_expr() -> Result<()> {
2213        let plan = LogicalPlanBuilder::from(test_table_scan()?)
2214            .filter(not_in_subquery(
2215                nullable_key_expr()?,
2216                test_subquery_with_name("sq")?,
2217            ))?
2218            .project(vec![col("test.b")])?
2219            .build()?;
2220
2221        assert_optimized_plan_equal!(
2222            plan,
2223            @r"
2224        Projection: test.b [b:UInt32]
2225          LeftAnti Join:  Filter: CASE WHEN test.c = UInt32(1) THEN UInt32(NULL) ELSE test.c END = __correlated_sq_1.c null_aware [a:UInt32, b:UInt32, c:UInt32]
2226            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2227            SubqueryAlias: __correlated_sq_1 [c:UInt32]
2228              Projection: sq.c [c:UInt32]
2229                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2230        "
2231        )
2232    }
2233
2234    #[test]
2235    fn unsupported_correlated_in_projection_is_left_unchanged() -> Result<()> {
2236        let subquery = Arc::new(
2237            LogicalPlanBuilder::from(scan_tpch_table("orders"))
2238                .filter(
2239                    out_ref_col(DataType::Int64, "customer.c_custkey")
2240                        .eq(col("orders.o_custkey")),
2241                )?
2242                .limit(0, Some(1))?
2243                .project(vec![col("orders.o_custkey")])?
2244                .build()?,
2245        );
2246        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
2247            .project(vec![
2248                in_subquery(col("customer.c_custkey"), subquery).alias("is_present"),
2249            ])?
2250            .build()?;
2251
2252        let result = DecorrelatePredicateSubquery::new()
2253            .rewrite(plan.clone(), &crate::OptimizerContext::new())?;
2254
2255        assert!(!result.transformed);
2256        assert_eq!(result.data, plan);
2257        Ok(())
2258    }
2259
2260    /// Test for single NOT IN subquery filter
2261    #[test]
2262    fn not_in_subquery_simple() -> Result<()> {
2263        let table_scan = test_table_scan()?;
2264        let plan = LogicalPlanBuilder::from(table_scan)
2265            .filter(not_in_subquery(col("c"), test_subquery_with_name("sq")?))?
2266            .project(vec![col("test.b")])?
2267            .build()?;
2268
2269        assert_optimized_plan_equal!(
2270            plan,
2271            @r"
2272        Projection: test.b [b:UInt32]
2273          LeftAnti Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
2274            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2275            SubqueryAlias: __correlated_sq_1 [c:UInt32]
2276              Projection: sq.c [c:UInt32]
2277                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2278        "
2279        )
2280    }
2281
2282    #[test]
2283    fn wrapped_not_in_subquery() -> Result<()> {
2284        let table_scan = test_table_scan()?;
2285        let plan = LogicalPlanBuilder::from(table_scan)
2286            .filter(not(in_subquery(col("c"), test_subquery_with_name("sq")?)))?
2287            .project(vec![col("test.b")])?
2288            .build()?;
2289
2290        assert_optimized_plan_equal!(
2291            plan,
2292            @r"
2293        Projection: test.b [b:UInt32]
2294          LeftAnti Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
2295            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2296            SubqueryAlias: __correlated_sq_1 [c:UInt32]
2297              Projection: sq.c [c:UInt32]
2298                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2299        "
2300        )
2301    }
2302
2303    #[test]
2304    fn wrapped_not_not_in_subquery() -> Result<()> {
2305        let table_scan = test_table_scan()?;
2306        let plan = LogicalPlanBuilder::from(table_scan)
2307            .filter(not(not_in_subquery(
2308                col("c"),
2309                test_subquery_with_name("sq")?,
2310            )))?
2311            .project(vec![col("test.b")])?
2312            .build()?;
2313
2314        assert_optimized_plan_equal!(
2315            plan,
2316            @r"
2317        Projection: test.b [b:UInt32]
2318          LeftSemi Join:  Filter: test.c = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
2319            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2320            SubqueryAlias: __correlated_sq_1 [c:UInt32]
2321              Projection: sq.c [c:UInt32]
2322                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2323        "
2324        )
2325    }
2326
2327    /// A constant value expression has no column, so `Int32(3) = inner_t.id`
2328    /// cannot be an equi-join key on its own. The rule projects the constant as
2329    /// a column of the outer side; `ExtractEquijoinPredicate` (not run here)
2330    /// then turns the filter into a real key for the null-aware hash join.
2331    #[test]
2332    fn constant_not_in_subquery_projects_value_as_join_key() -> Result<()> {
2333        let outer_scan = nullable_scalar_mark_scan("outer_t")?;
2334        let inner_scan = nullable_scalar_mark_scan("inner_t")?;
2335
2336        let subquery = Arc::new(
2337            LogicalPlanBuilder::from(inner_scan)
2338                .project(vec![col("inner_t.id")])?
2339                .build()?,
2340        );
2341
2342        let plan = LogicalPlanBuilder::from(outer_scan)
2343            .filter(not_in_subquery(lit(3i32), subquery))?
2344            .build()?;
2345
2346        assert_optimized_plan_equal!(
2347            plan,
2348            @r"
2349        Projection: outer_t.id, outer_t.grp [id:Int32;N, grp:Int32;N]
2350          LeftAnti Join:  Filter: __correlated_sq_1_value = __correlated_sq_1.id null_aware [id:Int32;N, grp:Int32;N, __correlated_sq_1_value:Int32]
2351            Projection: outer_t.id, outer_t.grp, Int32(3) AS __correlated_sq_1_value [id:Int32;N, grp:Int32;N, __correlated_sq_1_value:Int32]
2352              TableScan: outer_t [id:Int32;N, grp:Int32;N]
2353            SubqueryAlias: __correlated_sq_1 [id:Int32;N]
2354              Projection: inner_t.id [id:Int32;N]
2355                TableScan: inner_t [id:Int32;N, grp:Int32;N]
2356        "
2357        )
2358    }
2359
2360    /// A NULL constant has no column, but it is still nullable. The join must
2361    /// be null-aware although the subquery column `sq.c` is not nullable
2362    /// (<https://github.com/apache/datafusion/issues/25473>).
2363    #[test]
2364    fn null_constant_not_in_non_nullable_subquery_is_null_aware() -> Result<()> {
2365        let plan = LogicalPlanBuilder::from(test_table_scan()?)
2366            .filter(not_in_subquery(
2367                lit(ScalarValue::UInt32(None)),
2368                test_subquery_with_name("sq")?,
2369            ))?
2370            .project(vec![col("test.b")])?
2371            .build()?;
2372
2373        assert_optimized_plan_equal!(
2374            plan,
2375            @r"
2376        Projection: test.b [b:UInt32]
2377          Projection: test.a, test.b, test.c [a:UInt32, b:UInt32, c:UInt32]
2378            LeftAnti Join:  Filter: __correlated_sq_1_value = __correlated_sq_1.c null_aware [a:UInt32, b:UInt32, c:UInt32, __correlated_sq_1_value:UInt32;N]
2379              Projection: test.a, test.b, test.c, UInt32(NULL) AS __correlated_sq_1_value [a:UInt32, b:UInt32, c:UInt32, __correlated_sq_1_value:UInt32;N]
2380                TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2381              SubqueryAlias: __correlated_sq_1 [c:UInt32]
2382                Projection: sq.c [c:UInt32]
2383                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2384        "
2385        )
2386    }
2387
2388    /// `test.c + 1` over a non-nullable `test.c` cannot be NULL, and neither can
2389    /// `sq.c`, so the anti join stays plain
2390    /// (<https://github.com/apache/datafusion/issues/25474>).
2391    #[test]
2392    fn non_nullable_key_expr_not_in_is_not_null_aware() -> Result<()> {
2393        let plan = LogicalPlanBuilder::from(test_table_scan()?)
2394            .filter(not_in_subquery(
2395                col("test.c") + lit(1u32),
2396                test_subquery_with_name("sq")?,
2397            ))?
2398            .project(vec![col("test.b")])?
2399            .build()?;
2400
2401        assert_optimized_plan_equal!(
2402            plan,
2403            @r"
2404        Projection: test.b [b:UInt32]
2405          LeftAnti Join:  Filter: test.c + UInt32(1) = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
2406            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2407            SubqueryAlias: __correlated_sq_1 [c:UInt32]
2408              Projection: sq.c [c:UInt32]
2409                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2410        "
2411        )
2412    }
2413
2414    #[test]
2415    fn correlated_not_in_mark_join_is_null_aware_for_hashable_filter() -> Result<()> {
2416        let outer_scan = nullable_scalar_mark_scan("outer_t")?;
2417        let inner_scan = nullable_scalar_mark_scan("inner_t")?;
2418
2419        let subquery = Arc::new(
2420            LogicalPlanBuilder::from(inner_scan)
2421                .filter(
2422                    out_ref_col(DataType::Int32, "outer_t.grp").eq(col("inner_t.grp")),
2423                )?
2424                .project(vec![col("inner_t.id")])?
2425                .build()?,
2426        );
2427
2428        let plan = LogicalPlanBuilder::from(outer_scan)
2429            .filter(not_in_subquery(col("outer_t.id"), subquery).is_null())?
2430            .build()?;
2431
2432        let optimized = optimize_with_decorrelate(plan)?;
2433        assert!(
2434            has_null_aware_left_mark_join(&optimized),
2435            "{}",
2436            optimized.display_indent_schema()
2437        );
2438
2439        Ok(())
2440    }
2441
2442    /// A correlation that repeats the `IN` predicate keeps every NULL out of
2443    /// the subquery result, so the mark join must not be null-aware.
2444    #[test]
2445    fn mark_join_for_in_predicate_correlation_is_not_null_aware() -> Result<()> {
2446        let outer_scan = nullable_scalar_mark_scan("outer_t")?;
2447        let inner_scan = nullable_scalar_mark_scan("inner_t")?;
2448
2449        let subquery = Arc::new(
2450            LogicalPlanBuilder::from(inner_scan)
2451                .filter(out_ref_col(DataType::Int32, "outer_t.id").eq(col("inner_t.id")))?
2452                .project(vec![col("inner_t.id")])?
2453                .build()?,
2454        );
2455
2456        let plan = LogicalPlanBuilder::from(outer_scan)
2457            .filter(in_subquery(col("outer_t.id"), subquery).is_null())?
2458            .build()?;
2459
2460        let optimized = optimize_with_decorrelate(plan)?;
2461        assert!(
2462            has_non_null_aware_left_mark_join(&optimized),
2463            "{}",
2464            optimized.display_indent_schema()
2465        );
2466
2467        Ok(())
2468    }
2469
2470    /// A grouping set above the correlation puts a NULL back into the key: the
2471    /// grand-total row of `ROLLUP` is a NULL for every outer row. The
2472    /// correlation then no longer bounds the subquery result, and the mark
2473    /// join stays null-aware.
2474    #[test]
2475    fn mark_join_for_in_predicate_correlation_below_rollup_is_null_aware() -> Result<()> {
2476        let subquery = correlated_grouping_set_subquery("sq", rollup(vec![col("sq.c")]))?;
2477        let plan = LogicalPlanBuilder::from(test_table_scan()?)
2478            .project(vec![in_subquery(col("test.c"), subquery).alias("m")])?
2479            .build()?;
2480
2481        let optimized = optimize_with_decorrelate(plan)?;
2482        assert!(
2483            has_null_aware_left_mark_join(&optimized),
2484            "{}",
2485            optimized.display_indent_schema()
2486        );
2487
2488        Ok(())
2489    }
2490
2491    /// The same for the `LeftAnti` join that a `NOT IN` filter builds.
2492    #[test]
2493    fn anti_join_for_in_predicate_correlation_is_not_null_aware() -> Result<()> {
2494        let outer_scan = nullable_scalar_mark_scan("outer_t")?;
2495        let inner_scan = nullable_scalar_mark_scan("inner_t")?;
2496
2497        let subquery = Arc::new(
2498            LogicalPlanBuilder::from(inner_scan)
2499                .filter(out_ref_col(DataType::Int32, "outer_t.id").eq(col("inner_t.id")))?
2500                .project(vec![col("inner_t.id")])?
2501                .build()?,
2502        );
2503
2504        let plan = LogicalPlanBuilder::from(outer_scan)
2505            .filter(not_in_subquery(col("outer_t.id"), subquery))?
2506            .build()?;
2507
2508        assert_optimized_plan_equal!(
2509            plan,
2510            @r"
2511        LeftAnti Join:  Filter: outer_t.id = __correlated_sq_1.id [id:Int32;N, grp:Int32;N]
2512          TableScan: outer_t [id:Int32;N, grp:Int32;N]
2513          SubqueryAlias: __correlated_sq_1 [id:Int32;N]
2514            Projection: inner_t.id [id:Int32;N]
2515              TableScan: inner_t [id:Int32;N, grp:Int32;N]
2516        "
2517        )
2518    }
2519
2520    #[test]
2521    fn in_subquery_both_side_expr() -> Result<()> {
2522        let table_scan = test_table_scan()?;
2523        let subquery_scan = test_table_scan_with_name("sq")?;
2524
2525        let subquery = LogicalPlanBuilder::from(subquery_scan)
2526            .project(vec![col("c") * lit(2u32)])?
2527            .build()?;
2528
2529        let plan = LogicalPlanBuilder::from(table_scan)
2530            .filter(in_subquery(col("c") + lit(1u32), Arc::new(subquery)))?
2531            .project(vec![col("test.b")])?
2532            .build()?;
2533
2534        assert_optimized_plan_equal!(
2535            plan,
2536            @r"
2537        Projection: test.b [b:UInt32]
2538          LeftSemi Join:  Filter: test.c + UInt32(1) = __correlated_sq_1.sq.c * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
2539            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2540            SubqueryAlias: __correlated_sq_1 [sq.c * UInt32(2):UInt32]
2541              Projection: sq.c * UInt32(2) [sq.c * UInt32(2):UInt32]
2542                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2543        "
2544        )
2545    }
2546
2547    #[test]
2548    fn in_subquery_join_filter_and_inner_filter() -> Result<()> {
2549        let table_scan = test_table_scan()?;
2550        let subquery_scan = test_table_scan_with_name("sq")?;
2551
2552        let subquery = LogicalPlanBuilder::from(subquery_scan)
2553            .filter(
2554                out_ref_col(DataType::UInt32, "test.a")
2555                    .eq(col("sq.a"))
2556                    .and(col("sq.a").add(lit(1u32)).eq(col("sq.b"))),
2557            )?
2558            .project(vec![col("c") * lit(2u32)])?
2559            .build()?;
2560
2561        let plan = LogicalPlanBuilder::from(table_scan)
2562            .filter(in_subquery(col("c") + lit(1u32), Arc::new(subquery)))?
2563            .project(vec![col("test.b")])?
2564            .build()?;
2565
2566        assert_optimized_plan_equal!(
2567            plan,
2568            @r"
2569        Projection: test.b [b:UInt32]
2570          LeftSemi Join:  Filter: test.c + UInt32(1) = __correlated_sq_1.sq.c * UInt32(2) AND test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
2571            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2572            SubqueryAlias: __correlated_sq_1 [sq.c * UInt32(2):UInt32, a:UInt32]
2573              Projection: sq.c * UInt32(2), sq.a [sq.c * UInt32(2):UInt32, a:UInt32]
2574                Filter: sq.a + UInt32(1) = sq.b [a:UInt32, b:UInt32, c:UInt32]
2575                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2576        "
2577        )
2578    }
2579
2580    #[test]
2581    fn in_subquery_multi_project_subquery_cols() -> Result<()> {
2582        let table_scan = test_table_scan()?;
2583        let subquery_scan = test_table_scan_with_name("sq")?;
2584
2585        let subquery = LogicalPlanBuilder::from(subquery_scan)
2586            .filter(
2587                out_ref_col(DataType::UInt32, "test.a")
2588                    .add(out_ref_col(DataType::UInt32, "test.b"))
2589                    .eq(col("sq.a").add(col("sq.b")))
2590                    .and(col("sq.a").add(lit(1u32)).eq(col("sq.b"))),
2591            )?
2592            .project(vec![col("c") * lit(2u32)])?
2593            .build()?;
2594
2595        let plan = LogicalPlanBuilder::from(table_scan)
2596            .filter(in_subquery(col("c") + lit(1u32), Arc::new(subquery)))?
2597            .project(vec![col("test.b")])?
2598            .build()?;
2599
2600        assert_optimized_plan_equal!(
2601            plan,
2602            @r"
2603        Projection: test.b [b:UInt32]
2604          LeftSemi Join:  Filter: test.c + UInt32(1) = __correlated_sq_1.sq.c * UInt32(2) AND test.a + test.b = __correlated_sq_1.a + __correlated_sq_1.b [a:UInt32, b:UInt32, c:UInt32]
2605            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2606            SubqueryAlias: __correlated_sq_1 [sq.c * UInt32(2):UInt32, a:UInt32, b:UInt32]
2607              Projection: sq.c * UInt32(2), sq.a, sq.b [sq.c * UInt32(2):UInt32, a:UInt32, b:UInt32]
2608                Filter: sq.a + UInt32(1) = sq.b [a:UInt32, b:UInt32, c:UInt32]
2609                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
2610        "
2611        )
2612    }
2613
2614    #[test]
2615    fn two_in_subquery_with_outer_filter() -> Result<()> {
2616        let table_scan = test_table_scan()?;
2617        let subquery_scan1 = test_table_scan_with_name("sq1")?;
2618        let subquery_scan2 = test_table_scan_with_name("sq2")?;
2619
2620        let subquery1 = LogicalPlanBuilder::from(subquery_scan1)
2621            .filter(out_ref_col(DataType::UInt32, "test.a").gt(col("sq1.a")))?
2622            .project(vec![col("c") * lit(2u32)])?
2623            .build()?;
2624
2625        let subquery2 = LogicalPlanBuilder::from(subquery_scan2)
2626            .filter(out_ref_col(DataType::UInt32, "test.a").gt(col("sq2.a")))?
2627            .project(vec![col("c") * lit(2u32)])?
2628            .build()?;
2629
2630        let plan = LogicalPlanBuilder::from(table_scan)
2631            .filter(
2632                in_subquery(col("c") + lit(1u32), Arc::new(subquery1)).and(
2633                    in_subquery(col("c") * lit(2u32), Arc::new(subquery2))
2634                        .and(col("test.c").gt(lit(1u32))),
2635                ),
2636            )?
2637            .project(vec![col("test.b")])?
2638            .build()?;
2639
2640        assert_optimized_plan_equal!(
2641            plan,
2642            @r"
2643        Projection: test.b [b:UInt32]
2644          Filter: test.c > UInt32(1) [a:UInt32, b:UInt32, c:UInt32]
2645            LeftSemi Join:  Filter: test.c * UInt32(2) = __correlated_sq_2.sq2.c * UInt32(2) AND test.a > __correlated_sq_2.a [a:UInt32, b:UInt32, c:UInt32]
2646              LeftSemi Join:  Filter: test.c + UInt32(1) = __correlated_sq_1.sq1.c * UInt32(2) AND test.a > __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
2647                TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2648                SubqueryAlias: __correlated_sq_1 [sq1.c * UInt32(2):UInt32, a:UInt32]
2649                  Projection: sq1.c * UInt32(2), sq1.a [sq1.c * UInt32(2):UInt32, a:UInt32]
2650                    TableScan: sq1 [a:UInt32, b:UInt32, c:UInt32]
2651              SubqueryAlias: __correlated_sq_2 [sq2.c * UInt32(2):UInt32, a:UInt32]
2652                Projection: sq2.c * UInt32(2), sq2.a [sq2.c * UInt32(2):UInt32, a:UInt32]
2653                  TableScan: sq2 [a:UInt32, b:UInt32, c:UInt32]
2654        "
2655        )
2656    }
2657
2658    #[test]
2659    fn in_subquery_with_same_table() -> Result<()> {
2660        let outer_scan = test_table_scan()?;
2661        let subquery_scan = test_table_scan()?;
2662        let subquery = LogicalPlanBuilder::from(subquery_scan)
2663            .filter(col("test.a").gt(col("test.b")))?
2664            .project(vec![col("c")])?
2665            .build()?;
2666
2667        let plan = LogicalPlanBuilder::from(outer_scan)
2668            .filter(in_subquery(col("test.a"), Arc::new(subquery)))?
2669            .project(vec![col("test.b")])?
2670            .build()?;
2671
2672        // Subquery and outer query refer to the same table.
2673        assert_optimized_plan_equal!(
2674            plan,
2675            @r"
2676        Projection: test.b [b:UInt32]
2677          LeftSemi Join:  Filter: test.a = __correlated_sq_1.c [a:UInt32, b:UInt32, c:UInt32]
2678            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2679            SubqueryAlias: __correlated_sq_1 [c:UInt32]
2680              Projection: test.c [c:UInt32]
2681                Filter: test.a > test.b [a:UInt32, b:UInt32, c:UInt32]
2682                  TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2683        "
2684        )
2685    }
2686
2687    #[test]
2688    fn in_subquery_correlated_with_same_table() -> Result<()> {
2689        let outer_scan = test_table_scan()?;
2690        let subquery_scan = test_table_scan()?;
2691        let subquery = LogicalPlanBuilder::from(subquery_scan)
2692            .filter(out_ref_col(DataType::UInt32, "test.a").gt(col("test.a")))?
2693            .project(vec![col("c")])?
2694            .build()?;
2695
2696        let plan = LogicalPlanBuilder::from(outer_scan)
2697            .filter(in_subquery(col("test.b"), Arc::new(subquery)))?
2698            .project(vec![col("test.b")])?
2699            .build()?;
2700
2701        // The outer `test.a` and the subquery's `test.a` stay apart in the join filter.
2702        assert_optimized_plan_equal!(
2703            plan,
2704            @r"
2705        Projection: test.b [b:UInt32]
2706          LeftSemi Join:  Filter: test.b = __correlated_sq_1.c AND test.a > __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
2707            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2708            SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
2709              Projection: test.c, test.a [c:UInt32, a:UInt32]
2710                TableScan: test [a:UInt32, b:UInt32, c:UInt32]
2711        "
2712        )
2713    }
2714
2715    /// Test for multiple exists subqueries in the same filter expression
2716    #[test]
2717    fn multiple_exists_subqueries() -> Result<()> {
2718        let orders = Arc::new(
2719            LogicalPlanBuilder::from(scan_tpch_table("orders"))
2720                .filter(
2721                    col("orders.o_custkey")
2722                        .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
2723                )?
2724                .project(vec![col("orders.o_custkey")])?
2725                .build()?,
2726        );
2727
2728        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
2729            .filter(exists(Arc::clone(&orders)).and(exists(orders)))?
2730            .project(vec![col("customer.c_custkey")])?
2731            .build()?;
2732
2733        assert_optimized_plan_equal!(
2734            plan,
2735            @r"
2736        Projection: customer.c_custkey [c_custkey:Int64]
2737          LeftSemi Join:  Filter: __correlated_sq_2.o_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8]
2738            LeftSemi Join:  Filter: __correlated_sq_1.o_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8]
2739              TableScan: customer [c_custkey:Int64, c_name:Utf8]
2740              SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
2741                Projection: orders.o_custkey [o_custkey:Int64]
2742                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2743            SubqueryAlias: __correlated_sq_2 [o_custkey:Int64]
2744              Projection: orders.o_custkey [o_custkey:Int64]
2745                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2746        "
2747        )
2748    }
2749
2750    /// Test recursive correlated subqueries
2751    #[test]
2752    fn recursive_exists_subqueries() -> Result<()> {
2753        let lineitem = Arc::new(
2754            LogicalPlanBuilder::from(scan_tpch_table("lineitem"))
2755                .filter(
2756                    col("lineitem.l_orderkey")
2757                        .eq(out_ref_col(DataType::Int64, "orders.o_orderkey")),
2758                )?
2759                .project(vec![col("lineitem.l_orderkey")])?
2760                .build()?,
2761        );
2762
2763        let orders = Arc::new(
2764            LogicalPlanBuilder::from(scan_tpch_table("orders"))
2765                .filter(
2766                    exists(lineitem).and(
2767                        col("orders.o_custkey")
2768                            .eq(out_ref_col(DataType::Int64, "customer.c_custkey")),
2769                    ),
2770                )?
2771                .project(vec![col("orders.o_custkey")])?
2772                .build()?,
2773        );
2774
2775        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
2776            .filter(exists(orders))?
2777            .project(vec![col("customer.c_custkey")])?
2778            .build()?;
2779
2780        assert_optimized_plan_equal!(
2781            plan,
2782            @r"
2783        Projection: customer.c_custkey [c_custkey:Int64]
2784          LeftSemi Join:  Filter: __correlated_sq_2.o_custkey = customer.c_custkey [c_custkey:Int64, c_name:Utf8]
2785            TableScan: customer [c_custkey:Int64, c_name:Utf8]
2786            SubqueryAlias: __correlated_sq_2 [o_custkey:Int64]
2787              Projection: orders.o_custkey [o_custkey:Int64]
2788                LeftSemi Join:  Filter: __correlated_sq_1.l_orderkey = orders.o_orderkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2789                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2790                  SubqueryAlias: __correlated_sq_1 [l_orderkey:Int64]
2791                    Projection: lineitem.l_orderkey [l_orderkey:Int64]
2792                      TableScan: lineitem [l_orderkey:Int64, l_partkey:Int64, l_suppkey:Int64, l_linenumber:Int32, l_quantity:Float64, l_extendedprice:Float64]
2793        "
2794        )
2795    }
2796
2797    /// Test for correlated exists subquery filter with additional subquery filters
2798    #[test]
2799    fn exists_subquery_with_subquery_filters() -> Result<()> {
2800        let sq = Arc::new(
2801            LogicalPlanBuilder::from(scan_tpch_table("orders"))
2802                .filter(
2803                    out_ref_col(DataType::Int64, "customer.c_custkey")
2804                        .eq(col("orders.o_custkey"))
2805                        .and(col("o_orderkey").eq(lit(1))),
2806                )?
2807                .project(vec![col("orders.o_custkey")])?
2808                .build()?,
2809        );
2810
2811        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
2812            .filter(exists(sq))?
2813            .project(vec![col("customer.c_custkey")])?
2814            .build()?;
2815
2816        assert_optimized_plan_equal!(
2817            plan,
2818            @r"
2819        Projection: customer.c_custkey [c_custkey:Int64]
2820          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
2821            TableScan: customer [c_custkey:Int64, c_name:Utf8]
2822            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
2823              Projection: orders.o_custkey [o_custkey:Int64]
2824                Filter: orders.o_orderkey = Int32(1) [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2825                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2826        "
2827        )
2828    }
2829
2830    #[test]
2831    fn exists_subquery_no_cols() -> Result<()> {
2832        let sq = Arc::new(
2833            LogicalPlanBuilder::from(scan_tpch_table("orders"))
2834                .filter(out_ref_col(DataType::Int64, "customer.c_custkey").eq(lit(1u32)))?
2835                .project(vec![col("orders.o_custkey")])?
2836                .build()?,
2837        );
2838
2839        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
2840            .filter(exists(sq))?
2841            .project(vec![col("customer.c_custkey")])?
2842            .build()?;
2843
2844        // Other rule will pushdown `customer.c_custkey = 1`,
2845        assert_optimized_plan_equal!(
2846            plan,
2847            @r"
2848        Projection: customer.c_custkey [c_custkey:Int64]
2849          LeftSemi Join:  Filter: customer.c_custkey = UInt32(1) [c_custkey:Int64, c_name:Utf8]
2850            TableScan: customer [c_custkey:Int64, c_name:Utf8]
2851            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
2852              Projection: orders.o_custkey [o_custkey:Int64]
2853                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2854        "
2855        )
2856    }
2857
2858    /// Test for exists subquery with both columns in schema
2859    #[test]
2860    fn exists_subquery_with_no_correlated_cols() -> Result<()> {
2861        let sq = Arc::new(
2862            LogicalPlanBuilder::from(scan_tpch_table("orders"))
2863                .filter(col("orders.o_custkey").eq(col("orders.o_custkey")))?
2864                .project(vec![col("orders.o_custkey")])?
2865                .build()?,
2866        );
2867
2868        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
2869            .filter(exists(sq))?
2870            .project(vec![col("customer.c_custkey")])?
2871            .build()?;
2872
2873        assert_optimized_plan_equal!(
2874            plan,
2875            @r"
2876        Projection: customer.c_custkey [c_custkey:Int64]
2877          LeftSemi Join:  Filter: Boolean(true) [c_custkey:Int64, c_name:Utf8]
2878            TableScan: customer [c_custkey:Int64, c_name:Utf8]
2879            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
2880              Projection: orders.o_custkey [o_custkey:Int64]
2881                Filter: orders.o_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2882                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2883        "
2884        )
2885    }
2886
2887    /// Test for correlated exists subquery not equal
2888    #[test]
2889    fn exists_subquery_where_not_eq() -> Result<()> {
2890        let sq = Arc::new(
2891            LogicalPlanBuilder::from(scan_tpch_table("orders"))
2892                .filter(
2893                    out_ref_col(DataType::Int64, "customer.c_custkey")
2894                        .not_eq(col("orders.o_custkey")),
2895                )?
2896                .project(vec![col("orders.o_custkey")])?
2897                .build()?,
2898        );
2899
2900        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
2901            .filter(exists(sq))?
2902            .project(vec![col("customer.c_custkey")])?
2903            .build()?;
2904
2905        assert_optimized_plan_equal!(
2906            plan,
2907            @r"
2908        Projection: customer.c_custkey [c_custkey:Int64]
2909          LeftSemi Join:  Filter: customer.c_custkey != __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
2910            TableScan: customer [c_custkey:Int64, c_name:Utf8]
2911            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
2912              Projection: orders.o_custkey [o_custkey:Int64]
2913                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2914        "
2915        )
2916    }
2917
2918    /// Test for correlated exists subquery less than
2919    #[test]
2920    fn exists_subquery_where_less_than() -> Result<()> {
2921        let sq = Arc::new(
2922            LogicalPlanBuilder::from(scan_tpch_table("orders"))
2923                .filter(
2924                    out_ref_col(DataType::Int64, "customer.c_custkey")
2925                        .lt(col("orders.o_custkey")),
2926                )?
2927                .project(vec![col("orders.o_custkey")])?
2928                .build()?,
2929        );
2930
2931        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
2932            .filter(exists(sq))?
2933            .project(vec![col("customer.c_custkey")])?
2934            .build()?;
2935
2936        assert_optimized_plan_equal!(
2937            plan,
2938            @r"
2939        Projection: customer.c_custkey [c_custkey:Int64]
2940          LeftSemi Join:  Filter: customer.c_custkey < __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
2941            TableScan: customer [c_custkey:Int64, c_name:Utf8]
2942            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
2943              Projection: orders.o_custkey [o_custkey:Int64]
2944                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2945        "
2946        )
2947    }
2948
2949    /// Test for correlated exists subquery filter with subquery disjunction
2950    #[test]
2951    fn exists_subquery_with_subquery_disjunction() -> Result<()> {
2952        let sq = Arc::new(
2953            LogicalPlanBuilder::from(scan_tpch_table("orders"))
2954                .filter(
2955                    out_ref_col(DataType::Int64, "customer.c_custkey")
2956                        .eq(col("orders.o_custkey"))
2957                        .or(col("o_orderkey").eq(lit(1))),
2958                )?
2959                .project(vec![col("orders.o_custkey")])?
2960                .build()?,
2961        );
2962
2963        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
2964            .filter(exists(sq))?
2965            .project(vec![col("customer.c_custkey")])?
2966            .build()?;
2967
2968        assert_optimized_plan_equal!(
2969            plan,
2970            @"
2971        Projection: customer.c_custkey [c_custkey:Int64]
2972          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey OR __correlated_sq_1.o_orderkey = Int32(1) [c_custkey:Int64, c_name:Utf8]
2973            TableScan: customer [c_custkey:Int64, c_name:Utf8]
2974            SubqueryAlias: __correlated_sq_1 [o_custkey:Int64, o_orderkey:Int64]
2975              Projection: orders.o_custkey, orders.o_orderkey [o_custkey:Int64, o_orderkey:Int64]
2976                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
2977        "
2978        )
2979    }
2980
2981    /// Test for correlated exists without projection
2982    #[test]
2983    fn exists_subquery_no_projection() -> Result<()> {
2984        let sq = Arc::new(
2985            LogicalPlanBuilder::from(scan_tpch_table("orders"))
2986                .filter(
2987                    out_ref_col(DataType::Int64, "customer.c_custkey")
2988                        .eq(col("orders.o_custkey")),
2989                )?
2990                .build()?,
2991        );
2992
2993        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
2994            .filter(exists(sq))?
2995            .project(vec![col("customer.c_custkey")])?
2996            .build()?;
2997
2998        assert_optimized_plan_equal!(
2999            plan,
3000            @r"
3001        Projection: customer.c_custkey [c_custkey:Int64]
3002          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
3003            TableScan: customer [c_custkey:Int64, c_name:Utf8]
3004            SubqueryAlias: __correlated_sq_1 [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
3005              TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
3006        "
3007        )
3008    }
3009
3010    /// Test for correlated exists expressions
3011    #[test]
3012    fn exists_subquery_project_expr() -> Result<()> {
3013        let sq = Arc::new(
3014            LogicalPlanBuilder::from(scan_tpch_table("orders"))
3015                .filter(
3016                    out_ref_col(DataType::Int64, "customer.c_custkey")
3017                        .eq(col("orders.o_custkey")),
3018                )?
3019                .project(vec![col("orders.o_custkey").add(lit(1))])?
3020                .build()?,
3021        );
3022
3023        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
3024            .filter(exists(sq))?
3025            .project(vec![col("customer.c_custkey")])?
3026            .build()?;
3027
3028        assert_optimized_plan_equal!(
3029            plan,
3030            @r"
3031        Projection: customer.c_custkey [c_custkey:Int64]
3032          LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
3033            TableScan: customer [c_custkey:Int64, c_name:Utf8]
3034            SubqueryAlias: __correlated_sq_1 [orders.o_custkey + Int32(1):Int64, o_custkey:Int64]
3035              Projection: orders.o_custkey + Int32(1), orders.o_custkey [orders.o_custkey + Int32(1):Int64, o_custkey:Int64]
3036                TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
3037        "
3038        )
3039    }
3040
3041    /// Test for correlated exists subquery filter with additional filters
3042    #[test]
3043    fn exists_subquery_should_support_additional_filters() -> Result<()> {
3044        let sq = Arc::new(
3045            LogicalPlanBuilder::from(scan_tpch_table("orders"))
3046                .filter(
3047                    out_ref_col(DataType::Int64, "customer.c_custkey")
3048                        .eq(col("orders.o_custkey")),
3049                )?
3050                .project(vec![col("orders.o_custkey")])?
3051                .build()?,
3052        );
3053        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
3054            .filter(exists(sq).and(col("c_custkey").eq(lit(1))))?
3055            .project(vec![col("customer.c_custkey")])?
3056            .build()?;
3057
3058        assert_optimized_plan_equal!(
3059            plan,
3060            @r"
3061        Projection: customer.c_custkey [c_custkey:Int64]
3062          Filter: customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8]
3063            LeftSemi Join:  Filter: customer.c_custkey = __correlated_sq_1.o_custkey [c_custkey:Int64, c_name:Utf8]
3064              TableScan: customer [c_custkey:Int64, c_name:Utf8]
3065              SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
3066                Projection: orders.o_custkey [o_custkey:Int64]
3067                  TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
3068        "
3069        )
3070    }
3071
3072    /// Test for correlated exists subquery filter with disjunctions
3073    #[test]
3074    fn exists_subquery_disjunction() -> Result<()> {
3075        let sq = Arc::new(
3076            LogicalPlanBuilder::from(scan_tpch_table("orders"))
3077                .filter(col("customer.c_custkey").eq(col("orders.o_custkey")))?
3078                .project(vec![col("orders.o_custkey")])?
3079                .build()?,
3080        );
3081
3082        let plan = LogicalPlanBuilder::from(scan_tpch_table("customer"))
3083            .filter(exists(sq).or(col("customer.c_custkey").eq(lit(1))))?
3084            .project(vec![col("customer.c_custkey")])?
3085            .build()?;
3086
3087        assert_optimized_plan_equal!(
3088            plan,
3089            @r"
3090        Projection: customer.c_custkey [c_custkey:Int64]
3091          Projection: customer.c_custkey, customer.c_name [c_custkey:Int64, c_name:Utf8]
3092            Filter: __correlated_sq_1.mark OR customer.c_custkey = Int32(1) [c_custkey:Int64, c_name:Utf8, mark:Boolean;N]
3093              LeftMark Join:  Filter: Boolean(true) [c_custkey:Int64, c_name:Utf8, mark:Boolean;N]
3094                TableScan: customer [c_custkey:Int64, c_name:Utf8]
3095                SubqueryAlias: __correlated_sq_1 [o_custkey:Int64]
3096                  Projection: orders.o_custkey [o_custkey:Int64]
3097                    Filter: customer.c_custkey = orders.o_custkey [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
3098                      TableScan: orders [o_orderkey:Int64, o_custkey:Int64, o_orderstatus:Utf8, o_totalprice:Float64;N]
3099        "
3100        )
3101    }
3102
3103    /// Test for correlated exists subquery filter with disjunction and count bug
3104    #[test]
3105    fn exists_subquery_disjunction_with_count_bug() -> Result<()> {
3106        let sq = Arc::new(
3107            LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
3108                .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?
3109                .aggregate(Vec::<Expr>::new(), vec![count_udaf().call(vec![])])?
3110                .build()?,
3111        );
3112
3113        let plan = LogicalPlanBuilder::from(test_table_scan()?)
3114            .filter(exists(sq).or(col("test.c").eq(lit(1))))?
3115            .project(vec![col("test.b")])?
3116            .build()?;
3117
3118        assert_optimized_plan_equal!(
3119            plan,
3120            @r"
3121        Projection: test.b [b:UInt32]
3122          Projection: test.a, test.b, test.c [a:UInt32, b:UInt32, c:UInt32]
3123            Filter: __correlated_sq_1.mark OR test.c = Int32(1) [a:UInt32, b:UInt32, c:UInt32, mark:Boolean]
3124              Projection: test.a, test.b, test.c, Boolean(true) AS mark [a:UInt32, b:UInt32, c:UInt32, mark:Boolean]
3125                Left Join:  Filter: test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32, a:UInt32;N, __always_true:Boolean;N, count():Int64;N]
3126                  TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3127                  SubqueryAlias: __correlated_sq_1 [a:UInt32, __always_true:Boolean, count():Int64]
3128                    Aggregate: groupBy=[[sq.a, Boolean(true) AS __always_true]], aggr=[[count()]] [a:UInt32, __always_true:Boolean, count():Int64]
3129                      TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
3130        "
3131        )
3132    }
3133
3134    /// Test for correlated EXISTS subquery filter
3135    #[test]
3136    fn exists_subquery_correlated() -> Result<()> {
3137        let sq = Arc::new(
3138            LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
3139                .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq.a")))?
3140                .project(vec![col("c")])?
3141                .build()?,
3142        );
3143
3144        let plan = LogicalPlanBuilder::from(test_table_scan_with_name("test")?)
3145            .filter(exists(sq))?
3146            .project(vec![col("test.c")])?
3147            .build()?;
3148
3149        assert_optimized_plan_equal!(
3150            plan,
3151            @r"
3152        Projection: test.c [c:UInt32]
3153          LeftSemi Join:  Filter: test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
3154            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3155            SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
3156              Projection: sq.c, sq.a [c:UInt32, a:UInt32]
3157                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
3158        "
3159        )
3160    }
3161
3162    /// Test for single exists subquery filter
3163    #[test]
3164    fn exists_subquery_simple() -> Result<()> {
3165        let table_scan = test_table_scan()?;
3166        let plan = LogicalPlanBuilder::from(table_scan)
3167            .filter(exists(test_subquery_with_name("sq")?))?
3168            .project(vec![col("test.b")])?
3169            .build()?;
3170
3171        assert_optimized_plan_equal!(
3172            plan,
3173            @r"
3174        Projection: test.b [b:UInt32]
3175          LeftSemi Join:  Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32]
3176            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3177            SubqueryAlias: __correlated_sq_1 [c:UInt32]
3178              Projection: sq.c [c:UInt32]
3179                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
3180        "
3181        )
3182    }
3183
3184    /// Test for single NOT exists subquery filter
3185    #[test]
3186    fn not_exists_subquery_simple() -> Result<()> {
3187        let table_scan = test_table_scan()?;
3188        let plan = LogicalPlanBuilder::from(table_scan)
3189            .filter(not_exists(test_subquery_with_name("sq")?))?
3190            .project(vec![col("test.b")])?
3191            .build()?;
3192
3193        assert_optimized_plan_equal!(
3194            plan,
3195            @r"
3196        Projection: test.b [b:UInt32]
3197          LeftAnti Join:  Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32]
3198            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3199            SubqueryAlias: __correlated_sq_1 [c:UInt32]
3200              Projection: sq.c [c:UInt32]
3201                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
3202        "
3203        )
3204    }
3205
3206    #[test]
3207    fn two_exists_subquery_with_outer_filter() -> Result<()> {
3208        let table_scan = test_table_scan()?;
3209        let subquery_scan1 = test_table_scan_with_name("sq1")?;
3210        let subquery_scan2 = test_table_scan_with_name("sq2")?;
3211
3212        let subquery1 = LogicalPlanBuilder::from(subquery_scan1)
3213            .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq1.a")))?
3214            .project(vec![col("c")])?
3215            .build()?;
3216
3217        let subquery2 = LogicalPlanBuilder::from(subquery_scan2)
3218            .filter(out_ref_col(DataType::UInt32, "test.a").eq(col("sq2.a")))?
3219            .project(vec![col("c")])?
3220            .build()?;
3221
3222        let plan = LogicalPlanBuilder::from(table_scan)
3223            .filter(
3224                exists(Arc::new(subquery1))
3225                    .and(exists(Arc::new(subquery2)).and(col("test.c").gt(lit(1u32)))),
3226            )?
3227            .project(vec![col("test.b")])?
3228            .build()?;
3229
3230        assert_optimized_plan_equal!(
3231            plan,
3232            @r"
3233        Projection: test.b [b:UInt32]
3234          Filter: test.c > UInt32(1) [a:UInt32, b:UInt32, c:UInt32]
3235            LeftSemi Join:  Filter: test.a = __correlated_sq_2.a [a:UInt32, b:UInt32, c:UInt32]
3236              LeftSemi Join:  Filter: test.a = __correlated_sq_1.a [a:UInt32, b:UInt32, c:UInt32]
3237                TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3238                SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
3239                  Projection: sq1.c, sq1.a [c:UInt32, a:UInt32]
3240                    TableScan: sq1 [a:UInt32, b:UInt32, c:UInt32]
3241              SubqueryAlias: __correlated_sq_2 [c:UInt32, a:UInt32]
3242                Projection: sq2.c, sq2.a [c:UInt32, a:UInt32]
3243                  TableScan: sq2 [a:UInt32, b:UInt32, c:UInt32]
3244        "
3245        )
3246    }
3247
3248    #[test]
3249    fn exists_subquery_expr_filter() -> Result<()> {
3250        let table_scan = test_table_scan()?;
3251        let subquery_scan = test_table_scan_with_name("sq")?;
3252        let subquery = LogicalPlanBuilder::from(subquery_scan)
3253            .filter(
3254                (lit(1u32) + col("sq.a"))
3255                    .gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),
3256            )?
3257            .project(vec![lit(1u32)])?
3258            .build()?;
3259        let plan = LogicalPlanBuilder::from(table_scan)
3260            .filter(exists(Arc::new(subquery)))?
3261            .project(vec![col("test.b")])?
3262            .build()?;
3263
3264        assert_optimized_plan_equal!(
3265            plan,
3266            @"
3267        Projection: test.b [b:UInt32]
3268          LeftSemi Join:  Filter: UInt32(1) + __correlated_sq_1.a > test.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
3269            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3270            SubqueryAlias: __correlated_sq_1 [UInt32(1):UInt32, a:UInt32]
3271              Projection: UInt32(1), sq.a [UInt32(1):UInt32, a:UInt32]
3272                TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
3273        "
3274        )
3275    }
3276
3277    #[test]
3278    fn exists_subquery_with_same_table() -> Result<()> {
3279        let outer_scan = test_table_scan()?;
3280        let subquery_scan = test_table_scan()?;
3281        let subquery = LogicalPlanBuilder::from(subquery_scan)
3282            .filter(col("test.a").gt(col("test.b")))?
3283            .project(vec![col("c")])?
3284            .build()?;
3285
3286        let plan = LogicalPlanBuilder::from(outer_scan)
3287            .filter(exists(Arc::new(subquery)))?
3288            .project(vec![col("test.b")])?
3289            .build()?;
3290
3291        // Subquery and outer query refer to the same table.
3292        assert_optimized_plan_equal!(
3293            plan,
3294            @r"
3295        Projection: test.b [b:UInt32]
3296          LeftSemi Join:  Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32]
3297            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3298            SubqueryAlias: __correlated_sq_1 [c:UInt32]
3299              Projection: test.c [c:UInt32]
3300                Filter: test.a > test.b [a:UInt32, b:UInt32, c:UInt32]
3301                  TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3302        "
3303        )
3304    }
3305
3306    #[test]
3307    fn exists_distinct_subquery() -> Result<()> {
3308        let table_scan = test_table_scan()?;
3309        let subquery_scan = test_table_scan_with_name("sq")?;
3310        let subquery = LogicalPlanBuilder::from(subquery_scan)
3311            .filter(
3312                (lit(1u32) + col("sq.a"))
3313                    .gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),
3314            )?
3315            .project(vec![col("sq.c")])?
3316            .distinct()?
3317            .build()?;
3318        let plan = LogicalPlanBuilder::from(table_scan)
3319            .filter(exists(Arc::new(subquery)))?
3320            .project(vec![col("test.b")])?
3321            .build()?;
3322
3323        assert_optimized_plan_equal!(
3324            plan,
3325            @"
3326        Projection: test.b [b:UInt32]
3327          LeftSemi Join:  Filter: UInt32(1) + __correlated_sq_1.a > test.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
3328            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3329            SubqueryAlias: __correlated_sq_1 [c:UInt32, a:UInt32]
3330              Distinct: [c:UInt32, a:UInt32]
3331                Projection: sq.c, sq.a [c:UInt32, a:UInt32]
3332                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
3333        "
3334        )
3335    }
3336
3337    #[test]
3338    fn exists_distinct_expr_subquery() -> Result<()> {
3339        let table_scan = test_table_scan()?;
3340        let subquery_scan = test_table_scan_with_name("sq")?;
3341        let subquery = LogicalPlanBuilder::from(subquery_scan)
3342            .filter(
3343                (lit(1u32) + col("sq.a"))
3344                    .gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),
3345            )?
3346            .project(vec![col("sq.b") + col("sq.c")])?
3347            .distinct()?
3348            .build()?;
3349        let plan = LogicalPlanBuilder::from(table_scan)
3350            .filter(exists(Arc::new(subquery)))?
3351            .project(vec![col("test.b")])?
3352            .build()?;
3353
3354        assert_optimized_plan_equal!(
3355            plan,
3356            @"
3357        Projection: test.b [b:UInt32]
3358          LeftSemi Join:  Filter: UInt32(1) + __correlated_sq_1.a > test.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
3359            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3360            SubqueryAlias: __correlated_sq_1 [sq.b + sq.c:UInt32, a:UInt32]
3361              Distinct: [sq.b + sq.c:UInt32, a:UInt32]
3362                Projection: sq.b + sq.c, sq.a [sq.b + sq.c:UInt32, a:UInt32]
3363                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
3364        "
3365        )
3366    }
3367
3368    #[test]
3369    fn exists_distinct_subquery_with_literal() -> Result<()> {
3370        let table_scan = test_table_scan()?;
3371        let subquery_scan = test_table_scan_with_name("sq")?;
3372        let subquery = LogicalPlanBuilder::from(subquery_scan)
3373            .filter(
3374                (lit(1u32) + col("sq.a"))
3375                    .gt(out_ref_col(DataType::UInt32, "test.a") * lit(2u32)),
3376            )?
3377            .project(vec![lit(1u32), col("sq.c")])?
3378            .distinct()?
3379            .build()?;
3380        let plan = LogicalPlanBuilder::from(table_scan)
3381            .filter(exists(Arc::new(subquery)))?
3382            .project(vec![col("test.b")])?
3383            .build()?;
3384
3385        assert_optimized_plan_equal!(
3386            plan,
3387            @"
3388        Projection: test.b [b:UInt32]
3389          LeftSemi Join:  Filter: UInt32(1) + __correlated_sq_1.a > test.a * UInt32(2) [a:UInt32, b:UInt32, c:UInt32]
3390            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3391            SubqueryAlias: __correlated_sq_1 [UInt32(1):UInt32, c:UInt32, a:UInt32]
3392              Distinct: [UInt32(1):UInt32, c:UInt32, a:UInt32]
3393                Projection: UInt32(1), sq.c, sq.a [UInt32(1):UInt32, c:UInt32, a:UInt32]
3394                  TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
3395        "
3396        )
3397    }
3398
3399    #[test]
3400    fn exists_uncorrelated_unnest() -> Result<()> {
3401        let subquery_table_source = table_source(&Schema::new(vec![Field::new(
3402            "arr",
3403            DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true))),
3404            true,
3405        )]));
3406        let subquery_table_scan =
3407            TableScanBuilder::new("sq", subquery_table_source).build()?;
3408        let subquery = LogicalPlanBuilder::table_scan(subquery_table_scan)?
3409            .unnest_column("arr")?
3410            .build()?;
3411        let table_scan = test_table_scan()?;
3412        let plan = LogicalPlanBuilder::from(table_scan)
3413            .filter(exists(Arc::new(subquery)))?
3414            .project(vec![col("test.b")])?
3415            .build()?;
3416
3417        assert_optimized_plan_equal!(
3418            plan,
3419            @r"
3420        Projection: test.b [b:UInt32]
3421          LeftSemi Join:  Filter: Boolean(true) [a:UInt32, b:UInt32, c:UInt32]
3422            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3423            SubqueryAlias: __correlated_sq_1 [arr:Int32;N]
3424              Unnest: lists[sq.arr|depth=1] structs[] [arr:Int32;N]
3425                TableScan: sq [arr:List(Int32);N]
3426        "
3427        )
3428    }
3429
3430    #[test]
3431    fn exists_correlated_unnest() -> Result<()> {
3432        let table_scan = test_table_scan()?;
3433        let subquery_table_source = table_source(&Schema::new(vec![Field::new(
3434            "a",
3435            DataType::List(Arc::new(Field::new_list_field(DataType::UInt32, true))),
3436            true,
3437        )]));
3438        let subquery_table_scan =
3439            TableScanBuilder::new("sq", subquery_table_source).build()?;
3440        let subquery = LogicalPlanBuilder::table_scan(subquery_table_scan)?
3441            .unnest_column("a")?
3442            .filter(col("a").eq(out_ref_col(DataType::UInt32, "test.b")))?
3443            .build()?;
3444        let plan = LogicalPlanBuilder::from(table_scan)
3445            .filter(exists(Arc::new(subquery)))?
3446            .project(vec![col("test.b")])?
3447            .build()?;
3448
3449        assert_optimized_plan_equal!(
3450            plan,
3451            @r"
3452        Projection: test.b [b:UInt32]
3453          LeftSemi Join:  Filter: __correlated_sq_1.a = test.b [a:UInt32, b:UInt32, c:UInt32]
3454            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3455            SubqueryAlias: __correlated_sq_1 [a:UInt32;N]
3456              Unnest: lists[sq.a|depth=1] structs[] [a:UInt32;N]
3457                TableScan: sq [a:List(UInt32);N]
3458        "
3459        )
3460    }
3461
3462    #[test]
3463    fn upper_case_ident() -> Result<()> {
3464        let fields = vec![
3465            Field::new("A", DataType::UInt32, false),
3466            Field::new("B", DataType::UInt32, false),
3467        ];
3468
3469        let schema = Schema::new(fields);
3470        let table_scan_a = table_scan(Some("\"TEST_A\""), &schema, None)?.build()?;
3471        let table_scan_b = table_scan(Some("\"TEST_B\""), &schema, None)?.build()?;
3472
3473        let subquery = LogicalPlanBuilder::from(table_scan_b)
3474            .filter(col("\"A\"").eq(out_ref_col(DataType::UInt32, "\"TEST_A\".\"A\"")))?
3475            .project(vec![lit(1)])?
3476            .build()?;
3477
3478        let plan = LogicalPlanBuilder::from(table_scan_a)
3479            .filter(exists(Arc::new(subquery)))?
3480            .project(vec![col("\"TEST_A\".\"B\"")])?
3481            .build()?;
3482
3483        assert_optimized_plan_equal!(
3484            plan,
3485            @r"
3486        Projection: TEST_A.B [B:UInt32]
3487          LeftSemi Join:  Filter: __correlated_sq_1.A = TEST_A.A [A:UInt32, B:UInt32]
3488            TableScan: TEST_A [A:UInt32, B:UInt32]
3489            SubqueryAlias: __correlated_sq_1 [Int32(1):Int32, A:UInt32]
3490              Projection: Int32(1), TEST_B.A [Int32(1):Int32, A:UInt32]
3491                TableScan: TEST_B [A:UInt32, B:UInt32]
3492        "
3493        )
3494    }
3495
3496    /// An Unnest replaces the column it unnests with the values of that
3497    /// column. A correlated filter on that column below the Unnest compares
3498    /// the whole list, so it cannot move above the Unnest.
3499    #[test]
3500    fn exists_subquery_filter_on_unnested_column() -> Result<()> {
3501        let list_type =
3502            DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true)));
3503        let schema = Schema::new(vec![
3504            Field::new("id", DataType::Int32, true),
3505            Field::new("arr", list_type.clone(), true),
3506        ]);
3507        let subquery = Arc::new(
3508            table_scan(Some("sq"), &schema, None)?
3509                .filter(col("sq.arr").eq(out_ref_col(list_type, "outer_t.arr")))?
3510                .unnest_column("arr")?
3511                .project(vec![col("sq.id")])?
3512                .build()?,
3513        );
3514        let plan = table_scan(Some("outer_t"), &schema, None)?
3515            .filter(exists(subquery))?
3516            .project(vec![col("outer_t.id")])?
3517            .build()?;
3518
3519        assert_optimized_plan_equal!(
3520            plan,
3521            @r"
3522        Projection: outer_t.id [id:Int32;N]
3523          Filter: EXISTS (<subquery>) [id:Int32;N, arr:List(Int32);N]
3524            Subquery: [id:Int32;N]
3525              Projection: sq.id [id:Int32;N]
3526                Unnest: lists[sq.arr|depth=1] structs[] [id:Int32;N, arr:Int32;N]
3527                  Filter: sq.arr = outer_ref(outer_t.arr) [id:Int32;N, arr:List(Int32);N]
3528                    TableScan: sq [id:Int32;N, arr:List(Int32);N]
3529            TableScan: outer_t [id:Int32;N, arr:List(Int32);N]
3530        "
3531        )
3532    }
3533
3534    #[test]
3535    fn exists_subquery_filter_above_correlated_derived_table() -> Result<()> {
3536        let sq_scan = test_table_scan_with_name("sq")?;
3537        let derived = LogicalPlanBuilder::from(sq_scan)
3538            .filter(col("sq.c").eq(out_ref_col(DataType::UInt32, "test.a")))?
3539            .project(vec![col("sq.c")])?
3540            .alias("t")?
3541            .build()?;
3542        let subquery = LogicalPlanBuilder::from(derived)
3543            .filter(out_ref_col(DataType::UInt32, "test.b").gt(lit(0u32)))?
3544            .project(vec![lit(1)])?
3545            .build()?;
3546
3547        let outer_scan = test_table_scan()?;
3548        let plan = LogicalPlanBuilder::from(outer_scan)
3549            .filter(exists(Arc::new(subquery)))?
3550            .project(vec![col("test.a")])?
3551            .build()?;
3552
3553        assert_optimized_plan_equal!(
3554            plan,
3555            @r"
3556        Projection: test.a [a:UInt32]
3557          LeftSemi Join:  Filter: __correlated_sq_1.c = test.a AND test.b > UInt32(0) [a:UInt32, b:UInt32, c:UInt32]
3558            TableScan: test [a:UInt32, b:UInt32, c:UInt32]
3559            SubqueryAlias: __correlated_sq_1 [Int32(1):Int32, c:UInt32]
3560              Projection: Int32(1), t.c [Int32(1):Int32, c:UInt32]
3561                SubqueryAlias: t [c:UInt32]
3562                  Projection: sq.c [c:UInt32]
3563                    TableScan: sq [a:UInt32, b:UInt32, c:UInt32]
3564        "
3565        )
3566    }
3567}