Skip to main content

datafusion_optimizer/
decorrelate.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//! [`PullUpCorrelatedExpr`] converts correlated subqueries to `Joins`
6
7use std::collections::BTreeSet;
8use std::sync::Arc;
9
10use crate::push_down_filter::lr_is_preserved;
11use crate::simplify_expressions::ExprSimplifier;
12use crate::utils::replace_qualified_name;
13
14use datafusion_common::nested_struct::is_injective_cast;
15use datafusion_common::tree_node::{
16    Transformed, TransformedResult, TreeNode, TreeNodeRecursion, TreeNodeRewriter,
17};
18use datafusion_common::utils::has_float_leaf;
19use datafusion_common::{
20    Column, DFSchema, DFSchemaRef, HashMap, Result, ScalarValue, assert_or_internal_err,
21    plan_err,
22};
23use datafusion_expr::expr::{Alias, GroupingSet};
24use datafusion_expr::expr_rewriter::strip_outer_reference;
25use datafusion_expr::logical_plan::{Join, JoinType};
26use datafusion_expr::simplify::SimplifyContext;
27use datafusion_expr::utils::{collect_subquery_cols, conjunction, split_conjunction};
28use datafusion_expr::{
29    Aggregate, BinaryExpr, Cast, Distinct, EmptyRelation, Expr, ExprSchemable, FetchType,
30    LogicalPlan, LogicalPlanBuilder, MaterializedCte, MaterializedCtePlan, Operator,
31    SkipType, Window, expr, lit,
32};
33
34/// This struct rewrite the sub query plan by pull up the correlated
35/// expressions(contains outer reference columns) from the inner subquery's
36/// 'Filter'. It adds the inner reference columns to the 'Projection' or
37/// 'Aggregate' of the subquery if they are missing, so that they can be
38/// evaluated by the parent operator as the join condition.
39#[derive(Debug)]
40pub struct PullUpCorrelatedExpr {
41    pub join_filters: Vec<Expr>,
42    /// mapping from the plan to its holding correlated columns
43    pub correlated_subquery_cols_map: HashMap<LogicalPlan, BTreeSet<Column>>,
44    pub in_predicate_opt: Option<Expr>,
45    /// Is this an Exists(Not Exists) SubQuery. Defaults to **FALSE**
46    pub exists_sub_query: bool,
47    /// Can the correlated expressions be pulled up. Defaults to **TRUE**
48    pub can_pull_up: bool,
49    /// Indicates if we encounter any correlated expression that can not be pulled up
50    /// above a aggregation without changing the meaning of the query.
51    can_pull_over_aggregation: bool,
52    /// Whether every correlated conjunct seen so far passes
53    /// [`is_partitionable_equality`], so a Window above them can partition by their
54    /// columns.
55    can_extend_partition_by: bool,
56    /// Do we need to handle [the count bug] during the pull up process.
57    ///
58    /// The "count bug" was described in [Optimization of Nested SQL
59    /// Queries Revisited](https://dl.acm.org/doi/pdf/10.1145/38714.38723). This bug is
60    /// not specific to the COUNT function, and it can occur with any aggregate function,
61    /// such as SUM, AVG, etc. The anomaly arises because aggregates fail to distinguish
62    /// between an empty set and null values when optimizing a correlated query as a join.
63    /// Here, we use "the count bug" to refer to all such cases.
64    ///
65    /// [the count bug]: https://github.com/apache/datafusion/issues/10553
66    pub need_handle_count_bug: bool,
67    /// mapping from the plan to its expressions' evaluation result on empty batch
68    pub collected_count_expr_map: HashMap<LogicalPlan, ExprResultMap>,
69    /// pull up having expr, which must be evaluated after the Join
70    pub pull_up_having_expr: Option<Expr>,
71    /// whether we have converted a scalar aggregation into a group aggregation. When unnesting
72    /// lateral joins, we need to produce a left outer join in such cases.
73    ///
74    /// An `Aggregate` above stops the pull up when this is set. `f_up` visits
75    /// the aggregate that sets it before any node above.
76    pub pulled_up_scalar_agg: bool,
77    /// Every correlated conjunct that a `Filter` of the subquery applies,
78    /// before `remove_duplicated_filter` drops the ones that the `IN`
79    /// predicate already covers. The outer references are kept, so that a
80    /// subquery column and an outer column with the same qualified name stay
81    /// apart.
82    ///
83    /// `join_filters` holds only the conjuncts that the join still needs.
84    /// This list is what the subquery enforces on its own rows. The caller
85    /// uses it to tell if a join key can be NULL inside the scope of an outer
86    /// row: `x IN (SELECT y FROM .. WHERE y = x)` keeps every NULL `y` out of
87    /// its result, although `join_filters` no longer says so.
88    ///
89    /// The list is cleared when the pull up passes a node that can put a NULL
90    /// back into such a column: an outer join, a union or a grouping set.
91    pub correlated_filters: Vec<Expr>,
92    /// Columns each node on the path from the subquery's root to the node
93    /// [`Self::f_down`]/[`Self::f_up`] is currently visiting reads in its own
94    /// expressions: one entry per node on that path, pushed in `f_down` and
95    /// popped in `f_up`. When `f_up` visits an `Aggregate`, this holds every
96    /// node strictly above it - its own entry is popped first - so a
97    /// grouping set that omits a correlated column can tell whether
98    /// something above it reads the column the pull up would fill in.
99    column_refs_above: Vec<BTreeSet<Column>>,
100    /// For each node on that same path, whether it returns rows based only on
101    /// whether its input has rows (see [`depends_only_on_input_having_rows`]). One
102    /// entry per node, pushed and popped with [`Self::column_refs_above`].
103    /// `f_down`'s `Limit` arm reads it: a `Limit` is only dropped from an
104    /// `EXISTS` subquery when this holds for every node above it.
105    depends_only_on_input_having_rows_above: Vec<bool>,
106}
107
108impl Default for PullUpCorrelatedExpr {
109    fn default() -> Self {
110        Self::new()
111    }
112}
113
114impl PullUpCorrelatedExpr {
115    pub fn new() -> Self {
116        Self {
117            join_filters: vec![],
118            correlated_subquery_cols_map: HashMap::new(),
119            in_predicate_opt: None,
120            exists_sub_query: false,
121            can_pull_up: true,
122            can_pull_over_aggregation: true,
123            can_extend_partition_by: true,
124            need_handle_count_bug: false,
125            collected_count_expr_map: HashMap::new(),
126            pull_up_having_expr: None,
127            pulled_up_scalar_agg: false,
128            correlated_filters: Vec::new(),
129            column_refs_above: Vec::new(),
130            depends_only_on_input_having_rows_above: Vec::new(),
131        }
132    }
133
134    /// Set if we need to handle [the count bug] during the pull up process
135    ///
136    /// [the count bug]: https://github.com/apache/datafusion/issues/10553
137    pub fn with_need_handle_count_bug(mut self, need_handle_count_bug: bool) -> Self {
138        self.need_handle_count_bug = need_handle_count_bug;
139        self
140    }
141
142    /// Set the in_predicate_opt
143    pub fn with_in_predicate_opt(mut self, in_predicate_opt: Option<Expr>) -> Self {
144        self.in_predicate_opt = in_predicate_opt;
145        self
146    }
147
148    /// Set if this is an Exists(Not Exists) SubQuery
149    pub fn with_exists_sub_query(mut self, exists_sub_query: bool) -> Self {
150        self.exists_sub_query = exists_sub_query;
151        self
152    }
153}
154
155/// The outcome of trying to fold the pull up's columns into a grouping set
156/// `Aggregate`. See [`PullUpCorrelatedExpr::grouping_sets_pull_up_outcome`].
157#[derive(Debug, PartialEq, Eq)]
158enum GroupingSetsPullUp {
159    /// Every set already groups by the columns; the aggregate's `group_expr`
160    /// stays as it is.
161    NoColumnsToAdd,
162    /// Some set leaves a required column out, but extending every set with it
163    /// changes nothing the rest of the query can observe.
164    SafeToExtend,
165    /// Some set leaves a required column out, and extending every set with it
166    /// would change what the query returns.
167    Unsafe,
168}
169
170/// Used to indicate the unmatched rows from the inner(subquery) table after the left out Join
171/// This is used to handle [the Count bug]
172///
173/// [the Count bug]: https://github.com/apache/datafusion/issues/10553
174pub const UN_MATCHED_ROW_INDICATOR: &str = "__always_true";
175
176/// Mapping from expr display name to its evaluation result on empty record
177/// batch (for example: 'count(*)' is 'ScalarValue(0)', 'count(*) + 2' is
178/// 'ScalarValue(2)')
179pub type ExprResultMap = HashMap<String, Expr>;
180
181impl TreeNodeRewriter for PullUpCorrelatedExpr {
182    type Node = LogicalPlan;
183
184    fn f_down(&mut self, plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
185        // Tracks the columns this node's own expressions read, so a
186        // descendant `Aggregate` can later tell what reads above it. Popped
187        // by the matching `f_up` call for this same node.
188        let mut column_refs = BTreeSet::new();
189        for expr in plan.expressions() {
190            column_refs.extend(expr.column_refs().into_iter().cloned());
191        }
192        self.column_refs_above.push(column_refs);
193        self.depends_only_on_input_having_rows_above
194            .push(depends_only_on_input_having_rows(&plan));
195
196        // This match is exhaustive on purpose. A correlated filter moves above
197        // a node only when the node is known to keep the result the same. Add
198        // each new `LogicalPlan` variant to one of the groups below.
199        match plan {
200            LogicalPlan::Filter(_) => Ok(Transformed::no(plan)),
201            // Subquery nodes are scope boundaries for correlation. A nested
202            // Subquery's outer references belong to a different decorrelation
203            // level and must not be pulled up into the current scope.
204            LogicalPlan::Subquery(_) => {
205                Ok(Transformed::new(plan, false, TreeNodeRecursion::Jump))
206            }
207            LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(ref cte))
208                if !cte.cte.all_out_ref_exprs().is_empty() =>
209            {
210                // A correlated body would have to run once per outer row.
211                Ok(self.stop_pull_up(plan))
212            }
213            LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
214                // Only the continuation can hold correlated expressions. Rewrite
215                // it alone, so that the body shared by every scan keeps its schema.
216                let continuation =
217                    Arc::unwrap_or_clone(cte.continuation).rewrite(self)?;
218                Ok(Transformed::new(
219                    LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
220                        MaterializedCte {
221                            continuation: Arc::new(continuation.data),
222                            ..cte
223                        },
224                    )),
225                    continuation.transformed,
226                    TreeNodeRecursion::Jump,
227                ))
228            }
229            // A correlated filter can only move above a join from a side whose
230            // rows the join preserves. Below the side an outer join fills with
231            // NULLs, the filter decides which rows are unmatched, so pulling it
232            // above the join changes the result. The side a semi, anti or mark
233            // join does not output cannot give its columns to a pulled up
234            // filter either.
235            LogicalPlan::Join(ref join) if !correlated_inputs_are_preserved(join) => {
236                Ok(self.stop_pull_up(plan))
237            }
238            // An ASOF join keeps each left row once, so a filter on the left
239            // side can move above it. A filter on the right side selects the
240            // rows the join can match, so it must stay below the join.
241            LogicalPlan::AsOfJoin(ref join) if holds_outer_reference(&join.right) => {
242                Ok(self.stop_pull_up(plan))
243            }
244            // An Unnest replaces the column it unnests with the values of that
245            // column, so a filter on it means something else above the
246            // Unnest. The output column loses its qualifier, so compare names.
247            // The SQL planner unnests a new `__unnest_placeholder` column and
248            // passes the original column through, so this only stops plans
249            // built with `unnest_column` and similar.
250            LogicalPlan::Unnest(ref unnest)
251                if correlated_filter_columns(&unnest.input).iter().any(|col| {
252                    unnest
253                        .exec_columns
254                        .iter()
255                        .any(|exec_col| exec_col.name == col.name)
256                }) =>
257            {
258                Ok(self.stop_pull_up(plan))
259            }
260            // A correlated filter cannot move out of one input of a Union, and
261            // `f_up` does not add its columns to a Sort or an Extension, so no
262            // correlated filter may be below these nodes.
263            LogicalPlan::Union(_) | LogicalPlan::Sort(_) | LogicalPlan::Extension(_) => {
264                if holds_outer_reference(&plan) {
265                    Ok(self.stop_pull_up(plan))
266                } else {
267                    Ok(Transformed::no(plan))
268                }
269            }
270            // For EXISTS only emptiness matters, so `f_down` removes or
271            // replaces a Limit over a correlated filter where it can. Any other
272            // Limit keeps the correlated filters below it.
273            LogicalPlan::Limit(ref limit) => {
274                if !holds_outer_reference(&plan) {
275                    return Ok(Transformed::no(plan));
276                }
277                if !self.exists_sub_query {
278                    return Ok(self.stop_pull_up(plan));
279                }
280                // A `LIMIT 0` always gives an empty input, whatever is
281                // above it, so it becomes an empty relation.
282                let fetch = limit.get_fetch_type()?;
283                if matches!(fetch, FetchType::Literal(Some(0))) {
284                    return Ok(Transformed::yes(LogicalPlan::EmptyRelation(
285                        EmptyRelation {
286                            produce_one_row: false,
287                            schema: Arc::clone(limit.input.schema()),
288                        },
289                    )));
290                }
291                // `EXISTS` asks whether the whole subquery returns a row, not
292                // whether this `Limit` does. If a node above the `Limit` looks
293                // at which rows it gets, such as a `Filter` or the `HAVING` in
294                // https://github.com/apache/datafusion/issues/26629, removing
295                // the `Limit` hands it different rows and can change the
296                // answer, so the `Limit` has to stay.
297                let (_, above) = self
298                    .depends_only_on_input_having_rows_above
299                    .split_last()
300                    .expect("f_down pushed this Limit's own entry");
301                if !above.iter().all(|follows| *follows) {
302                    return Ok(self.stop_pull_up(plan));
303                }
304
305                match (limit.get_skip_type()?, fetch) {
306                    (SkipType::Literal(0), FetchType::Literal(_)) => {
307                        // The rewriter does not call `f_down` on the returned
308                        // node, so do it here. This call pushes its own
309                        // entry onto `column_refs_above`; pop the one this
310                        // call pushed for the `Limit` itself first; only one
311                        // `f_up` call reaches this tree position once `Limit`
312                        // is gone, so only one entry must remain pushed.
313                        self.column_refs_above.pop();
314                        self.depends_only_on_input_having_rows_above.pop();
315                        let mut t = self.f_down((*limit.input).clone())?;
316                        t.transformed = true;
317                        Ok(t)
318                    }
319                    _ => Ok(self.stop_pull_up(plan)),
320                }
321            }
322            // A correlated filter below these nodes can move above them. The
323            // node itself must not hold an outer reference, because only a
324            // Filter gives its outer references to the join.
325            // - `f_up` adds the columns the pulled up filter needs to a
326            //   Projection or an Aggregate, and checks that the filter can move
327            //   above an Aggregate.
328            // - A `DISTINCT` shares the exemption of an Aggregate without
329            //   aggregate functions: its output takes the columns the node
330            //   below it adds, so they become part of its keys. This is only
331            //   right when the pulled up filter fixes those columns for each
332            //   outer row. A non-equality filter can return duplicates, see
333            //   https://github.com/apache/datafusion/issues/25808.
334            // - A Window keeps or drops whole partitions when the filter reads
335            //   only its `PARTITION BY` columns. For other filters, `f_up` adds
336            //   the columns of a column equality to `PARTITION BY` and keeps
337            //   the subquery correlated in the remaining cases.
338            // - An Unnest maps each input row to its own output rows, so a
339            //   filter on a column it passes through keeps the same rows.
340            //   The arm above checks that the filter does not read an unnested
341            //   column.
342            LogicalPlan::Projection(_)
343            | LogicalPlan::Aggregate(_)
344            | LogicalPlan::Distinct(Distinct::All(_))
345            | LogicalPlan::Window(_)
346            | LogicalPlan::Unnest(_)
347            | LogicalPlan::Join(_)
348            | LogicalPlan::AsOfJoin(_)
349            | LogicalPlan::Repartition(_)
350            | LogicalPlan::SubqueryAlias(_)
351            | LogicalPlan::TableScan(_)
352            | LogicalPlan::EmptyRelation(_)
353            | LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_))
354            | LogicalPlan::Values(_) => {
355                if plan.contains_outer_reference() {
356                    // the unsupported cases, the plan expressions contain out
357                    // reference columns
358                    Ok(self.stop_pull_up(plan))
359                } else {
360                    Ok(Transformed::no(plan))
361                }
362            }
363            // A correlated filter below these nodes cannot move above them:
364            // - `DISTINCT ON` keeps the first row of each group, so the filter
365            //   changes which row is first.
366            // - A RecursiveQuery repeats its recursive term.
367            // - The other nodes are not queries and are not in a subquery.
368            LogicalPlan::Distinct(Distinct::On(_))
369            | LogicalPlan::RecursiveQuery(_)
370            | LogicalPlan::Statement(_)
371            | LogicalPlan::Explain(_)
372            | LogicalPlan::Analyze(_)
373            | LogicalPlan::Dml(_)
374            | LogicalPlan::Ddl(_)
375            | LogicalPlan::Copy(_)
376            | LogicalPlan::Show(_) => {
377                if holds_outer_reference(&plan) {
378                    Ok(self.stop_pull_up(plan))
379                } else {
380                    Ok(Transformed::no(plan))
381                }
382            }
383        }
384    }
385
386    fn f_up(&mut self, plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
387        // Pop this node's own entry, pushed by the matching `f_down` call, so
388        // `column_refs_above` holds only the nodes strictly above `plan`.
389        self.column_refs_above.pop();
390        self.depends_only_on_input_having_rows_above.pop();
391
392        // A node that null-extends or regroups rows can put a NULL back into
393        // a column that a correlated filter below it rejected, so the filters
394        // recorded so far no longer bound what the subquery returns.
395        if !self.correlated_filters.is_empty() && may_reintroduce_nulls(&plan) {
396            self.correlated_filters.clear();
397        }
398        let subquery_schema = plan.schema();
399        match &plan {
400            LogicalPlan::Filter(plan_filter) => {
401                let subquery_filter_exprs = split_conjunction(&plan_filter.predicate);
402                for &expr in subquery_filter_exprs.iter().filter(|e| e.contains_outer()) {
403                    self.can_pull_over_aggregation &= can_pullup_over_aggregation(expr);
404                    self.can_extend_partition_by &=
405                        is_partitionable_equality(expr, plan_filter.input.schema());
406                }
407                for expr in &subquery_filter_exprs {
408                    if expr.contains_outer() && !self.correlated_filters.contains(expr) {
409                        self.correlated_filters.push((*expr).clone());
410                    }
411                }
412                let (mut join_filters, subquery_filters) =
413                    find_join_exprs(subquery_filter_exprs);
414                if let Some(in_predicate) = &self.in_predicate_opt {
415                    // in_predicate may be already included in the join filters, remove it from the join filters first.
416                    join_filters = remove_duplicated_filter(join_filters, in_predicate)?;
417                }
418                let correlated_subquery_cols =
419                    collect_subquery_cols(&join_filters, subquery_schema)?;
420                for expr in join_filters {
421                    if !self.join_filters.contains(&expr) {
422                        self.join_filters.push(expr)
423                    }
424                }
425
426                let mut expr_result_map_for_count_bug = HashMap::new();
427                let pull_up_expr_opt = if let Some(expr_result_map) =
428                    self.collected_count_expr_map.get(&*plan_filter.input)
429                {
430                    if let Some(expr) = conjunction(subquery_filters.clone()) {
431                        filter_exprs_evaluation_result_on_empty_batch(
432                            &expr,
433                            Arc::clone(plan_filter.input.schema()),
434                            expr_result_map,
435                            &mut expr_result_map_for_count_bug,
436                        )?
437                    } else {
438                        None
439                    }
440                } else {
441                    None
442                };
443
444                if self.exists_sub_query
445                    && self.pull_up_having_expr.is_some()
446                    && let Some(expr) = conjunction(subquery_filters.clone())
447                {
448                    let unqualified_expr = expr
449                        .transform_up(|e| {
450                            if let Expr::Column(Column { name, .. }) = &e {
451                                Ok(Transformed::yes(Expr::Column(
452                                    Column::new_unqualified(name),
453                                )))
454                            } else {
455                                Ok(Transformed::no(e))
456                            }
457                        })
458                        .data()?;
459                    let combined = match self.pull_up_having_expr.take() {
460                        Some(existing) => existing.and(unqualified_expr),
461                        None => unqualified_expr,
462                    };
463                    self.pull_up_having_expr = Some(combined);
464                    let new_plan =
465                        LogicalPlanBuilder::from((*plan_filter.input).clone()).build()?;
466                    let mut carried_correlated_cols = correlated_subquery_cols;
467                    if let Some(existing) =
468                        self.correlated_subquery_cols_map.get(&*plan_filter.input)
469                    {
470                        carried_correlated_cols.extend(existing.iter().cloned());
471                    }
472                    self.correlated_subquery_cols_map
473                        .insert(new_plan.clone(), carried_correlated_cols);
474                    if !expr_result_map_for_count_bug.is_empty() {
475                        self.collected_count_expr_map
476                            .insert(new_plan.clone(), expr_result_map_for_count_bug);
477                    } else if let Some(input_map) = self
478                        .collected_count_expr_map
479                        .get(&*plan_filter.input)
480                        .cloned()
481                    {
482                        self.collected_count_expr_map
483                            .insert(new_plan.clone(), input_map);
484                    }
485                    return Ok(Transformed::yes(new_plan));
486                }
487
488                match (&pull_up_expr_opt, &self.pull_up_having_expr) {
489                    (Some(_), Some(_)) => {
490                        // Error path
491                        plan_err!("Unsupported Subquery plan")
492                    }
493                    (Some(_), None) => {
494                        self.pull_up_having_expr = pull_up_expr_opt;
495                        let new_plan =
496                            LogicalPlanBuilder::from((*plan_filter.input).clone())
497                                .build()?;
498                        self.correlated_subquery_cols_map
499                            .entry(new_plan.clone())
500                            .or_default()
501                            .extend(correlated_subquery_cols);
502                        Ok(Transformed::yes(new_plan))
503                    }
504                    (None, _) => {
505                        // if the subquery still has filter expressions, restore them.
506                        let mut plan =
507                            LogicalPlanBuilder::from((*plan_filter.input).clone());
508                        if let Some(expr) = conjunction(subquery_filters) {
509                            plan = plan.filter(expr)?
510                        }
511                        let new_plan = plan.build()?;
512                        self.correlated_subquery_cols_map
513                            .entry(new_plan.clone())
514                            .or_default()
515                            .extend(correlated_subquery_cols);
516                        Ok(Transformed::yes(new_plan))
517                    }
518                }
519            }
520            LogicalPlan::Projection(projection)
521                if self.in_predicate_opt.is_some() || !self.join_filters.is_empty() =>
522            {
523                let mut local_correlated_cols = BTreeSet::new();
524                collect_local_correlated_cols(
525                    &plan,
526                    &self.correlated_subquery_cols_map,
527                    &mut local_correlated_cols,
528                );
529                // add missing columns to Projection
530                let mut missing_exprs = self.collect_missing_exprs(
531                    &projection.expr,
532                    &local_correlated_cols,
533                    projection.input.schema(),
534                )?;
535
536                let mut expr_result_map_for_count_bug = HashMap::new();
537                if let Some(expr_result_map) =
538                    self.collected_count_expr_map.get(&*projection.input)
539                {
540                    proj_exprs_evaluation_result_on_empty_batch(
541                        &missing_exprs,
542                        projection.input.schema(),
543                        expr_result_map,
544                        &mut expr_result_map_for_count_bug,
545                    )?;
546                    if !expr_result_map_for_count_bug.is_empty() {
547                        // has count bug
548                        let un_matched_row = Expr::Column(Column::new_unqualified(
549                            UN_MATCHED_ROW_INDICATOR.to_string(),
550                        ));
551                        // add the unmatched rows indicator to the Projection expressions
552                        missing_exprs.push(un_matched_row);
553                    }
554                }
555
556                let new_plan = LogicalPlanBuilder::from((*projection.input).clone())
557                    .project(missing_exprs)?
558                    .build()?;
559                if !expr_result_map_for_count_bug.is_empty() {
560                    self.collected_count_expr_map
561                        .insert(new_plan.clone(), expr_result_map_for_count_bug);
562                }
563                Ok(Transformed::yes(new_plan))
564            }
565            LogicalPlan::Aggregate(aggregate)
566                if self.in_predicate_opt.is_some() || !self.join_filters.is_empty() =>
567            {
568                // A pulled up scalar aggregate below gives no row for unmatched
569                // outer rows, so this aggregate would see an empty input. Stop
570                // the rewrite here, since rebuilding the nodes above can fail
571                // with a schema error. See https://github.com/apache/datafusion/issues/26508
572                if self.pulled_up_scalar_agg {
573                    self.can_pull_up = false;
574                    return Ok(Transformed::new(plan, false, TreeNodeRecursion::Stop));
575                }
576                // If the aggregation is from a distinct it will not change the result for
577                // exists/in subqueries so we can still pull up all predicates.
578                let is_distinct = aggregate.aggr_expr.is_empty();
579                if !is_distinct {
580                    self.can_pull_up = self.can_pull_up && self.can_pull_over_aggregation;
581                }
582                let mut local_correlated_cols = BTreeSet::new();
583                collect_local_correlated_cols(
584                    &plan,
585                    &self.correlated_subquery_cols_map,
586                    &mut local_correlated_cols,
587                );
588                // A grouping set that omits a column the pull up adds either
589                // keeps its sets as they are (every set already groups by the
590                // column), or gains the column in every set, `ROLLUP(i.k)`
591                // (`GROUPING SETS ((i.k), ())`) becoming
592                // `GROUPING SETS ((i.k), (i.k, i.k))`. The latter loses the
593                // empty set, and with it the grand total row the subquery
594                // returns for every outer row, including the rows whose
595                // correlated filter matches nothing, so it is only safe when
596                // no set is empty and nothing reads the column the fill
597                // changes from `NULL` to the correlated value.
598                let mut missing_exprs = if aggregate
599                    .group_expr
600                    .iter()
601                    .any(|expr| matches!(expr, Expr::GroupingSet(_)))
602                {
603                    match self
604                        .grouping_sets_pull_up_outcome(aggregate, &local_correlated_cols)
605                    {
606                        GroupingSetsPullUp::NoColumnsToAdd => {
607                            // Every set already groups by them, so the sets stay as
608                            // they are. Adding the columns again would repeat them
609                            // inside every set.
610                            aggregate.group_expr.to_vec()
611                        }
612                        GroupingSetsPullUp::SafeToExtend => {
613                            // No set is empty and nothing reads the columns the
614                            // fill changes from `NULL` to the correlated value,
615                            // so extending every set is invisible to the rest of
616                            // the query.
617                            self.collect_missing_exprs(
618                                &aggregate.group_expr,
619                                &local_correlated_cols,
620                                aggregate.input.schema(),
621                            )?
622                        }
623                        GroupingSetsPullUp::Unsafe => {
624                            self.can_pull_up = false;
625                            // The rewrite still runs, the same way the
626                            // `can_pull_over_aggregation` case above does. The callers
627                            // read `can_pull_up` only after the whole rewrite has
628                            // finished, and the nodes above this one still expect the
629                            // pulled up columns in its output, so leaving them out here
630                            // would fail the rewrite with a schema error instead. They
631                            // drop this plan and keep the correlated subquery.
632                            self.collect_missing_exprs(
633                                &aggregate.group_expr,
634                                &local_correlated_cols,
635                                aggregate.input.schema(),
636                            )?
637                        }
638                    }
639                } else {
640                    // add missing columns to Aggregation's group expressions
641                    self.collect_missing_exprs(
642                        &aggregate.group_expr,
643                        &local_correlated_cols,
644                        aggregate.input.schema(),
645                    )?
646                };
647
648                // if the original group expressions are empty, need to handle the Count bug
649                let mut expr_result_map_for_count_bug = HashMap::new();
650                if self.need_handle_count_bug
651                    && aggregate.group_expr.is_empty()
652                    && !missing_exprs.is_empty()
653                {
654                    agg_exprs_evaluation_result_on_empty_batch(
655                        &aggregate.aggr_expr,
656                        aggregate.input.schema(),
657                        &mut expr_result_map_for_count_bug,
658                    )?;
659                    if !expr_result_map_for_count_bug.is_empty() {
660                        // has count bug
661                        let un_matched_row = lit(true).alias(UN_MATCHED_ROW_INDICATOR);
662                        // add the unmatched rows indicator to the Aggregation's group expressions
663                        missing_exprs.push(un_matched_row);
664                    }
665                }
666                if aggregate.group_expr.is_empty() {
667                    self.pulled_up_scalar_agg = true;
668                }
669                let new_plan = LogicalPlanBuilder::from((*aggregate.input).clone())
670                    .aggregate(missing_exprs, aggregate.aggr_expr.to_vec())?
671                    .build()?;
672                if !expr_result_map_for_count_bug.is_empty() {
673                    self.collected_count_expr_map
674                        .insert(new_plan.clone(), expr_result_map_for_count_bug);
675                }
676                Ok(Transformed::yes(new_plan))
677            }
678            LogicalPlan::SubqueryAlias(alias) => {
679                let mut local_correlated_cols = BTreeSet::new();
680                collect_local_correlated_cols(
681                    &plan,
682                    &self.correlated_subquery_cols_map,
683                    &mut local_correlated_cols,
684                );
685                let mut new_correlated_cols = BTreeSet::new();
686                for col in local_correlated_cols.iter() {
687                    new_correlated_cols
688                        .insert(Column::new(Some(alias.alias.clone()), col.name.clone()));
689                }
690
691                let new_plan = if alias.input.schema().fields().len()
692                    != alias.schema.fields().len()
693                {
694                    LogicalPlanBuilder::from((*alias.input).clone())
695                        .alias(alias.alias.clone())?
696                        .build()?
697                } else {
698                    plan.clone()
699                };
700
701                self.correlated_subquery_cols_map
702                    .insert(new_plan.clone(), new_correlated_cols);
703                if let Some(input_map) = self.collected_count_expr_map.get(&*alias.input)
704                {
705                    self.collected_count_expr_map
706                        .insert(new_plan.clone(), input_map.clone());
707                }
708
709                if new_plan != plan {
710                    Ok(Transformed::yes(new_plan))
711                } else {
712                    Ok(Transformed::no(plan))
713                }
714            }
715            LogicalPlan::Limit(limit) => {
716                if let Some(input_map) =
717                    self.collected_count_expr_map.get(&*limit.input).cloned()
718                {
719                    self.collected_count_expr_map
720                        .insert(plan.clone(), input_map);
721                }
722                Ok(Transformed::no(plan))
723            }
724            LogicalPlan::Window(window) => {
725                let mut local_correlated_cols = BTreeSet::new();
726                collect_local_correlated_cols(
727                    &plan,
728                    &self.correlated_subquery_cols_map,
729                    &mut local_correlated_cols,
730                );
731                // A filter that reads only `PARTITION BY` columns keeps or drops
732                // whole partitions, so each window function sees the same rows
733                // above it or below it. A filter on any other column changes the
734                // rows of a partition.
735                if !local_correlated_cols.is_empty()
736                    && !window
737                        .window_expr
738                        .iter()
739                        .all(|expr| partitions_by_all(expr, &local_correlated_cols))
740                {
741                    // `inner.y = outer.k` keeps the rows of one `y` value for
742                    // each outer row, so partitioning by `y` as well gives each
743                    // window function the same rows. An aggregate without
744                    // `GROUP BY` below returns a row for an outer row without
745                    // a match, which the pulled up filter would drop.
746                    if self.can_extend_partition_by && !self.pulled_up_scalar_agg {
747                        let extended =
748                            partition_window_by(window, &local_correlated_cols)?;
749                        return self.pass_through_pulled_up_cols(extended);
750                    }
751                    self.can_pull_up = false;
752                }
753                self.pass_through_pulled_up_cols(plan)
754            }
755            // `f_down` checked that the pulled up filters do not read an
756            // unnested column.
757            LogicalPlan::Unnest(_) => self.pass_through_pulled_up_cols(plan),
758            _ => Ok(Transformed::no(plan)),
759        }
760    }
761}
762
763impl PullUpCorrelatedExpr {
764    /// Keeps the correlated expressions below `plan` where they are. The caller
765    /// then keeps the subquery correlated.
766    fn stop_pull_up(&mut self, plan: LogicalPlan) -> Transformed<LogicalPlan> {
767        self.can_pull_up = false;
768        Transformed::new(plan, false, TreeNodeRecursion::Jump)
769    }
770
771    /// Rebuilds a node whose output holds every column of its input, so that
772    /// it outputs the columns the pull up added below it.
773    ///
774    /// The count bug handling of a Projection or a Filter above reads the
775    /// values an aggregate below gives on an empty input. Those values do not
776    /// hold once a Window or an Unnest runs over the aggregate, so the pull up
777    /// stops in that case.
778    fn pass_through_pulled_up_cols(
779        &mut self,
780        plan: LogicalPlan,
781    ) -> Result<Transformed<LogicalPlan>> {
782        if plan
783            .inputs()
784            .iter()
785            .any(|input| self.collected_count_expr_map.contains_key(*input))
786        {
787            self.can_pull_up = false;
788        }
789        Ok(Transformed::yes(plan.recompute_schema()?))
790    }
791
792    /// Whether the pull up can add its columns to a grouping set `Aggregate`,
793    /// and whether it needs to.
794    ///
795    /// [`GroupingSetsPullUp::NoColumnsToAdd`] when every set of every grouping
796    /// set already groups by each column [`Self::collect_missing_exprs`]
797    /// would add: the pull up adds nothing and the aggregate keeps the sets
798    /// it has.
799    ///
800    /// Otherwise some set leaves a required column out, which fills that
801    /// column with `NULL` in the set's rows. Adding the column to every set
802    /// (`LogicalPlanBuilder::aggregate` cross joins a plain group expression
803    /// with the sets that are already there) gives it a value instead. This
804    /// is only invisible to the rest of the query when:
805    ///  - no set is empty. `ROLLUP(i.k)`, `GROUPING SETS ((i.k), ())`, always
806    ///    holds one, and turns into `GROUPING SETS ((i.k), (i.k, i.k))`,
807    ///    losing the empty set and the grand total row it yields for every
808    ///    outer row, including the rows the correlated filter matches
809    ///    nothing for. The join that replaces the filter cannot bring that
810    ///    row back.
811    ///  - the aggregate does not compute `GROUPING`/`GROUPING_ID`, which
812    ///    reads whether a row's set groups by a column.
813    ///  - nothing above the aggregate reads the column, which
814    ///    `column_refs_above` tracks as `f_down`/`f_up` push and pop a node's
815    ///    own columns while they walk down to and back up from it.
816    ///
817    /// When one of these fails, [`GroupingSetsPullUp::Unsafe`] is returned:
818    /// the columns are still added, so the schema the nodes above expect
819    /// stays correct, but the caller must give up on decorrelating.
820    fn grouping_sets_pull_up_outcome(
821        &self,
822        aggregate: &Aggregate,
823        correlated_subquery_cols: &BTreeSet<Column>,
824    ) -> GroupingSetsPullUp {
825        let group_expr = &aggregate.group_expr;
826        let grouping_sets = group_expr
827            .iter()
828            .filter_map(|expr| match expr {
829                Expr::GroupingSet(grouping_set) => Some(grouping_set),
830                _ => None,
831            })
832            .collect::<Vec<_>>();
833        if grouping_sets.is_empty() {
834            return GroupingSetsPullUp::NoColumnsToAdd;
835        }
836
837        // The same columns `collect_missing_exprs` appends: the correlated columns
838        // and the columns of a pulled up HAVING, minus the ones `group_expr`
839        // already lists on their own, which it leaves alone.
840        let mut required_cols = correlated_subquery_cols.iter().collect::<BTreeSet<_>>();
841        if let Some(pull_up_having) = &self.pull_up_having_expr {
842            required_cols.extend(pull_up_having.column_refs());
843        }
844        required_cols.retain(|col| {
845            !group_expr
846                .iter()
847                .any(|expr| matches!(expr, Expr::Column(c) if c == *col))
848        });
849        if required_cols.is_empty() {
850            return GroupingSetsPullUp::NoColumnsToAdd;
851        }
852
853        let already_covered =
854            grouping_sets.iter().all(|grouping_set| match grouping_set {
855                GroupingSet::Rollup(_) | GroupingSet::Cube(_) => false,
856                GroupingSet::GroupingSets(sets) => sets.iter().all(|set| {
857                    required_cols.iter().all(|col| {
858                        set.iter()
859                            .any(|expr| matches!(expr, Expr::Column(c) if c == *col))
860                    })
861                }),
862            });
863        if already_covered {
864            return GroupingSetsPullUp::NoColumnsToAdd;
865        }
866
867        let has_empty_set = grouping_sets.iter().any(|grouping_set| match grouping_set {
868            GroupingSet::Rollup(_) | GroupingSet::Cube(_) => true,
869            GroupingSet::GroupingSets(sets) => sets.iter().any(|set| set.is_empty()),
870        });
871        // `GROUPING`/`GROUPING_ID` are resolved to bit tests on `__grouping_id`
872        // above the aggregate by `ResolveGroupingFunction` before this rule
873        // runs, so `aggregate.aggr_expr` never holds a `GROUPING` call by the
874        // time this is reached; adding a column shifts those bits instead.
875        let unsafe_read = self.column_refs_above.iter().flatten().any(|col| {
876            col.name == Aggregate::INTERNAL_GROUPING_ID || required_cols.contains(col)
877        });
878
879        if has_empty_set || unsafe_read {
880            GroupingSetsPullUp::Unsafe
881        } else {
882            GroupingSetsPullUp::SafeToExtend
883        }
884    }
885
886    fn collect_missing_exprs(
887        &mut self,
888        exprs: &[Expr],
889        correlated_subquery_cols: &BTreeSet<Column>,
890        _subquery_schema: &DFSchemaRef,
891    ) -> Result<Vec<Expr>> {
892        let mut missing_exprs =
893            Vec::with_capacity(exprs.len() + correlated_subquery_cols.len());
894        for expr in exprs {
895            if !missing_exprs.contains(expr) {
896                missing_exprs.push(expr.clone())
897            }
898        }
899        for col in correlated_subquery_cols.iter() {
900            let col_expr = Expr::Column(col.clone());
901            if !collides_with_existing(&missing_exprs, &col_expr) {
902                missing_exprs.push(col_expr)
903            }
904        }
905        if let Some(pull_up_having) = &self.pull_up_having_expr {
906            for col in pull_up_having.column_refs() {
907                let col_expr = Expr::Column(col.clone());
908                // `col` is unqualified but the projection may already have
909                // it as `agg.c`. Check by bare name so that doesn't get
910                // added twice.
911                let already_present = missing_exprs
912                    .iter()
913                    .any(|expr| matches!(expr, Expr::Column(c) if c.name == col.name))
914                    || collides_with_existing(&missing_exprs, &col_expr);
915                if !already_present {
916                    missing_exprs.push(col_expr)
917                }
918            }
919        }
920        Ok(missing_exprs)
921    }
922}
923
924/// Whether `plan` returns rows based only on whether its input has rows, and
925/// not on which rows those are.
926///
927/// This is what lets `EXISTS` drop a `Limit` with no skip and a non-zero
928/// fetch. Such a `Limit` returns rows exactly when its input has rows. If
929/// every node above it also only depends on whether it gets rows, the whole
930/// subquery returns rows exactly when the `Limit`'s input has rows, with or
931/// without the `Limit`, so removing it cannot change the `EXISTS` result.
932///
933/// It holds for:
934/// - `Projection`, `SubqueryAlias`, `Sort`, `Window` and `Repartition`, which
935///   return rows whenever their input has rows (a `Sort` with a fetch of 0
936///   returns none either way)
937/// - `DISTINCT` and a grouped `Aggregate`, which return at least one row for a
938///   non-empty input and none for an empty one
939/// - an `Aggregate` without grouping, which always returns one row
940/// - a materialized CTE, which returns its continuation's rows
941///
942/// It does not hold for a `Filter`, which keeps or removes rows by their
943/// values, so the rows the `Limit` kept decide whether any survive. A `Join`
944/// and an `Unnest` can also turn rows into none. Every other plan, including a
945/// user-defined `Extension`, is treated as not holding: the `Limit` stays and
946/// the subquery is not decorrelated.
947fn depends_only_on_input_having_rows(plan: &LogicalPlan) -> bool {
948    matches!(
949        plan,
950        LogicalPlan::Projection(_)
951            | LogicalPlan::SubqueryAlias(_)
952            | LogicalPlan::Sort(_)
953            | LogicalPlan::Window(_)
954            | LogicalPlan::Repartition(_)
955            | LogicalPlan::Distinct(Distinct::All(_))
956            | LogicalPlan::Aggregate(_)
957            | LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(_))
958    )
959}
960
961/// Whether `plan` can output a NULL in a column that a filter below it keeps
962/// free of NULLs: an outer join fills the columns of its unmatched side with
963/// NULL, a union adds the rows of its other inputs, and a grouping set fills
964/// the columns it leaves out with NULL, such as the grand total row of `ROLLUP`.
965fn may_reintroduce_nulls(plan: &LogicalPlan) -> bool {
966    match plan {
967        LogicalPlan::Join(join) => {
968            matches!(
969                join.join_type,
970                JoinType::Left | JoinType::Right | JoinType::Full
971            )
972        }
973        LogicalPlan::Union(_) => true,
974        LogicalPlan::Aggregate(aggregate) => aggregate
975            .group_expr
976            .iter()
977            .any(|expr| matches!(expr, Expr::GroupingSet(_))),
978        _ => false,
979    }
980}
981
982/// Whether every input of `join` that holds outer references is a side whose
983/// rows the join preserves, so a correlated filter below it can be pulled above
984/// the join without changing the result.
985fn correlated_inputs_are_preserved(join: &Join) -> bool {
986    let (left_preserved, right_preserved) = lr_is_preserved(join.join_type);
987    (left_preserved || !holds_outer_reference(&join.left))
988        && (right_preserved || !holds_outer_reference(&join.right))
989}
990
991/// Whether `plan` or any of its inputs holds an outer reference of the scope
992/// being decorrelated. Like [`PullUpCorrelatedExpr`], this does not descend into
993/// a [`LogicalPlan::Subquery`], whose outer references belong to a nested
994/// scope, such as the right side of a `LATERAL` join that is not decorrelated
995/// yet.
996fn holds_outer_reference(plan: &LogicalPlan) -> bool {
997    let mut found = false;
998    plan.apply(|node| {
999        Ok(match node {
1000            LogicalPlan::Subquery(_) => TreeNodeRecursion::Jump,
1001            _ if node.contains_outer_reference() => {
1002                found = true;
1003                TreeNodeRecursion::Stop
1004            }
1005            _ => TreeNodeRecursion::Continue,
1006        })
1007    })
1008    .expect("apply closure is infallible");
1009    found
1010}
1011
1012/// The columns that the correlated conjuncts of the Filters in `plan` read,
1013/// in the scope being decorrelated. Like [`holds_outer_reference`], this does
1014/// not descend into a [`LogicalPlan::Subquery`].
1015fn correlated_filter_columns(plan: &LogicalPlan) -> Vec<Column> {
1016    let mut cols = vec![];
1017    plan.apply(|node| {
1018        Ok(match node {
1019            LogicalPlan::Subquery(_) => TreeNodeRecursion::Jump,
1020            LogicalPlan::Filter(filter) => {
1021                for expr in split_conjunction(&filter.predicate) {
1022                    if expr.contains_outer() {
1023                        cols.extend(expr.column_refs().into_iter().cloned());
1024                    }
1025                }
1026                TreeNodeRecursion::Continue
1027            }
1028            _ => TreeNodeRecursion::Continue,
1029        })
1030    })
1031    .expect("apply closure is infallible");
1032    cols
1033}
1034
1035/// Adds `cols` to the `PARTITION BY` of every window function of `window`. Each
1036/// window expression keeps its old output name, so nothing above sees a change.
1037fn partition_window_by(window: &Window, cols: &BTreeSet<Column>) -> Result<LogicalPlan> {
1038    let window_expr = window
1039        .window_expr
1040        .iter()
1041        .map(|expr| {
1042            add_partition_by(expr, cols).alias_if_changed(expr.schema_name().to_string())
1043        })
1044        .collect::<Result<Vec<_>>>()?;
1045    Window::try_new(window_expr, Arc::clone(&window.input)).map(LogicalPlan::Window)
1046}
1047
1048fn add_partition_by(expr: &Expr, cols: &BTreeSet<Column>) -> Expr {
1049    match expr {
1050        Expr::Alias(alias) => Expr::Alias(Alias {
1051            expr: Box::new(add_partition_by(&alias.expr, cols)),
1052            ..alias.clone()
1053        }),
1054        Expr::WindowFunction(window_fun) => {
1055            let mut window_fun = window_fun.clone();
1056            for col in cols {
1057                let partitioned = window_fun
1058                    .params
1059                    .partition_by
1060                    .iter()
1061                    .any(|expr| matches!(expr, Expr::Column(c) if c == col));
1062                if !partitioned {
1063                    window_fun
1064                        .params
1065                        .partition_by
1066                        .push(Expr::Column(col.clone()));
1067                }
1068            }
1069            Expr::WindowFunction(window_fun)
1070        }
1071        _ => expr.clone(),
1072    }
1073}
1074
1075/// Whether the window function `expr` lists each of `cols` as a plain
1076/// `PARTITION BY` column.
1077fn partitions_by_all(expr: &Expr, cols: &BTreeSet<Column>) -> bool {
1078    let mut expr = expr;
1079    while let Expr::Alias(Alias { expr: inner, .. }) = expr {
1080        expr = inner;
1081    }
1082    let Expr::WindowFunction(window_fun) = expr else {
1083        return false;
1084    };
1085    let partition_by = &window_fun.params.partition_by;
1086    cols.iter().all(|col| {
1087        partition_by
1088            .iter()
1089            .any(|expr| matches!(expr, Expr::Column(c) if c == col))
1090    })
1091}
1092
1093/// True if `candidate` collides with an existing entry's schema name,
1094/// e.g. a bare column already wrapped in an equally-named `CAST`.
1095/// Colliding means `LogicalPlanBuilder::project` would reject it as a duplicate.
1096fn collides_with_existing(exprs: &[Expr], candidate: &Expr) -> bool {
1097    let candidate_name = candidate.schema_name().to_string();
1098    exprs
1099        .iter()
1100        .any(|expr| expr.schema_name().to_string() == candidate_name)
1101}
1102
1103fn can_pullup_over_aggregation(expr: &Expr) -> bool {
1104    split_column_equality(expr).is_some()
1105}
1106
1107/// Whether partitioning by the columns of `expr` keeps the rows `expr` matches
1108/// for one outer row in one partition. That holds for `col = <expr>` or
1109/// `<expr> = col`, where:
1110/// - `<expr>` reads no subquery column and is not volatile.
1111/// - `col` has no float leaf, because `-0.0 = 0.0` holds but a partition
1112///   keeps the two apart.
1113/// - `col` is cast only by a cast that keeps distinct values distinct. A lossy
1114///   cast lets several `col` values match one outer row, see #26014.
1115fn is_partitionable_equality(expr: &Expr, schema: &DFSchema) -> bool {
1116    let Some((col_side, other)) = split_column_equality(expr) else {
1117        return false;
1118    };
1119    let (col, cast_to) = match col_side {
1120        Expr::Cast(Cast { expr, field }) => (&**expr, Some(field.data_type())),
1121        _ => (col_side, None),
1122    };
1123    let Ok(col_type) = col.get_type(schema) else {
1124        return false;
1125    };
1126    !other.is_volatile()
1127        && !has_float_leaf(&col_type)
1128        && cast_to.is_none_or(|to| is_injective_cast(&col_type, to))
1129}
1130
1131/// Splits `col = <expr>` or `<expr> = col` into the subquery column side, a
1132/// column or a cast of one, and the other side, which reads no subquery column.
1133fn split_column_equality(expr: &Expr) -> Option<(&Expr, &Expr)> {
1134    let Expr::BinaryExpr(BinaryExpr {
1135        left,
1136        op: Operator::Eq,
1137        right,
1138    }) = expr
1139    else {
1140        return None;
1141    };
1142    [(&**left, &**right), (&**right, &**left)]
1143        .into_iter()
1144        .find(|(col_side, other)| {
1145            let is_col = match col_side {
1146                Expr::Column(_) => true,
1147                Expr::Cast(Cast { expr, .. }) => matches!(&**expr, Expr::Column(_)),
1148                _ => false,
1149            };
1150            is_col && !other.any_column_refs()
1151        })
1152}
1153
1154fn collect_local_correlated_cols(
1155    plan: &LogicalPlan,
1156    all_cols_map: &HashMap<LogicalPlan, BTreeSet<Column>>,
1157    local_cols: &mut BTreeSet<Column>,
1158) {
1159    for child in plan.inputs() {
1160        if let Some(cols) = all_cols_map.get(child) {
1161            local_cols.extend(cols.iter().cloned());
1162        }
1163        // SubqueryAlias is treated as the leaf node
1164        if !matches!(child, LogicalPlan::SubqueryAlias(_)) {
1165            collect_local_correlated_cols(child, all_cols_map, local_cols);
1166        }
1167    }
1168}
1169
1170/// Extracts correlated predicates, such as a comparison between a column from the
1171/// subquery and a column from the outer scope.
1172///
1173/// Preserves [`Expr::OuterReferenceColumn`] markers so callers can distinguish
1174/// inner and outer columns when qualifying join filters (see [`build_join_filter`]).
1175///
1176/// # Arguments
1177///
1178/// * `exprs` - Subquery filter predicates to classify.
1179///
1180/// # Return value
1181///
1182/// Tuple of (correlated join filters, remaining subquery filters). Correlated
1183/// self-equalities are discarded from both lists.
1184pub(crate) fn find_join_exprs(exprs: Vec<&Expr>) -> (Vec<Expr>, Vec<Expr>) {
1185    let mut joins = vec![];
1186    let mut others = vec![];
1187    for filter in exprs {
1188        // Predicates containing outer references become join filters.
1189        if filter.contains_outer() {
1190            // Compare with the outer-reference markers intact: inner and outer
1191            // columns with the same qualified name belong to different scopes.
1192            if !matches!(filter, Expr::BinaryExpr(BinaryExpr { left, op: Operator::Eq, right }) if left.eq(right))
1193            {
1194                joins.push(filter.clone());
1195            }
1196        } else {
1197            others.push(filter.clone());
1198        }
1199    }
1200    (joins, others)
1201}
1202
1203/// Combines join filters and qualifies their inner columns with the subquery alias.
1204///
1205/// Aliasing must precede stripping outer references so inner and outer columns
1206/// with the same qualified name remain distinguishable.
1207pub(crate) fn build_join_filter<'a>(
1208    join_filters: Vec<Expr>,
1209    correlated_cols: impl IntoIterator<Item = &'a Column>,
1210    subquery_alias: &str,
1211) -> Result<Option<Expr>> {
1212    let correlated_cols = correlated_cols
1213        .into_iter()
1214        .cloned()
1215        .collect::<BTreeSet<_>>();
1216    conjunction(join_filters)
1217        .map(|filter| {
1218            replace_qualified_name(filter, &correlated_cols, subquery_alias)
1219                .map(strip_outer_reference)
1220        })
1221        .transpose()
1222}
1223
1224fn remove_duplicated_filter(
1225    filters: Vec<Expr>,
1226    in_predicate: &Expr,
1227) -> Result<Vec<Expr>> {
1228    // We assume below that swapping the order of operands to an operator does
1229    // not change behavior, which is only true if the operator is commutative.
1230    assert_or_internal_err!(
1231        match in_predicate {
1232            Expr::BinaryExpr(b) => b.op.swap() == Some(b.op),
1233            _ => true,
1234        },
1235        "in_predicate must use a commutative operator"
1236    );
1237
1238    Ok(filters
1239        .into_iter()
1240        .filter(|filter| {
1241            let filter = &strip_outer_reference(filter.clone());
1242            if filter == in_predicate {
1243                return false;
1244            }
1245
1246            // Treat swapped operand order to a binary operator as equivalent
1247            !match (filter, in_predicate) {
1248                (Expr::BinaryExpr(a_expr), Expr::BinaryExpr(b_expr)) => {
1249                    a_expr.op == b_expr.op
1250                        && ((a_expr.left == b_expr.left && a_expr.right == b_expr.right)
1251                            || (a_expr.left == b_expr.right
1252                                && a_expr.right == b_expr.left))
1253                }
1254                _ => false,
1255            }
1256        })
1257        .collect::<Vec<_>>())
1258}
1259
1260fn agg_exprs_evaluation_result_on_empty_batch(
1261    agg_expr: &[Expr],
1262    schema: &DFSchemaRef,
1263    expr_result_map_for_count_bug: &mut ExprResultMap,
1264) -> Result<()> {
1265    let info = SimplifyContext::builder()
1266        .with_schema(Arc::clone(schema))
1267        .build();
1268    let simplifier = ExprSimplifier::new(info);
1269    for e in agg_expr.iter() {
1270        let result_expr = e
1271            .clone()
1272            .transform_up(|expr| {
1273                let new_expr = if let Expr::AggregateFunction(agg) = &expr {
1274                    let return_type = expr.get_type(schema.as_ref())?;
1275                    let default_value = agg.func.default_value(&return_type)?;
1276                    Transformed::yes(Expr::Literal(default_value, None))
1277                } else {
1278                    Transformed::no(expr)
1279                };
1280                Ok(new_expr)
1281            })
1282            .data()?;
1283
1284        let result_expr = result_expr.unalias();
1285        let result_expr = simplifier.simplify(result_expr)?;
1286        expr_result_map_for_count_bug.insert(e.schema_name().to_string(), result_expr);
1287    }
1288    Ok(())
1289}
1290
1291fn proj_exprs_evaluation_result_on_empty_batch(
1292    proj_expr: &[Expr],
1293    schema: &DFSchemaRef,
1294    input_expr_result_map_for_count_bug: &ExprResultMap,
1295    expr_result_map_for_count_bug: &mut ExprResultMap,
1296) -> Result<()> {
1297    for expr in proj_expr.iter() {
1298        let result_expr = expr
1299            .clone()
1300            .transform_up(|expr| {
1301                if let Expr::Column(Column { name, .. }) = &expr {
1302                    if let Some(result_expr) =
1303                        input_expr_result_map_for_count_bug.get(name)
1304                    {
1305                        Ok(Transformed::yes(result_expr.clone()))
1306                    } else {
1307                        Ok(Transformed::no(expr))
1308                    }
1309                } else {
1310                    Ok(Transformed::no(expr))
1311                }
1312            })
1313            .data()?;
1314
1315        // An expression that reads no column, like `1 AS x`, keeps its value
1316        // on an empty input, while the join that replaces the subquery gives
1317        // it NULL for an outer row without a match.
1318        let is_constant = !expr.any_column_refs() && !expr.contains_outer();
1319        if result_expr.ne(expr) || is_constant {
1320            let info = SimplifyContext::builder()
1321                .with_schema(Arc::clone(schema))
1322                .build();
1323            let simplifier = ExprSimplifier::new(info);
1324            let result_expr = simplifier.simplify(result_expr)?;
1325            let expr_name = match expr {
1326                Expr::Alias(Alias { name, .. }) => name.to_string(),
1327                Expr::Column(Column {
1328                    relation: _,
1329                    name,
1330                    spans: _,
1331                }) => name.to_string(),
1332                _ => expr.schema_name().to_string(),
1333            };
1334            expr_result_map_for_count_bug.insert(expr_name, result_expr);
1335        }
1336    }
1337    Ok(())
1338}
1339
1340fn filter_exprs_evaluation_result_on_empty_batch(
1341    filter_expr: &Expr,
1342    schema: DFSchemaRef,
1343    input_expr_result_map_for_count_bug: &ExprResultMap,
1344    expr_result_map_for_count_bug: &mut ExprResultMap,
1345) -> Result<Option<Expr>> {
1346    let result_expr = filter_expr
1347        .clone()
1348        .transform_up(|expr| {
1349            if let Expr::Column(Column { name, .. }) = &expr {
1350                if let Some(result_expr) = input_expr_result_map_for_count_bug.get(name) {
1351                    Ok(Transformed::yes(result_expr.clone()))
1352                } else {
1353                    Ok(Transformed::no(expr))
1354                }
1355            } else {
1356                Ok(Transformed::no(expr))
1357            }
1358        })
1359        .data()?;
1360
1361    let pull_up_expr = if result_expr.ne(filter_expr) {
1362        let info = SimplifyContext::builder().with_schema(schema).build();
1363        let simplifier = ExprSimplifier::new(info);
1364        let result_expr = simplifier.simplify(result_expr)?;
1365        match &result_expr {
1366            Expr::Literal(ScalarValue::Null, _)
1367            | Expr::Literal(ScalarValue::Boolean(None), _)
1368            | Expr::Literal(ScalarValue::Boolean(Some(false)), _) => {
1369                for (name, exprs) in input_expr_result_map_for_count_bug {
1370                    expr_result_map_for_count_bug.insert(name.clone(), exprs.clone());
1371                }
1372                None
1373            }
1374            // evaluate to true on empty batch, need to pull up the expr
1375            Expr::Literal(ScalarValue::Boolean(Some(true)), _) => {
1376                for (name, exprs) in input_expr_result_map_for_count_bug {
1377                    expr_result_map_for_count_bug.insert(name.clone(), exprs.clone());
1378                }
1379                Some(filter_expr.clone())
1380            }
1381            // can not evaluate statically
1382            _ => {
1383                for input_expr in input_expr_result_map_for_count_bug.values() {
1384                    let new_expr = Expr::Case(expr::Case {
1385                        expr: None,
1386                        when_then_expr: vec![(
1387                            Box::new(result_expr.clone()),
1388                            Box::new(input_expr.clone()),
1389                        )],
1390                        else_expr: Some(Box::new(Expr::Literal(ScalarValue::Null, None))),
1391                    });
1392                    let expr_key = new_expr.schema_name().to_string();
1393                    expr_result_map_for_count_bug.insert(expr_key, new_expr);
1394                }
1395                None
1396            }
1397        }
1398    } else {
1399        for (name, exprs) in input_expr_result_map_for_count_bug {
1400            expr_result_map_for_count_bug.insert(name.clone(), exprs.clone());
1401        }
1402        None
1403    };
1404    Ok(pull_up_expr)
1405}
1406
1407#[cfg(test)]
1408mod tests {
1409    use super::*;
1410    use arrow::datatypes::DataType;
1411    use datafusion_expr::{col, out_ref_col};
1412
1413    #[test]
1414    fn test_find_join_exprs_preserves_outer_references() {
1415        let outer = out_ref_col(DataType::Int32, "t.a");
1416        let correlated = col("t.a").eq(outer.clone());
1417        let self_equality = outer.clone().eq(outer);
1418        let local = col("t.b").gt(lit(2));
1419
1420        assert_eq!(
1421            find_join_exprs(vec![&correlated, &self_equality, &local]),
1422            (vec![correlated], vec![local])
1423        );
1424    }
1425
1426    #[test]
1427    fn test_build_join_filter() -> Result<()> {
1428        assert_eq!(build_join_filter(vec![], [], "sq")?, None);
1429
1430        let column = Column::from("t.a");
1431        let outer = out_ref_col(DataType::Int32, "t.a");
1432        let filters = vec![col("t.a").eq(outer.clone()), outer.gt(lit(1))];
1433
1434        assert_eq!(
1435            build_join_filter(filters, [&column, &column], "sq")?,
1436            Some(col("sq.a").eq(col("t.a")).and(col("t.a").gt(lit(1))))
1437        );
1438        Ok(())
1439    }
1440}