Skip to main content

datafusion_expr/logical_plan/
tree_node.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//!  [`TreeNode`] based visiting and rewriting for [`LogicalPlan`]s
6//!
7//! Visiting (read only) APIs
8//! * [`LogicalPlan::visit`]: recursively visit the node and all of its inputs
9//! * [`LogicalPlan::visit_with_subqueries`]: recursively visit the node and all of its inputs, including subqueries
10//! * [`LogicalPlan::apply_children`]: recursively visit all inputs of this node
11//! * [`LogicalPlan::apply_expressions`]: (non recursively) visit all expressions of this node
12//! * [`LogicalPlan::apply_subqueries`]: (non recursively) visit all subqueries of this node
13//! * [`LogicalPlan::apply_with_subqueries`]: recursively visit all inputs and embedded subqueries.
14//!
15//! Rewriting (update) APIs:
16//! * [`LogicalPlan::exists`]: search for an expression in a plan
17//! * [`LogicalPlan::rewrite`]: recursively rewrite the node and all of its inputs
18//! * [`LogicalPlan::map_children`]: recursively rewrite all inputs of this node
19//! * [`LogicalPlan::map_expressions`]: (non recursively) visit all expressions of this node
20//! * [`LogicalPlan::map_subqueries`]: (non recursively) rewrite all subqueries of this node
21//! * [`LogicalPlan::rewrite_with_subqueries`]: recursively rewrite the node and all of its inputs, including subqueries
22//!
23//! (Re)creation APIs (these require substantial cloning and thus are slow):
24//! * [`LogicalPlan::with_new_exprs`]: Create a new plan with different expressions
25//! * [`LogicalPlan::expressions`]: Return a copy of the plan's expressions
26
27use std::sync::Arc;
28
29use crate::logical_plan::plan::RangePartitioning;
30use crate::{
31    Aggregate, Analyze, AsOfJoin, AsOfMatch, CreateMemoryTable, CreateView, DdlStatement,
32    Distinct, DistinctOn, DmlStatement, Execute, Explain, Expr, Extension, Filter, Join,
33    Limit, LogicalPlan, MaterializedCte, MaterializedCtePlan, Partitioning, Prepare,
34    Projection, RecursiveQuery, Repartition, Sort, Statement, Subquery, SubqueryAlias,
35    TableScan, Union, Unnest, UserDefinedLogicalNode, Values, Window, WriteOp,
36    builder::unnest_with_options, dml::CopyTo,
37};
38use datafusion_common::tree_node::TreeNodeRefContainer;
39
40use crate::expr::{Exists, InSubquery, SetComparison};
41use datafusion_common::tree_node::{
42    Transformed, TreeNode, TreeNodeContainer, TreeNodeIterator, TreeNodeRecursion,
43    TreeNodeRewriter, TreeNodeVisitor,
44};
45use datafusion_common::{Result, internal_err};
46
47impl TreeNode for LogicalPlan {
48    fn apply_children<'n, F: FnMut(&'n Self) -> Result<TreeNodeRecursion>>(
49        &'n self,
50        f: F,
51    ) -> Result<TreeNodeRecursion> {
52        self.inputs().apply_ref_elements(f)
53    }
54
55    /// Applies `f` to each child (input) of this plan node, rewriting them *in place.*
56    ///
57    /// # Notes
58    ///
59    /// Inputs include ONLY direct children, not embedded `LogicalPlan`s for
60    /// subqueries, for example such as are in [`Expr::Exists`].
61    ///
62    /// [`Expr::Exists`]: crate::Expr::Exists
63    fn map_children<F: FnMut(Self) -> Result<Transformed<Self>>>(
64        self,
65        f: F,
66    ) -> Result<Transformed<Self>> {
67        Ok(match self {
68            LogicalPlan::Projection(Projection {
69                expr,
70                input,
71                schema,
72            }) => input.map_elements(f)?.update_data(|input| {
73                LogicalPlan::Projection(Projection {
74                    expr,
75                    input,
76                    schema,
77                })
78            }),
79            LogicalPlan::Filter(Filter { predicate, input }) => input
80                .map_elements(f)?
81                .update_data(|input| LogicalPlan::Filter(Filter { predicate, input })),
82            LogicalPlan::Repartition(Repartition {
83                input,
84                partitioning_scheme,
85            }) => input.map_elements(f)?.update_data(|input| {
86                LogicalPlan::Repartition(Repartition {
87                    input,
88                    partitioning_scheme,
89                })
90            }),
91            LogicalPlan::Window(Window {
92                input,
93                window_expr,
94                schema,
95            }) => input.map_elements(f)?.update_data(|input| {
96                LogicalPlan::Window(Window {
97                    input,
98                    window_expr,
99                    schema,
100                })
101            }),
102            LogicalPlan::Aggregate(Aggregate {
103                input,
104                group_expr,
105                aggr_expr,
106                schema,
107            }) => input.map_elements(f)?.update_data(|input| {
108                LogicalPlan::Aggregate(Aggregate {
109                    input,
110                    group_expr,
111                    aggr_expr,
112                    schema,
113                })
114            }),
115            LogicalPlan::Sort(Sort { expr, input, fetch }) => input
116                .map_elements(f)?
117                .update_data(|input| LogicalPlan::Sort(Sort { expr, input, fetch })),
118            LogicalPlan::Join(Join {
119                left,
120                right,
121                on,
122                filter,
123                join_type,
124                join_constraint,
125                schema,
126                null_equality,
127                null_aware,
128                null_aware_value_keys,
129            }) => (left, right).map_elements(f)?.update_data(|(left, right)| {
130                LogicalPlan::Join(Join {
131                    left,
132                    right,
133                    on,
134                    filter,
135                    join_type,
136                    join_constraint,
137                    schema,
138                    null_equality,
139                    null_aware,
140                    null_aware_value_keys,
141                })
142            }),
143            LogicalPlan::AsOfJoin(AsOfJoin {
144                left,
145                right,
146                on,
147                match_condition,
148                join_constraint,
149                schema,
150            }) => (left, right).map_elements(f)?.update_data(|(left, right)| {
151                LogicalPlan::AsOfJoin(AsOfJoin {
152                    left,
153                    right,
154                    on,
155                    match_condition,
156                    join_constraint,
157                    schema,
158                })
159            }),
160            LogicalPlan::Limit(Limit { skip, fetch, input }) => input
161                .map_elements(f)?
162                .update_data(|input| LogicalPlan::Limit(Limit { skip, fetch, input })),
163            LogicalPlan::Subquery(Subquery {
164                subquery,
165                outer_ref_columns,
166                spans,
167            }) => subquery.map_elements(f)?.update_data(|subquery| {
168                LogicalPlan::Subquery(Subquery {
169                    subquery,
170                    outer_ref_columns,
171                    spans,
172                })
173            }),
174            LogicalPlan::SubqueryAlias(SubqueryAlias {
175                input,
176                alias,
177                schema,
178            }) => input.map_elements(f)?.update_data(|input| {
179                LogicalPlan::SubqueryAlias(SubqueryAlias {
180                    input,
181                    alias,
182                    schema,
183                })
184            }),
185            LogicalPlan::Extension(extension) => rewrite_extension_inputs(extension, f)?
186                .update_data(LogicalPlan::Extension),
187            LogicalPlan::Union(Union { inputs, schema }) => inputs
188                .map_elements(f)?
189                .update_data(|inputs| LogicalPlan::Union(Union { inputs, schema })),
190            LogicalPlan::Distinct(distinct) => match distinct {
191                Distinct::All(input) => input.map_elements(f)?.update_data(Distinct::All),
192                Distinct::On(DistinctOn {
193                    on_expr,
194                    select_expr,
195                    sort_expr,
196                    input,
197                    schema,
198                }) => input.map_elements(f)?.update_data(|input| {
199                    Distinct::On(DistinctOn {
200                        on_expr,
201                        select_expr,
202                        sort_expr,
203                        input,
204                        schema,
205                    })
206                }),
207            }
208            .update_data(LogicalPlan::Distinct),
209            LogicalPlan::Explain(Explain {
210                verbose,
211                explain_format: format,
212                plan,
213                stringified_plans,
214                schema,
215                logical_optimization_succeeded,
216                show_statistics,
217            }) => plan.map_elements(f)?.update_data(|plan| {
218                LogicalPlan::Explain(Explain {
219                    verbose,
220                    explain_format: format,
221                    plan,
222                    stringified_plans,
223                    schema,
224                    logical_optimization_succeeded,
225                    show_statistics,
226                })
227            }),
228            LogicalPlan::Analyze(Analyze {
229                verbose,
230                format,
231                input,
232                schema,
233                analyze_level,
234                analyze_categories,
235            }) => input.map_elements(f)?.update_data(|input| {
236                LogicalPlan::Analyze(Analyze {
237                    verbose,
238                    format,
239                    input,
240                    schema,
241                    analyze_level,
242                    analyze_categories,
243                })
244            }),
245            LogicalPlan::Dml(DmlStatement {
246                table_name,
247                target,
248                op,
249                input,
250                output_schema,
251            }) => input.map_elements(f)?.update_data(|input| {
252                LogicalPlan::Dml(DmlStatement {
253                    table_name,
254                    target,
255                    op,
256                    input,
257                    output_schema,
258                })
259            }),
260            LogicalPlan::Copy(CopyTo {
261                input,
262                output_url,
263                partition_by,
264                file_type,
265                options,
266                output_schema,
267            }) => input.map_elements(f)?.update_data(|input| {
268                LogicalPlan::Copy(CopyTo {
269                    input,
270                    output_url,
271                    partition_by,
272                    file_type,
273                    options,
274                    output_schema,
275                })
276            }),
277            LogicalPlan::Ddl(ddl) => {
278                match ddl {
279                    DdlStatement::CreateMemoryTable(CreateMemoryTable {
280                        name,
281                        constraints,
282                        input,
283                        if_not_exists,
284                        or_replace,
285                        column_defaults,
286                        temporary,
287                    }) => input.map_elements(f)?.update_data(|input| {
288                        DdlStatement::CreateMemoryTable(CreateMemoryTable {
289                            name,
290                            constraints,
291                            input,
292                            if_not_exists,
293                            or_replace,
294                            column_defaults,
295                            temporary,
296                        })
297                    }),
298                    DdlStatement::CreateView(CreateView {
299                        name,
300                        input,
301                        or_replace,
302                        definition,
303                        temporary,
304                    }) => input.map_elements(f)?.update_data(|input| {
305                        DdlStatement::CreateView(CreateView {
306                            name,
307                            input,
308                            or_replace,
309                            definition,
310                            temporary,
311                        })
312                    }),
313                    // no inputs in these statements
314                    DdlStatement::CreateExternalTable(_)
315                    | DdlStatement::CreateCatalogSchema(_)
316                    | DdlStatement::CreateCatalog(_)
317                    | DdlStatement::CreateExternalCatalog(_)
318                    | DdlStatement::CreateIndex(_)
319                    | DdlStatement::DropTable(_)
320                    | DdlStatement::DropView(_)
321                    | DdlStatement::DropCatalogSchema(_)
322                    | DdlStatement::DropCatalog(_)
323                    | DdlStatement::CreateFunction(_)
324                    | DdlStatement::DropFunction(_) => Transformed::no(ddl),
325                }
326                .update_data(LogicalPlan::Ddl)
327            }
328            LogicalPlan::Unnest(Unnest {
329                input,
330                exec_columns: input_columns,
331                list_type_columns,
332                struct_type_columns,
333                dependency_indices,
334                schema,
335                options,
336            }) => input.map_elements(f)?.update_data(|input| {
337                LogicalPlan::Unnest(Unnest {
338                    input,
339                    exec_columns: input_columns,
340                    list_type_columns,
341                    struct_type_columns,
342                    dependency_indices,
343                    schema,
344                    options,
345                })
346            }),
347            LogicalPlan::RecursiveQuery(RecursiveQuery {
348                name,
349                static_term,
350                recursive_term,
351                is_distinct,
352                schema,
353            }) => (static_term, recursive_term).map_elements(f)?.update_data(
354                |(static_term, recursive_term)| {
355                    // Ordinary child rewrites preserve derived schemas. Call
356                    // `LogicalPlan::recompute_schema` when child schemas should
357                    // be reconciled again.
358                    LogicalPlan::RecursiveQuery(RecursiveQuery {
359                        name,
360                        static_term,
361                        recursive_term,
362                        is_distinct,
363                        schema,
364                    })
365                },
366            ),
367            LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte {
368                id,
369                name,
370                cte,
371                continuation,
372            })) => {
373                (cte, continuation)
374                    .map_elements(f)?
375                    .update_data(|(cte, continuation)| {
376                        LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
377                            MaterializedCte {
378                                id,
379                                name,
380                                cte,
381                                continuation,
382                            },
383                        ))
384                    })
385            }
386            LogicalPlan::Statement(stmt) => match stmt {
387                Statement::Prepare(p) => p
388                    .input
389                    .map_elements(f)?
390                    .update_data(|input| Statement::Prepare(Prepare { input, ..p })),
391                _ => Transformed::no(stmt),
392            }
393            .update_data(LogicalPlan::Statement),
394            // plans without inputs
395            LogicalPlan::TableScan { .. }
396            | LogicalPlan::EmptyRelation { .. }
397            | LogicalPlan::Values { .. }
398            | LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_))
399            | LogicalPlan::Show(_) => Transformed::no(self),
400        })
401    }
402}
403
404/// Rewrites all inputs for an Extension node "in place"
405/// (it currently has to copy values because there are no APIs for in place modification)
406///
407/// Should be removed when we have an API for in place modifications of the
408/// extension to avoid these copies
409fn rewrite_extension_inputs<F: FnMut(LogicalPlan) -> Result<Transformed<LogicalPlan>>>(
410    extension: Extension,
411    f: F,
412) -> Result<Transformed<Extension>> {
413    let Extension { node } = extension;
414
415    node.inputs()
416        .into_iter()
417        .cloned()
418        .map_until_stop_and_collect(f)?
419        .map_data(|new_inputs| {
420            let exprs = node.expressions();
421            Ok(Extension {
422                node: node.with_exprs_and_inputs(exprs, new_inputs)?,
423            })
424        })
425}
426
427/// This macro is used to determine continuation during combined transforming
428/// traversals.
429macro_rules! handle_transform_recursion {
430    ($F_DOWN:expr, $F_CHILD:expr, $F_UP:expr) => {{
431        $F_DOWN?
432            .transform_children(|n| {
433                n.map_subqueries($F_CHILD)?
434                    .transform_sibling(|n| n.map_children($F_CHILD))
435            })?
436            .transform_parent($F_UP)
437    }};
438}
439
440impl LogicalPlan {
441    /// Calls `f` on all expressions in the current `LogicalPlan` node.
442    ///
443    /// # Notes
444    /// * Similar to [`TreeNode::apply`] but for this node's expressions.
445    /// * Does not include expressions in input `LogicalPlan` nodes
446    /// * Visits only the top level expressions (Does not recurse into each expression)
447    pub fn apply_expressions<F: FnMut(&Expr) -> Result<TreeNodeRecursion>>(
448        &self,
449        mut f: F,
450    ) -> Result<TreeNodeRecursion> {
451        match self {
452            LogicalPlan::Projection(Projection { expr, .. }) => expr.apply_elements(f),
453            LogicalPlan::Values(Values { values, .. }) => values.apply_elements(f),
454            LogicalPlan::Filter(Filter { predicate, .. }) => f(predicate),
455            LogicalPlan::Repartition(Repartition {
456                partitioning_scheme,
457                ..
458            }) => match partitioning_scheme {
459                Partitioning::Hash(expr, _) | Partitioning::DistributeBy(expr) => {
460                    expr.apply_elements(f)
461                }
462                Partitioning::Range(range) => range.ordering().to_vec().apply_elements(f),
463                Partitioning::RoundRobinBatch(_) => Ok(TreeNodeRecursion::Continue),
464            },
465            LogicalPlan::Window(Window { window_expr, .. }) => {
466                window_expr.apply_elements(f)
467            }
468            LogicalPlan::Aggregate(Aggregate {
469                group_expr,
470                aggr_expr,
471                ..
472            }) => (group_expr, aggr_expr).apply_ref_elements(f),
473            // There are two part of expression for join, equijoin(on) and non-equijoin(filter).
474            // 1. the first part is `on.len()` equijoin expressions, and the struct of each expr is `left-on = right-on`.
475            // 2. the second part is non-equijoin(filter).
476            LogicalPlan::Join(Join { on, filter, .. }) => {
477                (on, filter).apply_ref_elements(f)
478            }
479            LogicalPlan::AsOfJoin(AsOfJoin {
480                on,
481                match_condition,
482                ..
483            }) => on.apply_elements(&mut f)?.visit_sibling(|| {
484                (&match_condition.left, &match_condition.right).apply_ref_elements(&mut f)
485            }),
486            LogicalPlan::Sort(Sort { expr, .. }) => expr.apply_elements(f),
487            LogicalPlan::Extension(extension) => {
488                // would be nice to avoid this copy -- maybe can
489                // update extension to just observer Exprs
490                extension.node.expressions().apply_elements(f)
491            }
492            LogicalPlan::TableScan(TableScan { filters, .. }) => {
493                filters.apply_elements(f)
494            }
495            LogicalPlan::Unnest(unnest) => {
496                let exprs = unnest
497                    .exec_columns
498                    .iter()
499                    .cloned()
500                    .map(Expr::Column)
501                    .collect::<Vec<_>>();
502                exprs.apply_elements(f)
503            }
504            LogicalPlan::Distinct(Distinct::On(DistinctOn {
505                on_expr,
506                select_expr,
507                sort_expr,
508                ..
509            })) => (on_expr, select_expr, sort_expr).apply_ref_elements(f),
510            LogicalPlan::Limit(Limit { skip, fetch, .. }) => {
511                (skip, fetch).apply_ref_elements(f)
512            }
513            LogicalPlan::Statement(stmt) => match stmt {
514                Statement::Execute(Execute { parameters, .. }) => {
515                    parameters.apply_elements(f)
516                }
517                _ => Ok(TreeNodeRecursion::Continue),
518            },
519            LogicalPlan::Dml(DmlStatement {
520                op: WriteOp::MergeInto(merge_op),
521                ..
522            }) => merge_op.exprs().apply_ref_elements(f),
523            // plans without expressions
524            LogicalPlan::EmptyRelation(_)
525            | LogicalPlan::RecursiveQuery(_)
526            | LogicalPlan::MaterializedCte(_)
527            | LogicalPlan::Subquery(_)
528            | LogicalPlan::SubqueryAlias(_)
529            | LogicalPlan::Analyze(_)
530            | LogicalPlan::Explain(_)
531            | LogicalPlan::Union(_)
532            | LogicalPlan::Distinct(Distinct::All(_))
533            | LogicalPlan::Dml(_)
534            | LogicalPlan::Ddl(_)
535            | LogicalPlan::Copy(_)
536            | LogicalPlan::Show(_) => Ok(TreeNodeRecursion::Continue),
537        }
538    }
539
540    /// Rewrites all expressions in the current `LogicalPlan` node using `f`.
541    ///
542    /// Returns the current node.
543    ///
544    /// # Notes
545    /// * Similar to [`TreeNode::map_children`] but for this node's expressions.
546    /// * Visits only the top level expressions (Does not recurse into each expression)
547    /// * A `Projection` whose expressions were rewritten gets its schema derived
548    ///   again from the new expressions, so the new expressions must resolve
549    ///   against the current input.
550    pub fn map_expressions<F: FnMut(Expr) -> Result<Transformed<Expr>>>(
551        self,
552        mut f: F,
553    ) -> Result<Transformed<Self>> {
554        Ok(match self {
555            LogicalPlan::Projection(Projection {
556                expr,
557                input,
558                schema,
559            }) => {
560                let expr = expr.map_elements(f)?;
561                if expr.transformed {
562                    // A projection's output fields are derived from its
563                    // expressions, so rewritten expressions need a freshly
564                    // derived schema.
565                    expr.map_data(|expr| {
566                        Projection::try_new(expr, input).map(LogicalPlan::Projection)
567                    })?
568                } else {
569                    expr.update_data(|expr| {
570                        LogicalPlan::Projection(Projection {
571                            expr,
572                            input,
573                            schema,
574                        })
575                    })
576                }
577            }
578            LogicalPlan::Values(Values { schema, values }) => values
579                .map_elements(f)?
580                .update_data(|values| LogicalPlan::Values(Values { schema, values })),
581            LogicalPlan::Filter(Filter { predicate, input }) => f(predicate)?
582                .update_data(|predicate| {
583                    LogicalPlan::Filter(Filter { predicate, input })
584                }),
585            LogicalPlan::Repartition(Repartition {
586                input,
587                partitioning_scheme,
588            }) => match partitioning_scheme {
589                Partitioning::Hash(expr, usize) => expr
590                    .map_elements(f)?
591                    .update_data(|expr| Partitioning::Hash(expr, usize)),
592                Partitioning::DistributeBy(expr) => expr
593                    .map_elements(f)?
594                    .update_data(Partitioning::DistributeBy),
595                Partitioning::Range(range) => {
596                    let split_points = range.split_points().to_vec();
597                    range
598                        .ordering()
599                        .to_vec()
600                        .map_elements(f)?
601                        .map_data(|ordering| {
602                            Ok(Partitioning::Range(RangePartitioning::try_new(
603                                ordering,
604                                split_points,
605                            )?))
606                        })?
607                }
608                Partitioning::RoundRobinBatch(_) => Transformed::no(partitioning_scheme),
609            }
610            .update_data(|partitioning_scheme| {
611                LogicalPlan::Repartition(Repartition {
612                    input,
613                    partitioning_scheme,
614                })
615            }),
616            LogicalPlan::Window(Window {
617                input,
618                window_expr,
619                schema,
620            }) => window_expr.map_elements(f)?.update_data(|window_expr| {
621                LogicalPlan::Window(Window {
622                    input,
623                    window_expr,
624                    schema,
625                })
626            }),
627            LogicalPlan::Aggregate(Aggregate {
628                input,
629                group_expr,
630                aggr_expr,
631                schema,
632            }) => (group_expr, aggr_expr).map_elements(f)?.update_data(
633                |(group_expr, aggr_expr)| {
634                    LogicalPlan::Aggregate(Aggregate {
635                        input,
636                        group_expr,
637                        aggr_expr,
638                        schema,
639                    })
640                },
641            ),
642
643            // There are two part of expression for join, equijoin(on) and non-equijoin(filter).
644            // 1. the first part is `on.len()` equijoin expressions, and the struct of each expr is `left-on = right-on`.
645            // 2. the second part is non-equijoin(filter).
646            LogicalPlan::Join(Join {
647                left,
648                right,
649                on,
650                filter,
651                join_type,
652                join_constraint,
653                schema,
654                null_equality,
655                null_aware,
656                null_aware_value_keys,
657            }) => (on, filter).map_elements(f)?.update_data(|(on, filter)| {
658                LogicalPlan::Join(Join {
659                    left,
660                    right,
661                    on,
662                    filter,
663                    join_type,
664                    join_constraint,
665                    schema,
666                    null_equality,
667                    null_aware,
668                    null_aware_value_keys,
669                })
670            }),
671            LogicalPlan::AsOfJoin(AsOfJoin {
672                left,
673                right,
674                on,
675                match_condition,
676                join_constraint,
677                schema,
678            }) => (on, (match_condition.left, match_condition.right))
679                .map_elements(f)?
680                .update_data(|(on, (left_match, right_match))| {
681                    LogicalPlan::AsOfJoin(AsOfJoin {
682                        left,
683                        right,
684                        on,
685                        match_condition: Box::new(AsOfMatch {
686                            left: left_match,
687                            op: match_condition.op,
688                            right: right_match,
689                        }),
690                        join_constraint,
691                        schema,
692                    })
693                }),
694            LogicalPlan::Sort(Sort { expr, input, fetch }) => expr
695                .map_elements(f)?
696                .update_data(|expr| LogicalPlan::Sort(Sort { expr, input, fetch })),
697            LogicalPlan::Extension(Extension { node }) => {
698                let raw_exprs = node.expressions();
699                if raw_exprs.is_empty() {
700                    // No expressions to transform — skip expensive clone of
701                    // all inputs and reconstruction via with_exprs_and_inputs.
702                    Transformed::no(LogicalPlan::Extension(Extension { node }))
703                } else {
704                    // TODO: a more general optimization would be to change
705                    // `UserDefinedLogicalNode::expressions()` to return
706                    // references (`&[Expr]`) instead of cloned `Vec<Expr>`,
707                    // and only clone + rebuild when the transform actually
708                    // modifies an expression. This would avoid the clone +
709                    // `with_exprs_and_inputs` rebuild even for non-empty
710                    // expression lists when the transform is a no-op.
711                    let exprs = raw_exprs.map_elements(f)?;
712                    let plan = LogicalPlan::Extension(Extension {
713                        node: UserDefinedLogicalNode::with_exprs_and_inputs(
714                            node.as_ref(),
715                            exprs.data,
716                            node.inputs().into_iter().cloned().collect::<Vec<_>>(),
717                        )?,
718                    });
719                    Transformed::new(plan, exprs.transformed, exprs.tnr)
720                }
721            }
722            LogicalPlan::TableScan(TableScan {
723                table_name,
724                source,
725                projection,
726                projected_schema,
727                filters,
728                fetch,
729                skip: offset,
730                statistics_requests,
731            }) => filters.map_elements(f)?.update_data(|filters| {
732                LogicalPlan::TableScan(TableScan {
733                    table_name,
734                    source,
735                    projection,
736                    projected_schema,
737                    filters,
738                    fetch,
739                    skip: offset,
740                    statistics_requests,
741                })
742            }),
743            LogicalPlan::Distinct(Distinct::On(DistinctOn {
744                on_expr,
745                select_expr,
746                sort_expr,
747                input,
748                schema,
749            })) => (on_expr, select_expr, sort_expr)
750                .map_elements(f)?
751                .update_data(|(on_expr, select_expr, sort_expr)| {
752                    LogicalPlan::Distinct(Distinct::On(DistinctOn {
753                        on_expr,
754                        select_expr,
755                        sort_expr,
756                        input,
757                        schema,
758                    }))
759                }),
760            LogicalPlan::Limit(Limit { skip, fetch, input }) => {
761                (skip, fetch).map_elements(f)?.update_data(|(skip, fetch)| {
762                    LogicalPlan::Limit(Limit { skip, fetch, input })
763                })
764            }
765            LogicalPlan::Statement(stmt) => match stmt {
766                Statement::Execute(e) => {
767                    e.parameters.map_elements(f)?.update_data(|parameters| {
768                        Statement::Execute(Execute { parameters, ..e })
769                    })
770                }
771                _ => Transformed::no(stmt),
772            }
773            .update_data(LogicalPlan::Statement),
774            LogicalPlan::Unnest(Unnest {
775                input,
776                exec_columns,
777                options,
778                ..
779            }) => {
780                let exprs: Vec<Expr> =
781                    exec_columns.into_iter().map(Expr::Column).collect();
782                exprs.map_elements(f)?.map_data(|mapped_exprs| {
783                    let new_columns = mapped_exprs
784                        .into_iter()
785                        .map(|e| match e {
786                            Expr::Column(c) => Ok(c),
787                            other => internal_err!(
788                                "Expected Expr::Column for Unnest exec_columns, got {other:?}"
789                            ),
790                        })
791                        .collect::<Result<Vec<_>>>()?;
792                    // Rebuild through `unnest_with_options` so the derived
793                    // `list_type_columns`, `struct_type_columns`,
794                    // `dependency_indices`, and `schema` are recomputed from
795                    // the (possibly rewritten) columns rather than carried over
796                    // stale. This keeps `map_expressions` consistent with
797                    // `with_new_exprs`.
798                    unnest_with_options(
799                        Arc::unwrap_or_clone(input),
800                        new_columns,
801                        options,
802                    )
803                })?
804            }
805            LogicalPlan::Dml(DmlStatement {
806                table_name,
807                target,
808                op: WriteOp::MergeInto(merge_op),
809                input,
810                output_schema,
811            }) => {
812                let owned_exprs: Vec<Expr> =
813                    merge_op.exprs().into_iter().cloned().collect();
814                owned_exprs.map_elements(f)?.transform_data(|new_exprs| {
815                    Ok(Transformed::no(LogicalPlan::Dml(DmlStatement {
816                        table_name,
817                        target,
818                        op: WriteOp::MergeInto(Box::new(
819                            merge_op.with_new_exprs(new_exprs)?,
820                        )),
821                        input,
822                        output_schema,
823                    })))
824                })?
825            }
826            // plans without expressions
827            LogicalPlan::EmptyRelation(_)
828            | LogicalPlan::RecursiveQuery(_)
829            | LogicalPlan::MaterializedCte(_)
830            | LogicalPlan::Subquery(_)
831            | LogicalPlan::SubqueryAlias(_)
832            | LogicalPlan::Analyze(_)
833            | LogicalPlan::Explain(_)
834            | LogicalPlan::Union(_)
835            | LogicalPlan::Distinct(Distinct::All(_))
836            | LogicalPlan::Dml(_)
837            | LogicalPlan::Ddl(_)
838            | LogicalPlan::Copy(_)
839            | LogicalPlan::Show(_) => Transformed::no(self),
840        })
841    }
842
843    /// Visits a plan similarly to [`Self::visit`], including subqueries that
844    /// may appear in expressions such as `IN (SELECT ...)`.
845    #[cfg_attr(feature = "recursive_protection", recursive::recursive)]
846    pub fn visit_with_subqueries<V: for<'n> TreeNodeVisitor<'n, Node = Self>>(
847        &self,
848        visitor: &mut V,
849    ) -> Result<TreeNodeRecursion> {
850        visitor
851            .f_down(self)?
852            .visit_children(|| {
853                self.apply_subqueries(|c| c.visit_with_subqueries(visitor))?
854                    .visit_sibling(|| {
855                        self.apply_children(|c| c.visit_with_subqueries(visitor))
856                    })
857            })?
858            .visit_parent(|| visitor.f_up(self))
859    }
860
861    /// Similarly to [`Self::rewrite`], rewrites this node and its inputs using `f`,
862    /// including subqueries that may appear in expressions such as `IN (SELECT
863    /// ...)`.
864    #[cfg_attr(feature = "recursive_protection", recursive::recursive)]
865    pub fn rewrite_with_subqueries<R: TreeNodeRewriter<Node = Self>>(
866        self,
867        rewriter: &mut R,
868    ) -> Result<Transformed<Self>> {
869        handle_transform_recursion!(
870            rewriter.f_down(self),
871            |c| c.rewrite_with_subqueries(rewriter),
872            |n| rewriter.f_up(n)
873        )
874    }
875
876    /// Similarly to [`Self::apply`], calls `f` on this node and all its inputs,
877    /// including subqueries that may appear in expressions such as `IN (SELECT
878    /// ...)`.
879    pub fn apply_with_subqueries<F: FnMut(&Self) -> Result<TreeNodeRecursion>>(
880        &self,
881        mut f: F,
882    ) -> Result<TreeNodeRecursion> {
883        #[cfg_attr(feature = "recursive_protection", recursive::recursive)]
884        fn apply_with_subqueries_impl<
885            F: FnMut(&LogicalPlan) -> Result<TreeNodeRecursion>,
886        >(
887            node: &LogicalPlan,
888            f: &mut F,
889        ) -> Result<TreeNodeRecursion> {
890            f(node)?.visit_children(|| {
891                node.apply_subqueries(|c| apply_with_subqueries_impl(c, f))?
892                    .visit_sibling(|| {
893                        node.apply_children(|c| apply_with_subqueries_impl(c, f))
894                    })
895            })
896        }
897
898        apply_with_subqueries_impl(self, &mut f)
899    }
900
901    /// Similarly to [`Self::transform`], rewrites this node and its inputs using `f`,
902    /// including subqueries that may appear in expressions such as `IN (SELECT
903    /// ...)`.
904    pub fn transform_with_subqueries<F: FnMut(Self) -> Result<Transformed<Self>>>(
905        self,
906        f: F,
907    ) -> Result<Transformed<Self>> {
908        self.transform_up_with_subqueries(f)
909    }
910
911    /// Similarly to [`Self::transform_down`], rewrites this node and its inputs using `f`,
912    /// including subqueries that may appear in expressions such as `IN (SELECT
913    /// ...)`.
914    pub fn transform_down_with_subqueries<F: FnMut(Self) -> Result<Transformed<Self>>>(
915        self,
916        mut f: F,
917    ) -> Result<Transformed<Self>> {
918        #[cfg_attr(feature = "recursive_protection", recursive::recursive)]
919        fn transform_down_with_subqueries_impl<
920            F: FnMut(LogicalPlan) -> Result<Transformed<LogicalPlan>>,
921        >(
922            node: LogicalPlan,
923            f: &mut F,
924        ) -> Result<Transformed<LogicalPlan>> {
925            f(node)?.transform_children(|n| {
926                n.map_subqueries(|c| transform_down_with_subqueries_impl(c, f))?
927                    .transform_sibling(|n| {
928                        n.map_children(|c| transform_down_with_subqueries_impl(c, f))
929                    })
930            })
931        }
932
933        transform_down_with_subqueries_impl(self, &mut f)
934    }
935
936    /// Similarly to [`Self::transform_up`], rewrites this node and its inputs using `f`,
937    /// including subqueries that may appear in expressions such as `IN (SELECT
938    /// ...)`.
939    pub fn transform_up_with_subqueries<F: FnMut(Self) -> Result<Transformed<Self>>>(
940        self,
941        mut f: F,
942    ) -> Result<Transformed<Self>> {
943        #[cfg_attr(feature = "recursive_protection", recursive::recursive)]
944        fn transform_up_with_subqueries_impl<
945            F: FnMut(LogicalPlan) -> Result<Transformed<LogicalPlan>>,
946        >(
947            node: LogicalPlan,
948            f: &mut F,
949        ) -> Result<Transformed<LogicalPlan>> {
950            node.map_subqueries(|c| transform_up_with_subqueries_impl(c, f))?
951                .transform_sibling(|n| {
952                    n.map_children(|c| transform_up_with_subqueries_impl(c, f))
953                })?
954                .transform_parent(f)
955        }
956
957        transform_up_with_subqueries_impl(self, &mut f)
958    }
959
960    /// Similarly to [`Self::transform_down`], rewrites this node and its inputs using `f`,
961    /// including subqueries that may appear in expressions such as `IN (SELECT
962    /// ...)`.
963    pub fn transform_down_up_with_subqueries<
964        FD: FnMut(Self) -> Result<Transformed<Self>>,
965        FU: FnMut(Self) -> Result<Transformed<Self>>,
966    >(
967        self,
968        mut f_down: FD,
969        mut f_up: FU,
970    ) -> Result<Transformed<Self>> {
971        #[cfg_attr(feature = "recursive_protection", recursive::recursive)]
972        fn transform_down_up_with_subqueries_impl<
973            FD: FnMut(LogicalPlan) -> Result<Transformed<LogicalPlan>>,
974            FU: FnMut(LogicalPlan) -> Result<Transformed<LogicalPlan>>,
975        >(
976            node: LogicalPlan,
977            f_down: &mut FD,
978            f_up: &mut FU,
979        ) -> Result<Transformed<LogicalPlan>> {
980            handle_transform_recursion!(
981                f_down(node),
982                |c| transform_down_up_with_subqueries_impl(c, f_down, f_up),
983                f_up
984            )
985        }
986
987        transform_down_up_with_subqueries_impl(self, &mut f_down, &mut f_up)
988    }
989
990    /// Similarly to [`Self::apply`], calls `f` on this node and its inputs,
991    /// including subqueries that may appear in expressions such as `IN (SELECT
992    /// ...)`.
993    pub fn apply_subqueries<F: FnMut(&Self) -> Result<TreeNodeRecursion>>(
994        &self,
995        mut f: F,
996    ) -> Result<TreeNodeRecursion> {
997        self.apply_expressions(|expr| {
998            expr.apply(|expr| match expr {
999                Expr::Exists(Exists { subquery, .. })
1000                | Expr::InSubquery(InSubquery { subquery, .. })
1001                | Expr::SetComparison(SetComparison { subquery, .. })
1002                | Expr::ScalarSubquery(subquery) => {
1003                    // Wrap in LogicalPlan::Subquery to match f's signature
1004                    f(&LogicalPlan::Subquery(subquery.clone()))
1005                }
1006                _ => Ok(TreeNodeRecursion::Continue),
1007            })
1008        })
1009    }
1010
1011    /// Returns true if any expression in this node contains a subquery
1012    /// (Exists, InSubquery, SetComparison, or ScalarSubquery).
1013    fn has_subquery_expressions(&self) -> bool {
1014        let mut found = false;
1015        let _ = self.apply_expressions(|expr| {
1016            if found {
1017                return Ok(TreeNodeRecursion::Stop);
1018            }
1019            expr.apply(|e| {
1020                if matches!(
1021                    e,
1022                    Expr::Exists(_)
1023                        | Expr::InSubquery(_)
1024                        | Expr::SetComparison(_)
1025                        | Expr::ScalarSubquery(_)
1026                ) {
1027                    found = true;
1028                    Ok(TreeNodeRecursion::Stop)
1029                } else {
1030                    Ok(TreeNodeRecursion::Continue)
1031                }
1032            })
1033        });
1034        found
1035    }
1036
1037    /// Similarly to [`Self::map_children`], rewrites all subqueries that may
1038    /// appear in expressions such as `IN (SELECT ...)` using `f`.
1039    ///
1040    /// Returns the current node.
1041    pub fn map_subqueries<F: FnMut(Self) -> Result<Transformed<Self>>>(
1042        self,
1043        mut f: F,
1044    ) -> Result<Transformed<Self>> {
1045        // Fast path: skip the expensive ownership-based expression traversal
1046        // when this node has no subquery expressions. This avoids
1047        // map_expressions → transform_down walking every expression node
1048        // via consume+recreate just to find no subqueries.
1049        if !self.has_subquery_expressions() {
1050            return Ok(Transformed::no(self));
1051        }
1052
1053        self.map_expressions(|expr| {
1054            expr.transform_down(|expr| match expr {
1055                Expr::Exists(Exists { subquery, negated }) => {
1056                    f(LogicalPlan::Subquery(subquery))?.map_data(|s| match s {
1057                        LogicalPlan::Subquery(subquery) => {
1058                            Ok(Expr::Exists(Exists { subquery, negated }))
1059                        }
1060                        _ => internal_err!("Transformation should return Subquery"),
1061                    })
1062                }
1063                Expr::InSubquery(InSubquery {
1064                    expr,
1065                    subquery,
1066                    negated,
1067                }) => f(LogicalPlan::Subquery(subquery))?.map_data(|s| match s {
1068                    LogicalPlan::Subquery(subquery) => Ok(Expr::InSubquery(InSubquery {
1069                        expr,
1070                        subquery,
1071                        negated,
1072                    })),
1073                    _ => internal_err!("Transformation should return Subquery"),
1074                }),
1075                Expr::SetComparison(SetComparison {
1076                    expr,
1077                    subquery,
1078                    op,
1079                    quantifier,
1080                }) => f(LogicalPlan::Subquery(subquery))?.map_data(|s| match s {
1081                    LogicalPlan::Subquery(subquery) => {
1082                        Ok(Expr::SetComparison(SetComparison {
1083                            expr,
1084                            subquery,
1085                            op,
1086                            quantifier,
1087                        }))
1088                    }
1089                    _ => internal_err!("Transformation should return Subquery"),
1090                }),
1091                Expr::ScalarSubquery(subquery) => f(LogicalPlan::Subquery(subquery))?
1092                    .map_data(|s| match s {
1093                        LogicalPlan::Subquery(subquery) => {
1094                            Ok(Expr::ScalarSubquery(subquery))
1095                        }
1096                        _ => internal_err!("Transformation should return Subquery"),
1097                    }),
1098                _ => Ok(Transformed::no(expr)),
1099            })
1100        })
1101    }
1102
1103    /// Similar to [`Self::map_subqueries`], but only applies `f` to
1104    /// uncorrelated subqueries (those with no outer column references).
1105    pub fn map_uncorrelated_subqueries<F: FnMut(Self) -> Result<Transformed<Self>>>(
1106        self,
1107        mut f: F,
1108    ) -> Result<Transformed<Self>> {
1109        self.map_subqueries(|subquery_plan| match &subquery_plan {
1110            LogicalPlan::Subquery(sq) if sq.outer_ref_columns.is_empty() => {
1111                f(subquery_plan)
1112            }
1113            _ => Ok(Transformed::no(subquery_plan)),
1114        })
1115    }
1116}