Skip to main content

datafusion_expr/logical_plan/
plan.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//! Logical plan types
6
7use std::cmp::Ordering;
8use std::collections::{BTreeSet, HashMap, HashSet};
9use std::fmt::{self, Debug, Display, Formatter};
10use std::hash::{Hash, Hasher};
11use std::sync::{Arc, LazyLock};
12
13use super::dml::CopyTo;
14use super::invariants::{
15    InvariantLevel, assert_always_invariants_at_current_node,
16    assert_executable_invariants,
17};
18use super::{DdlStatement, information_schema};
19use crate::builder::{unique_field_aliases, unnest_with_options};
20use crate::expr::{
21    Alias, Placeholder, Sort as SortExpr, WindowFunction, WindowFunctionParams,
22};
23use crate::expr_rewriter::{
24    NamePreserver, create_col_from_scalar_expr, normalize_cols, normalize_sorts,
25};
26use crate::logical_plan::display::{GraphvizVisitor, IndentVisitor};
27use crate::logical_plan::extension::UserDefinedLogicalNode;
28use crate::logical_plan::materialized_cte::{
29    MaterializedCte, MaterializedCtePlan, MaterializedCteScan,
30};
31use crate::logical_plan::{DmlStatement, Statement, WriteOp};
32use crate::type_coercion::other::coerce_union_type;
33use crate::utils::{
34    check_aggregate_and_window_nesting, check_no_window_functions,
35    enumerate_grouping_sets, expr_to_columns, exprlist_to_fields,
36    find_out_reference_exprs, get_unnested_list_field, grouping_set_expr_count,
37    grouping_set_to_exprlist, merge_schema, passthrough_field_index, split_conjunction,
38};
39use crate::{
40    BinaryExpr, CreateMemoryTable, CreateView, Execute, Expr, ExprSchemable, GroupingSet,
41    LogicalPlanBuilder, Operator, Prepare, TableProviderFilterPushDown, TableSource,
42    WindowFunctionDefinition, build_asof_join_schema, build_join_schema, expr_vec_fmt,
43    requalify_sides_if_needed,
44};
45
46use crate::logical_plan::information_schema::ColumnsDetail;
47use crate::statistics::StatisticsRequest;
48use arrow::compute::SortOptions;
49use arrow::datatypes::{DataType, Field, FieldRef, Schema, SchemaRef};
50use datafusion_common::cse::{NormalizeEq, Normalizeable};
51use datafusion_common::format::{ExplainAnalyzeCategories, ExplainFormat, MetricType};
52use datafusion_common::metadata::{
53    check_metadata_with_storage_equal, merge_metadata_for_union,
54};
55use datafusion_common::tree_node::{
56    Transformed, TreeNode, TreeNodeContainer, TreeNodeRecursion,
57};
58use datafusion_common::{
59    Column, Constraints, DFSchema, DFSchemaRef, DataFusionError, Dependency,
60    FunctionalDependence, FunctionalDependencies, NullEquality, ParamValues, Result,
61    ScalarValue, Spans, SplitPoint, TableReference, UnnestOptions,
62    aggregate_functional_dependencies, assert_eq_or_internal_err, assert_or_internal_err,
63    internal_err, plan_datafusion_err, plan_err, validate_range_split_points,
64};
65use itertools::Itertools as _;
66
67// backwards compatibility
68use crate::display::PgJsonVisitor;
69pub use datafusion_common::display::{PlanType, StringifiedPlan, ToStringifiedPlan};
70pub use datafusion_common::{JoinConstraint, JoinType};
71
72/// A `LogicalPlan` is a node in a tree of relational operators (such as
73/// Projection or Filter).
74///
75/// Represents transforming an input relation (table) to an output relation
76/// (table) with a potentially different schema. Plans form a dataflow tree
77/// where data flows from leaves up to the root to produce the query result.
78///
79/// `LogicalPlan`s can be created by the SQL query planner, the DataFrame API,
80/// or programmatically (for example custom query languages).
81///
82/// # See also:
83/// * [`Expr`]: For the expressions that are evaluated by the plan
84/// * [`LogicalPlanBuilder`]: For building `LogicalPlan`s
85/// * [`tree_node`]: To inspect and rewrite `LogicalPlan`s
86///
87/// [`tree_node`]: crate::logical_plan::tree_node
88///
89/// # Examples
90///
91/// ## Creating a LogicalPlan from SQL:
92///
93/// See [`SessionContext::sql`](https://docs.rs/datafusion/latest/datafusion/execution/context/struct.SessionContext.html#method.sql)
94///
95/// ## Creating a LogicalPlan from the DataFrame API:
96///
97/// See [`DataFrame::logical_plan`](https://docs.rs/datafusion/latest/datafusion/dataframe/struct.DataFrame.html#method.logical_plan)
98///
99/// ## Creating a LogicalPlan programmatically:
100///
101/// See [`LogicalPlanBuilder`]
102///
103/// # Visiting and Rewriting `LogicalPlan`s
104///
105/// Using the [`tree_node`] API, you can recursively walk all nodes in a
106/// `LogicalPlan`. [`TreeNode::apply`] visits a node before its inputs. For
107/// example, to find table names and expressions in a plan:
108///
109/// ```
110/// # use std::collections::HashSet;
111/// # use arrow::datatypes::{DataType, Field, Schema};
112/// # use datafusion_expr::{Expr, col, lit, LogicalPlan, LogicalPlanBuilder, table_scan};
113/// # use datafusion_common::tree_node::{TreeNodeRecursion, TreeNode};
114/// # use datafusion_common::{Column, Result};
115/// # fn employee_schema() -> Schema {
116/// #    Schema::new(vec![
117/// #           Field::new("name", DataType::Utf8, false),
118/// #           Field::new("salary", DataType::Int32, false),
119/// #       ])
120/// #   }
121/// // Projection(name, salary)
122/// //   Filter(salary > 1000)
123/// //     TableScan(employee)
124/// # fn main() -> Result<()> {
125/// let plan = table_scan(Some("employee"), &employee_schema(), None)?
126///  .filter(col("salary").gt(lit(1000)))?
127///  .project(vec![col("name"), col("salary")])?
128///  .build()?;
129///
130/// // use apply to walk the plan and collect table names and expressions
131/// let mut table_names = HashSet::new();
132/// let mut expressions = HashSet::new();
133/// plan.apply(|node| {
134///   if let LogicalPlan::TableScan(scan) = node {
135///     table_names.insert(scan.table_name.to_string());
136///   }
137///   // collect all expressions in the plan
138///   node.apply_expressions(|expr| {
139///    expressions.insert(expr.clone());
140///    Ok(TreeNodeRecursion::Continue) // control walk of expressions
141///   })?;
142///   Ok(TreeNodeRecursion::Continue) // control walk of plan nodes
143/// })?;
144///
145/// assert_eq!(table_names, HashSet::from(["employee".to_string()]));
146/// // we found the expression in projection and filter
147/// assert_eq!(expressions.len(), 3);
148/// println!("Found expressions: {:?}", expressions);
149/// // found predicate in the Filter: employee.salary > 1000
150/// let salary = Expr::Column(Column::new(Some("employee"), "salary"));
151/// assert!(expressions.contains(&salary.gt(lit(1000))));
152/// // found projection in the Projection: employee.name, employee.salary
153/// let name = Expr::Column(Column::new(Some("employee"), "name"));
154/// let salary = Expr::Column(Column::new(Some("employee"), "salary"));
155/// assert!(expressions.contains(&name));
156/// assert!(expressions.contains(&salary));
157/// # Ok(())
158/// # }
159/// ```
160///
161/// [`TreeNode::apply`] and [`TreeNode::rewrite`] traverse plan inputs, but do
162/// not visit subqueries embedded in expressions. Use
163/// [`LogicalPlan::apply_with_subqueries`] and
164/// [`LogicalPlan::rewrite_with_subqueries`] to include those subqueries.
165///
166/// You can also rewrite plans using the [`tree_node`] API. For example, to
167/// replace the filter predicate in a plan:
168///
169/// ```
170/// # use std::collections::HashSet;
171/// # use arrow::datatypes::{DataType, Field, Schema};
172/// # use datafusion_expr::{Expr, col, lit, LogicalPlan, LogicalPlanBuilder, table_scan};
173/// # use datafusion_common::tree_node::{TreeNodeRecursion, TreeNode};
174/// # use datafusion_common::{Column, Result};
175/// # fn employee_schema() -> Schema {
176/// #    Schema::new(vec![
177/// #           Field::new("name", DataType::Utf8, false),
178/// #           Field::new("salary", DataType::Int32, false),
179/// #       ])
180/// #   }
181/// // Projection(name, salary)
182/// //   Filter(salary > 1000)
183/// //     TableScan(employee)
184/// # fn main() -> Result<()> {
185/// use datafusion_common::tree_node::Transformed;
186/// let plan = table_scan(Some("employee"), &employee_schema(), None)?
187///  .filter(col("salary").gt(lit(1000)))?
188///  .project(vec![col("name"), col("salary")])?
189///  .build()?;
190///
191/// // use transform to rewrite the plan
192/// let transformed_result = plan.transform(|node| {
193///   // when we see the filter node
194///   if let LogicalPlan::Filter(mut filter) = node {
195///     // replace predicate with salary < 2000
196///     filter.predicate = Expr::Column(Column::new(Some("employee"), "salary")).lt(lit(2000));
197///     let new_plan = LogicalPlan::Filter(filter);
198///     return Ok(Transformed::yes(new_plan)); // communicate the node was changed
199///   }
200///   // return the node unchanged
201///   Ok(Transformed::no(node))
202/// }).unwrap();
203///
204/// // Transformed result contains rewritten plan and information about
205/// // whether the plan was changed
206/// assert!(transformed_result.transformed);
207/// let rewritten_plan = transformed_result.data;
208///
209/// // we found the filter
210/// assert_eq!(rewritten_plan.display_indent().to_string(),
211/// "Projection: employee.name, employee.salary\
212/// \n  Filter: employee.salary < Int32(2000)\
213/// \n    TableScan: employee");
214/// # Ok(())
215/// # }
216/// ```
217///
218/// For more control over traversal, implement a [`TreeNodeRewriter`] and use
219/// [`TreeNode::rewrite`]. Its `f_down` method runs before rewriting inputs and
220/// `f_up` runs after them. The following example removes Filter nodes in
221/// `f_up` by replacing each with its already rewritten input. This changes
222/// query semantics and is only an illustration of the API.
223///
224/// ```
225/// # use arrow::datatypes::{DataType, Field, Schema};
226/// # use datafusion_expr::{col, lit, LogicalPlan, table_scan};
227/// # use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRewriter};
228/// # use datafusion_common::Result;
229/// # fn main() -> Result<()> {
230/// # let schema = Schema::new(vec![
231/// #     Field::new("name", DataType::Utf8, false),
232/// #     Field::new("salary", DataType::Int32, false),
233/// # ]);
234/// let plan = table_scan(Some("employee"), &schema, None)?
235///     .filter(col("salary").gt(lit(1000)))?
236///     .project(vec![col("name"), col("salary")])?
237///     .build()?;
238///
239/// struct RemoveFilters;
240///
241/// impl TreeNodeRewriter for RemoveFilters {
242///     type Node = LogicalPlan;
243///
244///     fn f_up(&mut self, node: LogicalPlan) -> Result<Transformed<LogicalPlan>> {
245///         match node {
246///             LogicalPlan::Filter(filter) => {
247///                 Ok(Transformed::yes(filter.input.as_ref().clone()))
248///             }
249///             _ => Ok(Transformed::no(node)),
250///         }
251///     }
252/// }
253///
254/// let rewritten = plan.rewrite(&mut RemoveFilters)?;
255/// assert!(rewritten.transformed);
256/// assert_eq!(rewritten.data.display_indent().to_string(),
257///     "Projection: employee.name, employee.salary\n  TableScan: employee");
258/// # Ok(())
259/// # }
260/// ```
261///
262/// See the [plan walking example] for a complete walkthrough, including
263/// collecting tables and filter predicates from subqueries.
264///
265/// [`TreeNodeRewriter`]: datafusion_common::tree_node::TreeNodeRewriter
266/// [plan walking example]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/query_planning/plan_walk.rs
267#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
268pub enum LogicalPlan {
269    /// Evaluates an arbitrary list of expressions (essentially a
270    /// SELECT with an expression list) on its input.
271    Projection(Projection),
272    /// Filters rows from its input that do not match an
273    /// expression (essentially a WHERE clause with a predicate
274    /// expression).
275    ///
276    /// Semantically, `<predicate>` is evaluated for each row of the
277    /// input; If the value of `<predicate>` is true, the input row is
278    /// passed to the output. If the value of `<predicate>` is false
279    /// (or null), the row is discarded.
280    Filter(Filter),
281    /// Windows input based on a set of window spec and window
282    /// function (e.g. SUM or RANK).  This is used to implement SQL
283    /// window functions, and the `OVER` clause.
284    ///
285    /// See [`Window`] for more details
286    Window(Window),
287    /// Aggregates its input based on a set of grouping and aggregate
288    /// expressions (e.g. SUM). This is used to implement SQL aggregates
289    /// and `GROUP BY`.
290    ///
291    /// See [`Aggregate`] for more details
292    Aggregate(Aggregate),
293    /// Sorts its input according to a list of sort expressions. This
294    /// is used to implement SQL `ORDER BY`
295    Sort(Sort),
296    /// Join two logical plans on one or more join columns.
297    /// This is used to implement SQL `JOIN`
298    Join(Join),
299    /// Repartitions the input based on a partitioning scheme. This is
300    /// used to add parallelism and is sometimes referred to as an
301    /// "exchange" operator in other systems
302    Repartition(Repartition),
303    /// Union multiple inputs with the same schema into a single
304    /// output stream. This is used to implement SQL `UNION [ALL]` and
305    /// `INTERSECT [ALL]`.
306    Union(Union),
307    /// Produces rows from a [`TableSource`], used to implement SQL
308    /// `FROM` tables or views.
309    TableScan(TableScan),
310    /// Produces no rows: An empty relation with an empty schema that
311    /// produces 0 or 1 row. This is used to implement SQL `SELECT`
312    /// that has no values in the `FROM` clause.
313    EmptyRelation(EmptyRelation),
314    /// Produces the output of running another query.  This is used to
315    /// implement SQL subqueries
316    Subquery(Subquery),
317    /// Aliased relation provides, or changes, the name of a relation.
318    SubqueryAlias(SubqueryAlias),
319    /// Skip some number of rows, and then fetch some number of rows.
320    Limit(Limit),
321    /// A DataFusion [`Statement`] such as `SET VARIABLE` or `START TRANSACTION`
322    Statement(Statement),
323    /// Values expression. See
324    /// [Postgres VALUES](https://www.postgresql.org/docs/current/queries-values.html)
325    /// documentation for more details. This is used to implement SQL such as
326    /// `VALUES (1, 2), (3, 4)`
327    Values(Values),
328    /// Produces a relation with string representations of
329    /// various parts of the plan. This is used to implement SQL `EXPLAIN`.
330    Explain(Explain),
331    /// Runs the input, and prints annotated physical plan as a string
332    /// with execution metric. This is used to implement SQL
333    /// `EXPLAIN ANALYZE`.
334    Analyze(Analyze),
335    /// Extension operator defined outside of DataFusion. This is used
336    /// to extend DataFusion with custom relational operations that
337    Extension(Extension),
338    /// Remove duplicate rows from the input. This is used to
339    /// implement SQL `SELECT DISTINCT ...`.
340    Distinct(Distinct),
341    /// Data Manipulation Language (DML): Insert / Update / Delete
342    Dml(DmlStatement),
343    /// Data Definition Language (DDL): CREATE / DROP TABLES / VIEWS / SCHEMAS
344    Ddl(DdlStatement),
345    /// `COPY TO` for writing plan results to files
346    Copy(CopyTo),
347    /// A `SHOW`-class SQL statement: `SHOW TABLES`, `SHOW COLUMNS`,
348    /// `SHOW FUNCTIONS`, `SHOW <variable>`, `SHOW CREATE TABLE`, and
349    /// `DESCRIBE` (MySQL's alias for `SHOW COLUMNS FROM`).
350    Show(Show),
351    /// Unnest a column that contains a nested list type such as an
352    /// ARRAY. This is used to implement SQL `UNNEST`
353    Unnest(Unnest),
354    /// A variadic query (e.g. "Recursive CTEs")
355    RecursiveQuery(RecursiveQuery),
356    /// Match each left row with at most one ordered row from the right input.
357    /// This is used to implement SQL `ASOF JOIN`.
358    AsOfJoin(AsOfJoin),
359    /// A node of a SQL `WITH x AS MATERIALIZED (...)` CTE. See
360    /// [`MaterializedCtePlan`].
361    MaterializedCte(MaterializedCtePlan),
362}
363
364impl Default for LogicalPlan {
365    fn default() -> Self {
366        // `Default` is used as a transient placeholder on hot paths (e.g.
367        // `Box`/`Arc` `map_elements`), so use a shared empty schema to avoid
368        // allocating.
369        LogicalPlan::EmptyRelation(EmptyRelation {
370            produce_one_row: false,
371            schema: Arc::clone(DFSchema::empty_ref()),
372        })
373    }
374}
375
376impl<'a> TreeNodeContainer<'a, Self> for LogicalPlan {
377    fn apply_elements<F: FnMut(&'a Self) -> Result<TreeNodeRecursion>>(
378        &'a self,
379        mut f: F,
380    ) -> Result<TreeNodeRecursion> {
381        f(self)
382    }
383
384    fn map_elements<F: FnMut(Self) -> Result<Transformed<Self>>>(
385        self,
386        mut f: F,
387    ) -> Result<Transformed<Self>> {
388        f(self)
389    }
390}
391
392impl LogicalPlan {
393    /// Get a reference to the logical plan's schema
394    pub fn schema(&self) -> &DFSchemaRef {
395        match self {
396            LogicalPlan::EmptyRelation(EmptyRelation { schema, .. }) => schema,
397            LogicalPlan::Values(Values { schema, .. }) => schema,
398            LogicalPlan::TableScan(TableScan {
399                projected_schema, ..
400            }) => projected_schema,
401            LogicalPlan::Projection(Projection { schema, .. }) => schema,
402            LogicalPlan::Filter(Filter { input, .. }) => input.schema(),
403            LogicalPlan::Distinct(Distinct::All(input)) => input.schema(),
404            LogicalPlan::Distinct(Distinct::On(DistinctOn { schema, .. })) => schema,
405            LogicalPlan::Window(Window { schema, .. }) => schema,
406            LogicalPlan::Aggregate(Aggregate { schema, .. }) => schema,
407            LogicalPlan::Sort(Sort { input, .. }) => input.schema(),
408            LogicalPlan::Join(Join { schema, .. }) => schema,
409            LogicalPlan::AsOfJoin(AsOfJoin { schema, .. }) => schema,
410            LogicalPlan::Repartition(Repartition { input, .. }) => input.schema(),
411            LogicalPlan::Limit(Limit { input, .. }) => input.schema(),
412            LogicalPlan::Statement(statement) => statement.schema(),
413            LogicalPlan::Subquery(Subquery { subquery, .. }) => subquery.schema(),
414            LogicalPlan::SubqueryAlias(SubqueryAlias { schema, .. }) => schema,
415            LogicalPlan::Explain(explain) => &explain.schema,
416            LogicalPlan::Analyze(analyze) => &analyze.schema,
417            LogicalPlan::Extension(extension) => extension.node.schema(),
418            LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => cte.schema(),
419            LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) => &scan.schema,
420            LogicalPlan::Union(Union { schema, .. }) => schema,
421            LogicalPlan::Show(Show { output_schema, .. }) => output_schema,
422            LogicalPlan::Dml(DmlStatement { output_schema, .. }) => output_schema,
423            LogicalPlan::Copy(CopyTo { output_schema, .. }) => output_schema,
424            LogicalPlan::Ddl(ddl) => ddl.schema(),
425            LogicalPlan::Unnest(Unnest { schema, .. }) => schema,
426            LogicalPlan::RecursiveQuery(RecursiveQuery { schema, .. }) => schema,
427        }
428    }
429
430    /// Used for normalizing columns, as the fallback schemas to the main schema
431    /// of the plan.
432    pub fn fallback_normalize_schemas(&self) -> Vec<&DFSchema> {
433        match self {
434            LogicalPlan::Window(_)
435            | LogicalPlan::Projection(_)
436            | LogicalPlan::Aggregate(_)
437            | LogicalPlan::Unnest(_)
438            | LogicalPlan::Join(_)
439            | LogicalPlan::AsOfJoin(_) => self
440                .inputs()
441                .iter()
442                .map(|input| input.schema().as_ref())
443                .collect(),
444            _ => vec![],
445        }
446    }
447
448    /// Returns the (fixed) output schema for explain plans
449    pub fn explain_schema() -> SchemaRef {
450        SchemaRef::new(Schema::new(vec![
451            Field::new("plan_type", DataType::Utf8, false),
452            Field::new("plan", DataType::Utf8, false),
453        ]))
454    }
455
456    /// Returns the (fixed) output schema for `DESCRIBE` plans
457    pub fn describe_schema() -> Schema {
458        information_schema::columns_schema(ColumnsDetail::Describe)
459    }
460
461    /// Returns all expressions (non-recursively) evaluated by the current
462    /// logical plan node. This does not include expressions in any children.
463    ///
464    /// Note this method `clone`s all the expressions. When possible, the
465    /// [`tree_node`] API should be used instead of this API.
466    ///
467    /// The returned expressions do not necessarily represent or even
468    /// contributed to the output schema of this node. For example,
469    /// `LogicalPlan::Filter` returns the filter expression even though the
470    /// output of a Filter has the same columns as the input.
471    ///
472    /// The expressions do contain all the columns that are used by this plan,
473    /// so if there are columns not referenced by these expressions then
474    /// DataFusion's optimizer attempts to optimize them away.
475    ///
476    /// [`tree_node`]: crate::logical_plan::tree_node
477    pub fn expressions(self: &LogicalPlan) -> Vec<Expr> {
478        let mut exprs = vec![];
479        self.apply_expressions(|e| {
480            exprs.push(e.clone());
481            Ok(TreeNodeRecursion::Continue)
482        })
483        // closure always returns OK
484        .unwrap();
485        exprs
486    }
487
488    /// Returns all the out reference(correlated) expressions (recursively) in the current
489    /// logical plan nodes and all its descendant nodes.
490    pub fn all_out_ref_exprs(self: &LogicalPlan) -> Vec<Expr> {
491        let mut exprs = vec![];
492        self.apply_expressions(|e| {
493            for e in find_out_reference_exprs(e) {
494                if !exprs.contains(&e) {
495                    exprs.push(e)
496                }
497            }
498            Ok(TreeNodeRecursion::Continue)
499        })
500        // closure always returns OK
501        .unwrap();
502        self.inputs()
503            .into_iter()
504            .flat_map(|child| child.all_out_ref_exprs())
505            .for_each(|e| {
506                if !exprs.contains(&e) {
507                    exprs.push(e)
508                }
509            });
510        exprs
511    }
512
513    /// Returns all inputs / children of this `LogicalPlan` node.
514    ///
515    /// Note does not include inputs to inputs, or subqueries.
516    pub fn inputs(&self) -> Vec<&LogicalPlan> {
517        match self {
518            LogicalPlan::Projection(Projection { input, .. }) => vec![input],
519            LogicalPlan::Filter(Filter { input, .. }) => vec![input],
520            LogicalPlan::Repartition(Repartition { input, .. }) => vec![input],
521            LogicalPlan::Window(Window { input, .. }) => vec![input],
522            LogicalPlan::Aggregate(Aggregate { input, .. }) => vec![input],
523            LogicalPlan::Sort(Sort { input, .. }) => vec![input],
524            LogicalPlan::Join(Join { left, right, .. }) => vec![left, right],
525            LogicalPlan::AsOfJoin(AsOfJoin { left, right, .. }) => {
526                vec![left, right]
527            }
528            LogicalPlan::Limit(Limit { input, .. }) => vec![input],
529            LogicalPlan::Subquery(Subquery { subquery, .. }) => vec![subquery],
530            LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => vec![input],
531            LogicalPlan::Extension(extension) => extension.node.inputs(),
532            LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte {
533                cte,
534                continuation,
535                ..
536            })) => vec![cte, continuation],
537            LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => vec![],
538            LogicalPlan::Union(Union { inputs, .. }) => {
539                inputs.iter().map(|arc| arc.as_ref()).collect()
540            }
541            LogicalPlan::Distinct(
542                Distinct::All(input) | Distinct::On(DistinctOn { input, .. }),
543            ) => vec![input],
544            LogicalPlan::Explain(explain) => vec![&explain.plan],
545            LogicalPlan::Analyze(analyze) => vec![&analyze.input],
546            LogicalPlan::Dml(write) => vec![&write.input],
547            LogicalPlan::Copy(copy) => vec![&copy.input],
548            LogicalPlan::Ddl(ddl) => ddl.inputs(),
549            LogicalPlan::Unnest(Unnest { input, .. }) => vec![input],
550            LogicalPlan::RecursiveQuery(RecursiveQuery {
551                static_term,
552                recursive_term,
553                ..
554            }) => vec![static_term, recursive_term],
555            LogicalPlan::Statement(stmt) => stmt.inputs(),
556            // plans without inputs
557            LogicalPlan::TableScan { .. }
558            | LogicalPlan::EmptyRelation { .. }
559            | LogicalPlan::Values { .. }
560            | LogicalPlan::Show(_) => vec![],
561        }
562    }
563
564    /// returns all `Using` join columns in a logical plan
565    pub fn using_columns(&self) -> Result<Vec<HashSet<Column>>, DataFusionError> {
566        let mut using_columns: Vec<HashSet<Column>> = vec![];
567
568        self.apply_with_subqueries(|plan| {
569            let on = match plan {
570                LogicalPlan::Join(Join {
571                    join_constraint: JoinConstraint::Using,
572                    on,
573                    ..
574                })
575                | LogicalPlan::AsOfJoin(AsOfJoin {
576                    join_constraint: JoinConstraint::Using,
577                    on,
578                    ..
579                }) => Some(on),
580                _ => None,
581            };
582            if let Some(on) = on {
583                // The join keys in using-join must be columns.
584                let columns = on.iter().try_fold(
585                    HashSet::with_capacity(on.len() * 2),
586                    |mut accumu, (l, r)| {
587                        let Some(l) = l.get_as_join_column() else {
588                            return internal_err!(
589                                "Invalid join key. Expected column, found {l:?}"
590                            );
591                        };
592                        let Some(r) = r.get_as_join_column() else {
593                            return internal_err!(
594                                "Invalid join key. Expected column, found {r:?}"
595                            );
596                        };
597                        accumu.insert(l.to_owned());
598                        accumu.insert(r.to_owned());
599                        Result::<_, DataFusionError>::Ok(accumu)
600                    },
601                )?;
602                using_columns.push(columns);
603            }
604            Ok(TreeNodeRecursion::Continue)
605        })?;
606
607        Ok(using_columns)
608    }
609
610    /// returns the first output expression of this `LogicalPlan` node.
611    pub fn head_output_expr(&self) -> Result<Option<Expr>> {
612        match self {
613            LogicalPlan::Projection(projection) => {
614                Ok(Some(projection.expr.as_slice()[0].clone()))
615            }
616            LogicalPlan::Aggregate(agg) => {
617                if agg.group_expr.is_empty() {
618                    Ok(Some(agg.aggr_expr.as_slice()[0].clone()))
619                } else {
620                    Ok(Some(agg.group_expr.as_slice()[0].clone()))
621                }
622            }
623            LogicalPlan::Distinct(Distinct::On(DistinctOn { select_expr, .. })) => {
624                Ok(Some(select_expr[0].clone()))
625            }
626            LogicalPlan::Filter(Filter { input, .. })
627            | LogicalPlan::Distinct(Distinct::All(input))
628            | LogicalPlan::Sort(Sort { input, .. })
629            | LogicalPlan::Limit(Limit { input, .. })
630            | LogicalPlan::Repartition(Repartition { input, .. })
631            | LogicalPlan::Window(Window { input, .. }) => input.head_output_expr(),
632            LogicalPlan::Join(Join {
633                left,
634                right,
635                join_type,
636                ..
637            }) => match join_type {
638                JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
639                    if left.schema().fields().is_empty() {
640                        right.head_output_expr()
641                    } else {
642                        left.head_output_expr()
643                    }
644                }
645                JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => {
646                    left.head_output_expr()
647                }
648                JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark => {
649                    right.head_output_expr()
650                }
651            },
652            LogicalPlan::AsOfJoin(AsOfJoin { left, .. }) => left.head_output_expr(),
653            LogicalPlan::RecursiveQuery(RecursiveQuery { static_term, .. }) => {
654                static_term.head_output_expr()
655            }
656            LogicalPlan::Union(union) => Ok(Some(Expr::Column(Column::from(
657                union.schema.qualified_field(0),
658            )))),
659            LogicalPlan::TableScan(table) => Ok(Some(Expr::Column(Column::from(
660                table.projected_schema.qualified_field(0),
661            )))),
662            LogicalPlan::SubqueryAlias(subquery_alias) => {
663                let expr_opt = subquery_alias.input.head_output_expr()?;
664                expr_opt
665                    .map(|expr| {
666                        Ok(Expr::Column(create_col_from_scalar_expr(
667                            &expr,
668                            subquery_alias.alias.to_string(),
669                        )?))
670                    })
671                    .map_or(Ok(None), |v| v.map(Some))
672            }
673            // A materialized CTE outputs the output of its continuation.
674            LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
675                cte.continuation.head_output_expr()
676            }
677            LogicalPlan::Extension(_)
678            | LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => Ok(None),
679            LogicalPlan::Subquery(_) => Ok(None),
680            LogicalPlan::EmptyRelation(_)
681            | LogicalPlan::Statement(_)
682            | LogicalPlan::Values(_)
683            | LogicalPlan::Explain(_)
684            | LogicalPlan::Analyze(_)
685            | LogicalPlan::Dml(_)
686            | LogicalPlan::Copy(_)
687            | LogicalPlan::Ddl(_)
688            | LogicalPlan::Show(_)
689            | LogicalPlan::Unnest(_) => Ok(None),
690        }
691    }
692
693    /// Recomputes schema and type information for this LogicalPlan if needed.
694    ///
695    /// Some `LogicalPlan`s may need to recompute their schema if the number or
696    /// type of expressions have been changed (for example due to type
697    /// coercion). For example [`LogicalPlan::Projection`]s schema depends on
698    /// its expressions.
699    ///
700    /// Some `LogicalPlan`s schema is unaffected by any changes to their
701    /// expressions. For example [`LogicalPlan::Filter`] schema is always the
702    /// same as its input schema.
703    ///
704    /// This is useful after modifying a plans `Expr`s (or input plans) via
705    /// methods such as [Self::map_children] and [Self::map_expressions]. Unlike
706    /// [Self::with_new_exprs], this method does not require a new set of
707    /// expressions or inputs plans.
708    ///
709    /// # Return value
710    /// Returns an error if there is some issue recomputing the schema.
711    ///
712    /// # Notes
713    ///
714    /// * Does not recursively recompute schema for input (child) plans.
715    pub fn recompute_schema(self) -> Result<Self> {
716        match self {
717            // Since expr may be different than the previous expr, schema of the projection
718            // may change. We need to use try_new method instead of try_new_with_schema method.
719            LogicalPlan::Projection(Projection {
720                expr,
721                input,
722                schema: _,
723            }) => Projection::try_new(expr, input).map(LogicalPlan::Projection),
724            LogicalPlan::Dml(_) => Ok(self),
725            LogicalPlan::Copy(_) => Ok(self),
726            LogicalPlan::Values(Values { schema, values }) => {
727                // todo it isn't clear why the schema is not recomputed here
728                Ok(LogicalPlan::Values(Values { schema, values }))
729            }
730            LogicalPlan::Filter(Filter { predicate, input }) => {
731                Filter::try_new(predicate, input).map(LogicalPlan::Filter)
732            }
733            LogicalPlan::Repartition(_) => Ok(self),
734            LogicalPlan::Window(Window {
735                input,
736                window_expr,
737                schema: _,
738            }) => Window::try_new(window_expr, input).map(LogicalPlan::Window),
739            LogicalPlan::Aggregate(Aggregate {
740                input,
741                group_expr,
742                aggr_expr,
743                schema: _,
744            }) => Aggregate::try_new(input, group_expr, aggr_expr)
745                .map(LogicalPlan::Aggregate),
746            LogicalPlan::Sort(_) => Ok(self),
747            LogicalPlan::Join(Join {
748                left,
749                right,
750                filter,
751                join_type,
752                join_constraint,
753                on,
754                schema: _,
755                null_equality,
756                null_aware,
757                null_aware_value_keys,
758            }) => {
759                let schema =
760                    build_join_schema(left.schema(), right.schema(), &join_type)?;
761
762                let new_on: Vec<_> = on
763                    .into_iter()
764                    .map(|equi_expr| {
765                        // SimplifyExpression rule may add alias to the equi_expr.
766                        (equi_expr.0.unalias(), equi_expr.1.unalias())
767                    })
768                    .collect();
769
770                Ok(LogicalPlan::Join(Join {
771                    left,
772                    right,
773                    join_type,
774                    join_constraint,
775                    on: new_on,
776                    filter,
777                    schema: DFSchemaRef::new(schema),
778                    null_equality,
779                    null_aware,
780                    null_aware_value_keys,
781                }))
782            }
783            LogicalPlan::AsOfJoin(AsOfJoin {
784                left,
785                right,
786                on,
787                match_condition,
788                join_constraint,
789                schema: _,
790            }) => Ok(LogicalPlan::AsOfJoin(AsOfJoin::try_new(
791                left,
792                right,
793                on.into_iter()
794                    .map(|(left, right)| (left.unalias(), right.unalias()))
795                    .collect(),
796                AsOfMatch {
797                    left: match_condition.left.unalias(),
798                    op: match_condition.op,
799                    right: match_condition.right.unalias(),
800                },
801                join_constraint,
802            )?)),
803            LogicalPlan::Subquery(_) => Ok(self),
804            LogicalPlan::SubqueryAlias(SubqueryAlias {
805                input,
806                alias,
807                schema: _,
808            }) => SubqueryAlias::try_new(input, alias).map(LogicalPlan::SubqueryAlias),
809            LogicalPlan::Limit(_) => Ok(self),
810            LogicalPlan::Ddl(_) => Ok(self),
811            // A `Cte` takes the schema of its continuation, and does not store
812            // it. A `Scan` keeps the schema of the CTE body, which also keeps
813            // its schema.
814            LogicalPlan::MaterializedCte(_) => Ok(self),
815            LogicalPlan::Extension(Extension { node }) => {
816                // todo make an API that does not require cloning
817                // This requires a copy of the extension nodes expressions and inputs
818                let expr = node.expressions();
819                let inputs: Vec<_> = node.inputs().into_iter().cloned().collect();
820                Ok(LogicalPlan::Extension(Extension {
821                    node: node.with_exprs_and_inputs(expr, inputs)?,
822                }))
823            }
824            LogicalPlan::Union(Union { inputs, schema }) => {
825                let first_input_schema = inputs[0].schema();
826                if schema.fields().len() == first_input_schema.fields().len() {
827                    // If inputs are not pruned do not change schema
828                    Ok(LogicalPlan::Union(Union { inputs, schema }))
829                } else {
830                    // A note on `Union`s constructed via `try_new_by_name`:
831                    //
832                    // At this point, the schema for each input should have
833                    // the same width. Thus, we do not need to save whether a
834                    // `Union` was created `BY NAME`, and can safely rely on the
835                    // `try_new` initializer to derive the new schema based on
836                    // column positions.
837                    Ok(LogicalPlan::Union(Union::try_new(inputs)?))
838                }
839            }
840            LogicalPlan::Distinct(distinct) => {
841                let distinct = match distinct {
842                    Distinct::All(input) => Distinct::All(input),
843                    Distinct::On(DistinctOn {
844                        on_expr,
845                        select_expr,
846                        sort_expr,
847                        input,
848                        schema: _,
849                    }) => Distinct::On(DistinctOn::try_new(
850                        on_expr,
851                        select_expr,
852                        sort_expr,
853                        input,
854                    )?),
855                };
856                Ok(LogicalPlan::Distinct(distinct))
857            }
858            LogicalPlan::RecursiveQuery(RecursiveQuery {
859                name,
860                static_term,
861                recursive_term,
862                is_distinct,
863                schema: _,
864            }) => RecursiveQuery::try_new(name, static_term, recursive_term, is_distinct)
865                .map(LogicalPlan::RecursiveQuery),
866            LogicalPlan::Analyze(_) => Ok(self),
867            LogicalPlan::Explain(_) => Ok(self),
868            LogicalPlan::TableScan(_) => Ok(self),
869            LogicalPlan::EmptyRelation(_) => Ok(self),
870            LogicalPlan::Statement(_) => Ok(self),
871            LogicalPlan::Show(_) => Ok(self),
872            LogicalPlan::Unnest(Unnest {
873                input,
874                exec_columns,
875                options,
876                ..
877            }) => {
878                // Update schema with unnested column type.
879                unnest_with_options(Arc::unwrap_or_clone(input), exec_columns, options)
880            }
881        }
882    }
883
884    /// Returns a new `LogicalPlan` based on `self` with inputs and
885    /// expressions replaced.
886    ///
887    /// Note this method creates an entirely new node, which requires a large
888    /// amount of clone'ing. When possible, the [`tree_node`] API should be used
889    /// instead of this API.
890    ///
891    /// The exprs correspond to the same order of expressions returned
892    /// by [`Self::expressions`]. This function is used by optimizers
893    /// to rewrite plans using the following pattern:
894    ///
895    /// [`tree_node`]: crate::logical_plan::tree_node
896    ///
897    /// ```text
898    /// let new_inputs = optimize_children(..., plan, props);
899    ///
900    /// // get the plans expressions to optimize
901    /// let exprs = plan.expressions();
902    ///
903    /// // potentially rewrite plan expressions
904    /// let rewritten_exprs = rewrite_exprs(exprs);
905    ///
906    /// // create new plan using rewritten_exprs in same position
907    /// let new_plan = plan.new_with_exprs(rewritten_exprs, new_inputs);
908    /// ```
909    pub fn with_new_exprs(
910        &self,
911        mut expr: Vec<Expr>,
912        inputs: Vec<LogicalPlan>,
913    ) -> Result<LogicalPlan> {
914        match self {
915            // Since expr may be different than the previous expr, schema of the projection
916            // may change. We need to use try_new method instead of try_new_with_schema method.
917            LogicalPlan::Projection(Projection { .. }) => {
918                let input = self.only_input(inputs)?;
919                Projection::try_new(expr, Arc::new(input)).map(LogicalPlan::Projection)
920            }
921            LogicalPlan::Dml(DmlStatement {
922                table_name,
923                target,
924                op,
925                ..
926            }) => {
927                let input = self.only_input(inputs)?;
928                let op = match op {
929                    WriteOp::MergeInto(merge_op) => {
930                        WriteOp::MergeInto(Box::new(merge_op.with_new_exprs(expr)?))
931                    }
932                    other => {
933                        self.assert_no_expressions(expr)?;
934                        other.clone()
935                    }
936                };
937                Ok(LogicalPlan::Dml(DmlStatement::new(
938                    table_name.clone(),
939                    Arc::clone(target),
940                    op,
941                    Arc::new(input),
942                )))
943            }
944            LogicalPlan::Copy(CopyTo {
945                input: _,
946                output_url,
947                file_type,
948                options,
949                partition_by,
950                output_schema: _,
951            }) => {
952                self.assert_no_expressions(expr)?;
953                let input = self.only_input(inputs)?;
954                Ok(LogicalPlan::Copy(CopyTo::new(
955                    Arc::new(input),
956                    output_url.clone(),
957                    partition_by.clone(),
958                    Arc::clone(file_type),
959                    options.clone(),
960                )))
961            }
962            LogicalPlan::Values(Values { schema, .. }) => {
963                self.assert_no_inputs(inputs)?;
964                Ok(LogicalPlan::Values(Values {
965                    schema: Arc::clone(schema),
966                    values: expr
967                        .chunks_exact(schema.fields().len())
968                        .map(|s| s.to_vec())
969                        .collect(),
970                }))
971            }
972            LogicalPlan::Filter { .. } => {
973                let predicate = self.only_expr(expr)?;
974                let input = self.only_input(inputs)?;
975
976                Filter::try_new(predicate, Arc::new(input)).map(LogicalPlan::Filter)
977            }
978            LogicalPlan::Repartition(Repartition {
979                partitioning_scheme,
980                ..
981            }) => match partitioning_scheme {
982                Partitioning::RoundRobinBatch(n) => {
983                    self.assert_no_expressions(expr)?;
984                    let input = self.only_input(inputs)?;
985                    Ok(LogicalPlan::Repartition(Repartition {
986                        partitioning_scheme: Partitioning::RoundRobinBatch(*n),
987                        input: Arc::new(input),
988                    }))
989                }
990                Partitioning::Hash(_, n) => {
991                    let input = self.only_input(inputs)?;
992                    Ok(LogicalPlan::Repartition(Repartition {
993                        partitioning_scheme: Partitioning::Hash(expr, *n),
994                        input: Arc::new(input),
995                    }))
996                }
997                Partitioning::Range(range) => {
998                    if expr.len() != range.ordering().len() {
999                        return internal_err!(
1000                            "Incorrect number of expressions for Range partitioning"
1001                        );
1002                    }
1003                    let input = self.only_input(inputs)?;
1004                    let ordering = range
1005                        .ordering()
1006                        .iter()
1007                        .zip(expr)
1008                        .map(|(sort_expr, expr)| SortExpr {
1009                            expr,
1010                            asc: sort_expr.asc,
1011                            nulls_first: sort_expr.nulls_first,
1012                        })
1013                        .collect();
1014                    let range = RangePartitioning::try_new(
1015                        ordering,
1016                        range.split_points().to_vec(),
1017                    )?;
1018                    Ok(LogicalPlan::Repartition(Repartition {
1019                        partitioning_scheme: Partitioning::Range(range),
1020                        input: Arc::new(input),
1021                    }))
1022                }
1023                Partitioning::DistributeBy(_) => {
1024                    let input = self.only_input(inputs)?;
1025                    Ok(LogicalPlan::Repartition(Repartition {
1026                        partitioning_scheme: Partitioning::DistributeBy(expr),
1027                        input: Arc::new(input),
1028                    }))
1029                }
1030            },
1031            LogicalPlan::Window(Window { window_expr, .. }) => {
1032                assert_eq!(window_expr.len(), expr.len());
1033                let input = self.only_input(inputs)?;
1034                Window::try_new(expr, Arc::new(input)).map(LogicalPlan::Window)
1035            }
1036            LogicalPlan::Aggregate(Aggregate { group_expr, .. }) => {
1037                let input = self.only_input(inputs)?;
1038                // group exprs are the first expressions
1039                let agg_expr = expr.split_off(group_expr.len());
1040
1041                Aggregate::try_new(Arc::new(input), expr, agg_expr)
1042                    .map(LogicalPlan::Aggregate)
1043            }
1044            LogicalPlan::Sort(Sort {
1045                expr: sort_expr,
1046                fetch,
1047                ..
1048            }) => {
1049                let input = self.only_input(inputs)?;
1050                Ok(LogicalPlan::Sort(Sort {
1051                    expr: expr
1052                        .into_iter()
1053                        .zip(sort_expr.iter())
1054                        .map(|(expr, sort)| sort.with_expr(expr))
1055                        .collect(),
1056                    input: Arc::new(input),
1057                    fetch: *fetch,
1058                }))
1059            }
1060            LogicalPlan::Join(Join {
1061                join_type,
1062                join_constraint,
1063                on,
1064                null_equality,
1065                null_aware,
1066                null_aware_value_keys,
1067                ..
1068            }) => {
1069                let (left, right) = self.only_two_inputs(inputs)?;
1070                let schema = build_join_schema(left.schema(), right.schema(), join_type)?;
1071
1072                let equi_expr_count = on.len() * 2;
1073                assert!(expr.len() >= equi_expr_count);
1074
1075                // Assume that the last expr, if any,
1076                // is the filter_expr (non equality predicate from ON clause)
1077                let filter_expr = if expr.len() > equi_expr_count {
1078                    expr.pop()
1079                } else {
1080                    None
1081                };
1082
1083                // The first part of expr is equi-exprs,
1084                // and the struct of each equi-expr is like `left-expr = right-expr`.
1085                assert_eq!(expr.len(), equi_expr_count);
1086                let mut new_on = Vec::with_capacity(on.len());
1087                let mut iter = expr.into_iter();
1088                while let Some(left) = iter.next() {
1089                    let Some(right) = iter.next() else {
1090                        internal_err!(
1091                            "Expected a pair of expressions to construct the join on expression"
1092                        )?
1093                    };
1094
1095                    // SimplifyExpression rule may add alias to the equi_expr.
1096                    new_on.push((left.unalias(), right.unalias()));
1097                }
1098
1099                Ok(LogicalPlan::Join(Join {
1100                    left: Arc::new(left),
1101                    right: Arc::new(right),
1102                    join_type: *join_type,
1103                    join_constraint: *join_constraint,
1104                    on: new_on,
1105                    filter: filter_expr,
1106                    schema: DFSchemaRef::new(schema),
1107                    null_equality: *null_equality,
1108                    null_aware: *null_aware,
1109                    null_aware_value_keys: *null_aware_value_keys,
1110                }))
1111            }
1112            LogicalPlan::AsOfJoin(AsOfJoin {
1113                on,
1114                match_condition,
1115                join_constraint,
1116                ..
1117            }) => {
1118                let (left, right) = self.only_two_inputs(inputs)?;
1119                let expected = on.len() * 2 + 2;
1120                assert_eq_or_internal_err!(
1121                    expected,
1122                    expr.len(),
1123                    "Invalid number of new ASOF join expressions: expected {}, got {}",
1124                    expected,
1125                    expr.len()
1126                );
1127
1128                let mut iter = expr.into_iter();
1129                let mut new_on = Vec::with_capacity(on.len());
1130                for _ in 0..on.len() {
1131                    let left = iter.next().expect("expression count checked").unalias();
1132                    let right = iter.next().expect("expression count checked").unalias();
1133                    new_on.push((left, right));
1134                }
1135                let match_left = iter.next().expect("expression count checked").unalias();
1136                let match_right =
1137                    iter.next().expect("expression count checked").unalias();
1138
1139                Ok(LogicalPlan::AsOfJoin(AsOfJoin::try_new(
1140                    Arc::new(left),
1141                    Arc::new(right),
1142                    new_on,
1143                    AsOfMatch {
1144                        left: match_left,
1145                        op: match_condition.op,
1146                        right: match_right,
1147                    },
1148                    *join_constraint,
1149                )?))
1150            }
1151            LogicalPlan::Subquery(Subquery {
1152                outer_ref_columns,
1153                spans,
1154                ..
1155            }) => {
1156                self.assert_no_expressions(expr)?;
1157                let input = self.only_input(inputs)?;
1158                let subquery = LogicalPlanBuilder::from(input).build()?;
1159                Ok(LogicalPlan::Subquery(Subquery {
1160                    subquery: Arc::new(subquery),
1161                    outer_ref_columns: outer_ref_columns.clone(),
1162                    spans: spans.clone(),
1163                }))
1164            }
1165            LogicalPlan::SubqueryAlias(SubqueryAlias { alias, .. }) => {
1166                self.assert_no_expressions(expr)?;
1167                let input = self.only_input(inputs)?;
1168                SubqueryAlias::try_new(Arc::new(input), alias.clone())
1169                    .map(LogicalPlan::SubqueryAlias)
1170            }
1171            LogicalPlan::Limit(Limit { skip, fetch, .. }) => {
1172                let old_expr_len = skip.iter().chain(fetch.iter()).count();
1173                assert_eq_or_internal_err!(
1174                    old_expr_len,
1175                    expr.len(),
1176                    "Invalid number of new Limit expressions: expected {}, got {}",
1177                    old_expr_len,
1178                    expr.len()
1179                );
1180                // `LogicalPlan::expressions()` returns in [skip, fetch] order, so we can pop from the end.
1181                let new_fetch = fetch.as_ref().and_then(|_| expr.pop());
1182                let new_skip = skip.as_ref().and_then(|_| expr.pop());
1183                let input = self.only_input(inputs)?;
1184                Ok(LogicalPlan::Limit(Limit {
1185                    skip: new_skip.map(Box::new),
1186                    fetch: new_fetch.map(Box::new),
1187                    input: Arc::new(input),
1188                }))
1189            }
1190            LogicalPlan::Ddl(DdlStatement::CreateMemoryTable(CreateMemoryTable {
1191                name,
1192                if_not_exists,
1193                or_replace,
1194                column_defaults,
1195                temporary,
1196                ..
1197            })) => {
1198                self.assert_no_expressions(expr)?;
1199                let input = self.only_input(inputs)?;
1200                Ok(LogicalPlan::Ddl(DdlStatement::CreateMemoryTable(
1201                    CreateMemoryTable {
1202                        input: Arc::new(input),
1203                        constraints: Constraints::default(),
1204                        name: name.clone(),
1205                        if_not_exists: *if_not_exists,
1206                        or_replace: *or_replace,
1207                        column_defaults: column_defaults.clone(),
1208                        temporary: *temporary,
1209                    },
1210                )))
1211            }
1212            LogicalPlan::Ddl(DdlStatement::CreateView(CreateView {
1213                name,
1214                or_replace,
1215                definition,
1216                temporary,
1217                ..
1218            })) => {
1219                self.assert_no_expressions(expr)?;
1220                let input = self.only_input(inputs)?;
1221                Ok(LogicalPlan::Ddl(DdlStatement::CreateView(CreateView {
1222                    input: Arc::new(input),
1223                    name: name.clone(),
1224                    or_replace: *or_replace,
1225                    temporary: *temporary,
1226                    definition: definition.clone(),
1227                })))
1228            }
1229            LogicalPlan::Extension(e) => Ok(LogicalPlan::Extension(Extension {
1230                node: e.node.with_exprs_and_inputs(expr, inputs)?,
1231            })),
1232            LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
1233                self.assert_no_expressions(expr)?;
1234                let (body, continuation) = self.only_two_inputs(inputs)?;
1235                Ok(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
1236                    cte.with_new_inputs(Arc::new(body), Arc::new(continuation)),
1237                )))
1238            }
1239            LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => {
1240                self.assert_no_expressions(expr)?;
1241                self.assert_no_inputs(inputs)?;
1242                Ok(self.clone())
1243            }
1244            LogicalPlan::Union(Union { schema, .. }) => {
1245                self.assert_no_expressions(expr)?;
1246                let input_schema = inputs[0].schema();
1247                // If inputs are not pruned do not change schema.
1248                let schema = if schema.fields().len() == input_schema.fields().len() {
1249                    Arc::clone(schema)
1250                } else {
1251                    Arc::clone(input_schema)
1252                };
1253                Ok(LogicalPlan::Union(Union {
1254                    inputs: inputs.into_iter().map(Arc::new).collect(),
1255                    schema,
1256                }))
1257            }
1258            LogicalPlan::Distinct(distinct) => {
1259                let distinct = match distinct {
1260                    Distinct::All(_) => {
1261                        self.assert_no_expressions(expr)?;
1262                        let input = self.only_input(inputs)?;
1263                        Distinct::All(Arc::new(input))
1264                    }
1265                    Distinct::On(DistinctOn {
1266                        on_expr,
1267                        select_expr,
1268                        ..
1269                    }) => {
1270                        let input = self.only_input(inputs)?;
1271                        let sort_expr = expr.split_off(on_expr.len() + select_expr.len());
1272                        let select_expr = expr.split_off(on_expr.len());
1273                        assert!(
1274                            sort_expr.is_empty(),
1275                            "with_new_exprs for Distinct does not support sort expressions"
1276                        );
1277                        Distinct::On(DistinctOn::try_new(
1278                            expr,
1279                            select_expr,
1280                            None, // no sort expressions accepted
1281                            Arc::new(input),
1282                        )?)
1283                    }
1284                };
1285                Ok(LogicalPlan::Distinct(distinct))
1286            }
1287            LogicalPlan::RecursiveQuery(RecursiveQuery {
1288                name, is_distinct, ..
1289            }) => {
1290                self.assert_no_expressions(expr)?;
1291                let (static_term, recursive_term) = self.only_two_inputs(inputs)?;
1292                RecursiveQuery::try_new(
1293                    name.clone(),
1294                    Arc::new(static_term),
1295                    Arc::new(recursive_term),
1296                    *is_distinct,
1297                )
1298                .map(LogicalPlan::RecursiveQuery)
1299            }
1300            LogicalPlan::Analyze(a) => {
1301                self.assert_no_expressions(expr)?;
1302                let input = self.only_input(inputs)?;
1303                Ok(LogicalPlan::Analyze(Analyze {
1304                    verbose: a.verbose,
1305                    format: a.format.clone(),
1306                    schema: Arc::clone(&a.schema),
1307                    input: Arc::new(input),
1308                    analyze_level: a.analyze_level,
1309                    analyze_categories: a.analyze_categories.clone(),
1310                }))
1311            }
1312            LogicalPlan::Explain(e) => {
1313                self.assert_no_expressions(expr)?;
1314                let input = self.only_input(inputs)?;
1315                Ok(LogicalPlan::Explain(Explain {
1316                    verbose: e.verbose,
1317                    plan: Arc::new(input),
1318                    explain_format: e.explain_format.clone(),
1319                    stringified_plans: e.stringified_plans.clone(),
1320                    schema: Arc::clone(&e.schema),
1321                    logical_optimization_succeeded: e.logical_optimization_succeeded,
1322                    show_statistics: e.show_statistics,
1323                }))
1324            }
1325            LogicalPlan::Statement(Statement::Prepare(Prepare {
1326                name, fields, ..
1327            })) => {
1328                self.assert_no_expressions(expr)?;
1329                let input = self.only_input(inputs)?;
1330                Ok(LogicalPlan::Statement(Statement::Prepare(Prepare {
1331                    name: name.clone(),
1332                    fields: fields.clone(),
1333                    input: Arc::new(input),
1334                })))
1335            }
1336            LogicalPlan::Statement(Statement::Execute(Execute { name, .. })) => {
1337                self.assert_no_inputs(inputs)?;
1338                Ok(LogicalPlan::Statement(Statement::Execute(Execute {
1339                    name: name.clone(),
1340                    parameters: expr,
1341                })))
1342            }
1343            LogicalPlan::TableScan(ts) => {
1344                self.assert_no_inputs(inputs)?;
1345                Ok(LogicalPlan::TableScan(TableScan {
1346                    filters: expr,
1347                    ..ts.clone()
1348                }))
1349            }
1350            LogicalPlan::EmptyRelation(_)
1351            | LogicalPlan::Ddl(_)
1352            | LogicalPlan::Statement(_)
1353            | LogicalPlan::Show(_) => {
1354                // All of these plan types have no inputs / exprs so should not be called
1355                self.assert_no_expressions(expr)?;
1356                self.assert_no_inputs(inputs)?;
1357                Ok(self.clone())
1358            }
1359            LogicalPlan::Unnest(Unnest {
1360                exec_columns: columns,
1361                options,
1362                ..
1363            }) => {
1364                let exec_columns = if expr.is_empty() {
1365                    columns.clone()
1366                } else {
1367                    expr.into_iter()
1368                        .map(|e| match e {
1369                            Expr::Column(c) => Ok(c),
1370                            other => internal_err!(
1371                                "Expected Expr::Column for Unnest exec_columns, got {other:?}"
1372                            ),
1373                        })
1374                        .collect::<Result<Vec<_>>>()?
1375                };
1376                let input = self.only_input(inputs)?;
1377                Ok(unnest_with_options(input, exec_columns, options.clone())?)
1378            }
1379        }
1380    }
1381
1382    /// checks that the plan conforms to the listed invariant level, returning an Error if not
1383    pub fn check_invariants(&self, check: InvariantLevel) -> Result<()> {
1384        match check {
1385            InvariantLevel::Always => assert_always_invariants_at_current_node(self),
1386            InvariantLevel::Executable => assert_executable_invariants(self),
1387        }
1388    }
1389
1390    /// Helper for [Self::with_new_exprs] to use when no expressions are expected.
1391    #[inline]
1392    #[expect(clippy::needless_pass_by_value)] // expr is moved intentionally to ensure it's not used again
1393    fn assert_no_expressions(&self, expr: Vec<Expr>) -> Result<()> {
1394        assert_or_internal_err!(
1395            expr.is_empty(),
1396            "{self:?} should have no exprs, got {:?}",
1397            expr
1398        );
1399        Ok(())
1400    }
1401
1402    /// Helper for [Self::with_new_exprs] to use when no inputs are expected.
1403    #[inline]
1404    #[expect(clippy::needless_pass_by_value)] // inputs is moved intentionally to ensure it's not used again
1405    fn assert_no_inputs(&self, inputs: Vec<LogicalPlan>) -> Result<()> {
1406        assert_or_internal_err!(
1407            inputs.is_empty(),
1408            "{self:?} should have no inputs, got: {:?}",
1409            inputs
1410        );
1411        Ok(())
1412    }
1413
1414    /// Helper for [Self::with_new_exprs] to use when exactly one expression is expected.
1415    #[inline]
1416    fn only_expr(&self, mut expr: Vec<Expr>) -> Result<Expr> {
1417        assert_eq_or_internal_err!(
1418            expr.len(),
1419            1,
1420            "{self:?} should have exactly one expr, got {:?}",
1421            &expr
1422        );
1423        Ok(expr.remove(0))
1424    }
1425
1426    /// Helper for [Self::with_new_exprs] to use when exactly one input is expected.
1427    #[inline]
1428    fn only_input(&self, mut inputs: Vec<LogicalPlan>) -> Result<LogicalPlan> {
1429        assert_eq_or_internal_err!(
1430            inputs.len(),
1431            1,
1432            "{self:?} should have exactly one input, got {:?}",
1433            &inputs
1434        );
1435        Ok(inputs.remove(0))
1436    }
1437
1438    /// Helper for [Self::with_new_exprs] to use when exactly two inputs are expected.
1439    #[inline]
1440    fn only_two_inputs(
1441        &self,
1442        mut inputs: Vec<LogicalPlan>,
1443    ) -> Result<(LogicalPlan, LogicalPlan)> {
1444        assert_eq_or_internal_err!(
1445            inputs.len(),
1446            2,
1447            "{self:?} should have exactly two inputs, got {:?}",
1448            &inputs
1449        );
1450        let right = inputs.remove(1);
1451        let left = inputs.remove(0);
1452        Ok((left, right))
1453    }
1454
1455    /// Replaces placeholder param values (like `$1`, `$2`) in [`LogicalPlan`]
1456    /// with the specified `param_values`.
1457    ///
1458    /// [`Prepare`] statements are converted to
1459    /// their inner logical plan for execution.
1460    ///
1461    /// # Example
1462    /// ```
1463    /// # use arrow::datatypes::{Field, Schema, DataType};
1464    /// use datafusion_common::ScalarValue;
1465    /// # use datafusion_expr::{lit, col, LogicalPlanBuilder, logical_plan::table_scan, placeholder};
1466    /// # let schema = Schema::new(vec![
1467    /// #     Field::new("id", DataType::Int32, false),
1468    /// # ]);
1469    /// // Build SELECT * FROM t1 WHERE id = $1
1470    /// let plan = table_scan(Some("t1"), &schema, None).unwrap()
1471    ///     .filter(col("id").eq(placeholder("$1"))).unwrap()
1472    ///     .build().unwrap();
1473    ///
1474    /// assert_eq!(
1475    ///   "Filter: t1.id = $1\
1476    ///   \n  TableScan: t1",
1477    ///   plan.display_indent().to_string()
1478    /// );
1479    ///
1480    /// // Fill in the parameter $1 with a literal 3
1481    /// let plan = plan.with_param_values(vec![
1482    ///   ScalarValue::from(3i32) // value at index 0 --> $1
1483    /// ]).unwrap();
1484    ///
1485    /// assert_eq!(
1486    ///    "Filter: t1.id = Int32(3)\
1487    ///    \n  TableScan: t1",
1488    ///    plan.display_indent().to_string()
1489    ///  );
1490    ///
1491    /// // Note you can also used named parameters
1492    /// // Build SELECT * FROM t1 WHERE id = $my_param
1493    /// let plan = table_scan(Some("t1"), &schema, None).unwrap()
1494    ///     .filter(col("id").eq(placeholder("$my_param"))).unwrap()
1495    ///     .build().unwrap()
1496    ///     // Fill in the parameter $my_param with a literal 3
1497    ///     .with_param_values(vec![
1498    ///       ("my_param", ScalarValue::from(3i32)),
1499    ///     ]).unwrap();
1500    ///
1501    /// assert_eq!(
1502    ///    "Filter: t1.id = Int32(3)\
1503    ///    \n  TableScan: t1",
1504    ///    plan.display_indent().to_string()
1505    ///  );
1506    /// ```
1507    pub fn with_param_values(
1508        self,
1509        param_values: impl Into<ParamValues>,
1510    ) -> Result<LogicalPlan> {
1511        let param_values = param_values.into();
1512        let plan_with_values = self.replace_params_with_values(&param_values)?;
1513
1514        // unwrap Prepare
1515        Ok(
1516            if let LogicalPlan::Statement(Statement::Prepare(prepare_lp)) =
1517                plan_with_values
1518            {
1519                param_values.verify_fields(&prepare_lp.fields)?;
1520                // try and take ownership of the input if is not shared, clone otherwise
1521                Arc::unwrap_or_clone(prepare_lp.input)
1522            } else {
1523                plan_with_values
1524            },
1525        )
1526    }
1527
1528    /// Returns the maximum number of rows that this plan can output, if known.
1529    ///
1530    /// If `None`, the plan can return any number of rows.
1531    /// If `Some(n)` then the plan can return at most `n` rows but may return fewer.
1532    pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
1533        match self {
1534            LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
1535            LogicalPlan::Filter(filter) => {
1536                if filter.is_scalar() {
1537                    Some(1)
1538                } else {
1539                    filter.input.max_rows()
1540                }
1541            }
1542            LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
1543            LogicalPlan::Aggregate(Aggregate {
1544                input, group_expr, ..
1545            }) => {
1546                // Empty group_expr will return Some(1)
1547                if group_expr
1548                    .iter()
1549                    .all(|expr| matches!(expr, Expr::Literal(_, _)))
1550                {
1551                    Some(1)
1552                } else {
1553                    input.max_rows()
1554                }
1555            }
1556            LogicalPlan::Sort(Sort { input, fetch, .. }) => {
1557                match (fetch, input.max_rows()) {
1558                    (Some(fetch_limit), Some(input_max)) => {
1559                        Some(input_max.min(*fetch_limit))
1560                    }
1561                    (Some(fetch_limit), None) => Some(*fetch_limit),
1562                    (None, Some(input_max)) => Some(input_max),
1563                    (None, None) => None,
1564                }
1565            }
1566            LogicalPlan::Join(Join {
1567                left,
1568                right,
1569                join_type,
1570                ..
1571            }) => match join_type {
1572                JoinType::Inner => Some(left.max_rows()? * right.max_rows()?),
1573                JoinType::Left | JoinType::Right | JoinType::Full => {
1574                    match (left.max_rows()?, right.max_rows()?, join_type) {
1575                        (0, 0, _) => Some(0),
1576                        (max_rows, 0, JoinType::Left | JoinType::Full) => Some(max_rows),
1577                        (0, max_rows, JoinType::Right | JoinType::Full) => Some(max_rows),
1578                        (left_max, right_max, _) => Some(left_max * right_max),
1579                    }
1580                }
1581                JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => {
1582                    left.max_rows()
1583                }
1584                JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark => {
1585                    right.max_rows()
1586                }
1587            },
1588            LogicalPlan::AsOfJoin(AsOfJoin { left, .. }) => left.max_rows(),
1589            LogicalPlan::Repartition(Repartition { input, .. }) => input.max_rows(),
1590            LogicalPlan::Union(Union { inputs, .. }) => {
1591                inputs.iter().try_fold(0usize, |mut acc, plan| {
1592                    acc += plan.max_rows()?;
1593                    Some(acc)
1594                })
1595            }
1596            LogicalPlan::TableScan(TableScan { fetch, .. }) => *fetch,
1597            LogicalPlan::EmptyRelation(EmptyRelation {
1598                produce_one_row, ..
1599            }) => Some(usize::from(*produce_one_row)),
1600            LogicalPlan::RecursiveQuery(_) => None,
1601            LogicalPlan::Subquery(_) => None,
1602            LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => input.max_rows(),
1603            LogicalPlan::Limit(limit) => match limit.get_fetch_type() {
1604                Ok(FetchType::Literal(s)) => s,
1605                _ => None,
1606            },
1607            LogicalPlan::Distinct(
1608                Distinct::All(input) | Distinct::On(DistinctOn { input, .. }),
1609            ) => input.max_rows(),
1610            LogicalPlan::Values(v) => Some(v.values.len()),
1611            LogicalPlan::Unnest(_) => None,
1612            LogicalPlan::Ddl(_)
1613            | LogicalPlan::Explain(_)
1614            | LogicalPlan::Analyze(_)
1615            | LogicalPlan::Dml(_)
1616            | LogicalPlan::Copy(_)
1617            | LogicalPlan::Show(_)
1618            | LogicalPlan::Statement(_)
1619            | LogicalPlan::Extension(_)
1620            | LogicalPlan::MaterializedCte(_) => None,
1621        }
1622    }
1623
1624    /// Returns a lower bound on the number of rows that this plan can output.
1625    ///
1626    /// A return value of `0` means that the plan may produce no rows. A positive
1627    /// value guarantees that the plan produces at least that many rows.
1628    ///
1629    /// See [`Self::max_rows`] for the corresponding upper bound.
1630    pub fn min_rows(&self) -> usize {
1631        match self {
1632            LogicalPlan::Projection(Projection { input, .. })
1633            | LogicalPlan::Window(Window { input, .. })
1634            | LogicalPlan::Repartition(Repartition { input, .. })
1635            | LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => input.min_rows(),
1636            LogicalPlan::Filter(_) => 0,
1637            LogicalPlan::Aggregate(Aggregate { group_expr, .. }) => {
1638                // An ungrouped aggregate always produces one row, even for an
1639                // empty input.
1640                usize::from(group_expr.is_empty())
1641            }
1642            LogicalPlan::Sort(Sort { input, fetch, .. }) => fetch
1643                .map(|fetch| input.min_rows().min(fetch))
1644                .unwrap_or_else(|| input.min_rows()),
1645            LogicalPlan::Join(Join {
1646                left,
1647                right,
1648                on,
1649                filter,
1650                join_type,
1651                ..
1652            }) => match join_type {
1653                JoinType::Inner if on.is_empty() && filter.is_none() => {
1654                    left.min_rows().saturating_mul(right.min_rows())
1655                }
1656                JoinType::Left | JoinType::LeftMark => left.min_rows(),
1657                JoinType::Right | JoinType::RightMark => right.min_rows(),
1658                JoinType::Full => left.min_rows().max(right.min_rows()),
1659                JoinType::Inner
1660                | JoinType::LeftSemi
1661                | JoinType::RightSemi
1662                | JoinType::LeftAnti
1663                | JoinType::RightAnti => 0,
1664            },
1665            LogicalPlan::AsOfJoin(AsOfJoin { left, .. }) => left.min_rows(),
1666            LogicalPlan::Union(Union { inputs, .. }) => inputs
1667                .iter()
1668                .fold(0, |rows, input| rows.saturating_add(input.min_rows())),
1669            LogicalPlan::EmptyRelation(EmptyRelation {
1670                produce_one_row, ..
1671            }) => usize::from(*produce_one_row),
1672            LogicalPlan::Subquery(Subquery { subquery, .. }) => subquery.min_rows(),
1673            LogicalPlan::Limit(limit) => {
1674                match (limit.get_skip_type(), limit.get_fetch_type()) {
1675                    (Ok(SkipType::Literal(skip)), Ok(FetchType::Literal(fetch))) => fetch
1676                        .map(|fetch| {
1677                            limit.input.min_rows().saturating_sub(skip).min(fetch)
1678                        })
1679                        .unwrap_or_else(|| limit.input.min_rows().saturating_sub(skip)),
1680                    _ => 0,
1681                }
1682            }
1683            LogicalPlan::Distinct(
1684                Distinct::All(input) | Distinct::On(DistinctOn { input, .. }),
1685            ) => usize::from(input.min_rows() > 0),
1686            LogicalPlan::Values(values) => values.values.len(),
1687            LogicalPlan::TableScan(_)
1688            | LogicalPlan::RecursiveQuery(_)
1689            | LogicalPlan::Unnest(_)
1690            | LogicalPlan::Ddl(_)
1691            | LogicalPlan::Explain(_)
1692            | LogicalPlan::Analyze(_)
1693            | LogicalPlan::Dml(_)
1694            | LogicalPlan::Copy(_)
1695            | LogicalPlan::Show(_)
1696            | LogicalPlan::Statement(_)
1697            | LogicalPlan::Extension(_)
1698            | LogicalPlan::MaterializedCte(_) => 0,
1699        }
1700    }
1701
1702    /// Returns the skip (offset) of this plan node, if it has one.
1703    ///
1704    /// Only [`LogicalPlan::Limit`] carries a skip value; all other variants
1705    /// return `Ok(None)`. Returns `Ok(None)` for a zero skip.
1706    pub fn skip(&self) -> Result<Option<usize>> {
1707        match self {
1708            LogicalPlan::Limit(limit) => match limit.get_skip_type()? {
1709                SkipType::Literal(0) => Ok(None),
1710                SkipType::Literal(n) => Ok(Some(n)),
1711                SkipType::UnsupportedExpr => Ok(None),
1712            },
1713            LogicalPlan::Sort(_) => Ok(None),
1714            LogicalPlan::TableScan(_) => Ok(None),
1715            LogicalPlan::Projection(_) => Ok(None),
1716            LogicalPlan::Filter(_) => Ok(None),
1717            LogicalPlan::Window(_) => Ok(None),
1718            LogicalPlan::Aggregate(_) => Ok(None),
1719            LogicalPlan::Join(_) => Ok(None),
1720            LogicalPlan::AsOfJoin(_) => Ok(None),
1721            LogicalPlan::Repartition(_) => Ok(None),
1722            LogicalPlan::Union(_) => Ok(None),
1723            LogicalPlan::EmptyRelation(_) => Ok(None),
1724            LogicalPlan::Subquery(_) => Ok(None),
1725            LogicalPlan::SubqueryAlias(_) => Ok(None),
1726            LogicalPlan::Statement(_) => Ok(None),
1727            LogicalPlan::Values(_) => Ok(None),
1728            LogicalPlan::Explain(_) => Ok(None),
1729            LogicalPlan::Analyze(_) => Ok(None),
1730            LogicalPlan::Extension(_) => Ok(None),
1731            LogicalPlan::MaterializedCte(_) => Ok(None),
1732            LogicalPlan::Distinct(_) => Ok(None),
1733            LogicalPlan::Dml(_) => Ok(None),
1734            LogicalPlan::Ddl(_) => Ok(None),
1735            LogicalPlan::Copy(_) => Ok(None),
1736            LogicalPlan::Show(_) => Ok(None),
1737            LogicalPlan::Unnest(_) => Ok(None),
1738            LogicalPlan::RecursiveQuery(_) => Ok(None),
1739        }
1740    }
1741
1742    /// Returns the fetch (limit) of this plan node, if it has one.
1743    ///
1744    /// [`LogicalPlan::Sort`], [`LogicalPlan::TableScan`], and
1745    /// [`LogicalPlan::Limit`] may carry a fetch value; all other variants
1746    /// return `Ok(None)`.
1747    pub fn fetch(&self) -> Result<Option<usize>> {
1748        match self {
1749            LogicalPlan::Sort(Sort { fetch, .. }) => Ok(*fetch),
1750            LogicalPlan::TableScan(TableScan { fetch, .. }) => Ok(*fetch),
1751            LogicalPlan::Limit(limit) => match limit.get_fetch_type()? {
1752                FetchType::Literal(s) => Ok(s),
1753                FetchType::UnsupportedExpr => Ok(None),
1754            },
1755            LogicalPlan::Projection(_) => Ok(None),
1756            LogicalPlan::Filter(_) => Ok(None),
1757            LogicalPlan::Window(_) => Ok(None),
1758            LogicalPlan::Aggregate(_) => Ok(None),
1759            LogicalPlan::Join(_) => Ok(None),
1760            LogicalPlan::AsOfJoin(_) => Ok(None),
1761            LogicalPlan::Repartition(_) => Ok(None),
1762            LogicalPlan::Union(_) => Ok(None),
1763            LogicalPlan::EmptyRelation(_) => Ok(None),
1764            LogicalPlan::Subquery(_) => Ok(None),
1765            LogicalPlan::SubqueryAlias(_) => Ok(None),
1766            LogicalPlan::Statement(_) => Ok(None),
1767            LogicalPlan::Values(_) => Ok(None),
1768            LogicalPlan::Explain(_) => Ok(None),
1769            LogicalPlan::Analyze(_) => Ok(None),
1770            LogicalPlan::Extension(_) => Ok(None),
1771            LogicalPlan::MaterializedCte(_) => Ok(None),
1772            LogicalPlan::Distinct(_) => Ok(None),
1773            LogicalPlan::Dml(_) => Ok(None),
1774            LogicalPlan::Ddl(_) => Ok(None),
1775            LogicalPlan::Copy(_) => Ok(None),
1776            LogicalPlan::Show(_) => Ok(None),
1777            LogicalPlan::Unnest(_) => Ok(None),
1778            LogicalPlan::RecursiveQuery(_) => Ok(None),
1779        }
1780    }
1781
1782    /// If this node's expressions contains any references to an outer subquery
1783    pub fn contains_outer_reference(&self) -> bool {
1784        let mut contains = false;
1785        self.apply_expressions(|expr| {
1786            Ok(if expr.contains_outer() {
1787                contains = true;
1788                TreeNodeRecursion::Stop
1789            } else {
1790                TreeNodeRecursion::Continue
1791            })
1792        })
1793        .unwrap();
1794        contains
1795    }
1796
1797    /// Get the output expressions and their corresponding columns.
1798    ///
1799    /// The parent node may reference the output columns of the plan by expressions, such as
1800    /// projection over aggregate or window functions. This method helps to convert the
1801    /// referenced expressions into columns.
1802    ///
1803    /// See also: [`crate::utils::columnize_expr`]
1804    pub fn columnized_output_exprs(&self) -> Result<Vec<(&Expr, Column)>> {
1805        match self {
1806            LogicalPlan::Aggregate(aggregate) => Ok(aggregate
1807                .output_expressions()?
1808                .into_iter()
1809                .zip(self.schema().columns())
1810                .collect()),
1811            LogicalPlan::Window(Window {
1812                window_expr,
1813                input,
1814                schema,
1815            }) => {
1816                // The input could be another Window, so the result should also include the input's. For Example:
1817                // `EXPLAIN SELECT RANK() OVER (PARTITION BY a ORDER BY b), SUM(b) OVER (PARTITION BY a) FROM t`
1818                // Its plan is:
1819                // Projection: RANK() PARTITION BY [t.a] ORDER BY [t.b ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, SUM(t.b) PARTITION BY [t.a] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
1820                //   WindowAggr: windowExpr=[[SUM(CAST(t.b AS Int64)) PARTITION BY [t.a] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING]]
1821                //     WindowAggr: windowExpr=[[RANK() PARTITION BY [t.a] ORDER BY [t.b ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]/
1822                //       TableScan: t projection=[a, b]
1823                let mut output_exprs = input.columnized_output_exprs()?;
1824                let input_len = input.schema().fields().len();
1825                output_exprs.extend(
1826                    window_expr
1827                        .iter()
1828                        .zip(schema.columns().into_iter().skip(input_len)),
1829                );
1830                Ok(output_exprs)
1831            }
1832            _ => Ok(vec![]),
1833        }
1834    }
1835}
1836
1837impl LogicalPlan {
1838    /// Return a `LogicalPlan` with all placeholders (e.g $1 $2,
1839    /// ...) replaced with corresponding values provided in
1840    /// `params_values`
1841    ///
1842    /// See [`Self::with_param_values`] for examples and usage with an owned
1843    /// `ParamValues`
1844    pub fn replace_params_with_values(
1845        self,
1846        param_values: &ParamValues,
1847    ) -> Result<LogicalPlan> {
1848        self.transform_up_with_subqueries(|plan| {
1849            let schema = Arc::clone(plan.schema());
1850            let name_preserver = NamePreserver::new(&plan);
1851            plan.map_expressions(|e| {
1852                let (e, has_placeholder) = e.infer_placeholder_types(&schema)?;
1853                if !has_placeholder {
1854                    // Performance optimization:
1855                    // avoid NamePreserver copy and second pass over expression
1856                    // if no placeholders.
1857                    Ok(Transformed::no(e))
1858                } else {
1859                    let original_name = name_preserver.save(&e);
1860                    let transformed_expr = e.transform_up(|e| {
1861                        if let Expr::Placeholder(Placeholder { id, .. }) = e {
1862                            let (value, metadata) = param_values
1863                                .get_placeholders_with_values(&id)?
1864                                .into_inner();
1865                            Ok(Transformed::yes(Expr::Literal(value, metadata)))
1866                        } else {
1867                            Ok(Transformed::no(e))
1868                        }
1869                    })?;
1870                    // Preserve name to avoid breaking column references to this expression
1871                    Ok(transformed_expr.update_data(|expr| original_name.restore(expr)))
1872                }
1873            })?
1874            .map_data(|plan| plan.update_schema_data_type())
1875        })
1876        .map(|res| res.data)
1877    }
1878
1879    /// Recompute schema fields' data type after replacing params, ensuring fields data type can be
1880    /// updated according to the new parameters.
1881    ///
1882    /// Unlike `recompute_schema()`, this method rebuilds VALUES plans entirely to properly infer
1883    /// types from literal values after placeholder substitution.
1884    fn update_schema_data_type(self) -> Result<LogicalPlan> {
1885        match self {
1886            // Build `LogicalPlan::Values` from the values for type inference.
1887            // We can't use `recompute_schema` because it skips recomputing for
1888            // `LogicalPlan::Values`.
1889            LogicalPlan::Values(Values { values, schema: _ }) => {
1890                LogicalPlanBuilder::values(values)?.build()
1891            }
1892            // other plans can just use `recompute_schema` directly.
1893            plan => plan.recompute_schema(),
1894        }
1895    }
1896
1897    /// Walk the logical plan, find any `Placeholder` tokens, and return a set of their names.
1898    pub fn get_parameter_names(&self) -> Result<HashSet<String>> {
1899        let mut param_names = HashSet::new();
1900        self.apply_with_subqueries(|plan| {
1901            plan.apply_expressions(|expr| {
1902                expr.apply(|expr| {
1903                    if let Expr::Placeholder(Placeholder { id, .. }) = expr {
1904                        param_names.insert(id.clone());
1905                    }
1906                    Ok(TreeNodeRecursion::Continue)
1907                })
1908            })
1909        })
1910        .map(|_| param_names)
1911    }
1912
1913    /// Walk the logical plan, find any `Placeholder` tokens, and return a map of their IDs and DataTypes
1914    ///
1915    /// Note that this will drop any extension or field metadata attached to parameters. Use
1916    /// [`LogicalPlan::get_parameter_fields`] to keep extension metadata.
1917    pub fn get_parameter_types(
1918        &self,
1919    ) -> Result<HashMap<String, Option<DataType>>, DataFusionError> {
1920        let mut parameter_fields = self.get_parameter_fields()?;
1921        Ok(parameter_fields
1922            .drain()
1923            .map(|(name, maybe_field)| {
1924                (name, maybe_field.map(|field| field.data_type().clone()))
1925            })
1926            .collect())
1927    }
1928
1929    /// Walk the logical plan, find any `Placeholder` tokens, and return a map of their IDs and FieldRefs.
1930    /// Bare `LIMIT`/`OFFSET` parameters default to `Int64` if no occurrence provides a type.
1931    pub fn get_parameter_fields(
1932        &self,
1933    ) -> Result<HashMap<String, Option<FieldRef>>, DataFusionError> {
1934        let mut param_types: HashMap<String, Option<FieldRef>> = HashMap::new();
1935        let mut row_count_parameters: HashSet<String> = HashSet::new();
1936
1937        self.apply_with_subqueries(|plan| {
1938            plan.apply_expressions(|expr| {
1939                if matches!(plan, LogicalPlan::Limit(_))
1940                    && let Expr::Placeholder(Placeholder { id, field: None }) = expr
1941                {
1942                    row_count_parameters.insert(id.clone());
1943                }
1944                expr.apply(|expr| {
1945                    if let Expr::Placeholder(Placeholder { id, field }) = expr {
1946                        let prev = param_types.get(id);
1947                        match (prev, field) {
1948                            (Some(Some(prev)), Some(field)) => {
1949                                check_metadata_with_storage_equal(
1950                                    (field.data_type(), Some(field.metadata())),
1951                                    (prev.data_type(), Some(prev.metadata())),
1952                                    "parameter",
1953                                    &format!(": Conflicting types for id {id}"),
1954                                )?;
1955                            }
1956                            (_, Some(field)) => {
1957                                param_types.insert(id.clone(), Some(Arc::clone(field)));
1958                            }
1959                            _ => {
1960                                param_types.entry(id.clone()).or_insert(None);
1961                            }
1962                        }
1963                    }
1964                    Ok(TreeNodeRecursion::Continue)
1965                })
1966            })
1967        })?;
1968
1969        for id in row_count_parameters {
1970            param_types
1971                .entry(id)
1972                .or_default()
1973                .get_or_insert_with(|| Arc::new(Field::new("", DataType::Int64, true)));
1974        }
1975        Ok(param_types)
1976    }
1977
1978    // ------------
1979    // Various implementations for printing out LogicalPlans
1980    // ------------
1981
1982    /// Return a `format`able structure that produces a single line
1983    /// per node.
1984    ///
1985    /// # Example
1986    ///
1987    /// ```text
1988    /// Projection: employee.id
1989    ///    Filter: employee.state Eq Utf8(\"CO\")\
1990    ///       CsvScan: employee projection=Some([0, 3])
1991    /// ```
1992    ///
1993    /// ```
1994    /// use arrow::datatypes::{DataType, Field, Schema};
1995    /// use datafusion_expr::{col, lit, logical_plan::table_scan, LogicalPlanBuilder};
1996    /// let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
1997    /// let plan = table_scan(Some("t1"), &schema, None)
1998    ///     .unwrap()
1999    ///     .filter(col("id").eq(lit(5)))
2000    ///     .unwrap()
2001    ///     .build()
2002    ///     .unwrap();
2003    ///
2004    /// // Format using display_indent
2005    /// let display_string = format!("{}", plan.display_indent());
2006    ///
2007    /// assert_eq!("Filter: t1.id = Int32(5)\n  TableScan: t1", display_string);
2008    /// ```
2009    pub fn display_indent(&self) -> impl Display + '_ {
2010        // Boilerplate structure to wrap LogicalPlan with something
2011        // that can be formatted
2012        struct Wrapper<'a>(&'a LogicalPlan);
2013        impl Display for Wrapper<'_> {
2014            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2015                let with_schema = false;
2016                let mut visitor = IndentVisitor::new(f, with_schema);
2017                match self.0.visit_with_subqueries(&mut visitor) {
2018                    Ok(_) => Ok(()),
2019                    Err(_) => Err(fmt::Error),
2020                }
2021            }
2022        }
2023        Wrapper(self)
2024    }
2025
2026    /// Return a `format`able structure that produces a single line
2027    /// per node that includes the output schema. For example:
2028    ///
2029    /// ```text
2030    /// Projection: employee.id [id:Int32]\
2031    ///    Filter: employee.state = Utf8(\"CO\") [id:Int32, state:Utf8]\
2032    ///      TableScan: employee projection=[0, 3] [id:Int32, state:Utf8]";
2033    /// ```
2034    ///
2035    /// ```
2036    /// use arrow::datatypes::{DataType, Field, Schema};
2037    /// use datafusion_expr::{col, lit, logical_plan::table_scan, LogicalPlanBuilder};
2038    /// let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
2039    /// let plan = table_scan(Some("t1"), &schema, None)
2040    ///     .unwrap()
2041    ///     .filter(col("id").eq(lit(5)))
2042    ///     .unwrap()
2043    ///     .build()
2044    ///     .unwrap();
2045    ///
2046    /// // Format using display_indent_schema
2047    /// let display_string = format!("{}", plan.display_indent_schema());
2048    ///
2049    /// assert_eq!(
2050    ///     "Filter: t1.id = Int32(5) [id:Int32]\
2051    ///             \n  TableScan: t1 [id:Int32]",
2052    ///     display_string
2053    /// );
2054    /// ```
2055    pub fn display_indent_schema(&self) -> impl Display + '_ {
2056        // Boilerplate structure to wrap LogicalPlan with something
2057        // that can be formatted
2058        struct Wrapper<'a>(&'a LogicalPlan);
2059        impl Display for Wrapper<'_> {
2060            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2061                let with_schema = true;
2062                let mut visitor = IndentVisitor::new(f, with_schema);
2063                match self.0.visit_with_subqueries(&mut visitor) {
2064                    Ok(_) => Ok(()),
2065                    Err(_) => Err(fmt::Error),
2066                }
2067            }
2068        }
2069        Wrapper(self)
2070    }
2071
2072    /// Return a displayable structure that produces plan in postgresql JSON format.
2073    ///
2074    /// Users can use this format to visualize the plan in existing plan visualization tools, for example [dalibo](https://explain.dalibo.com/)
2075    pub fn display_pg_json(&self) -> impl Display + '_ {
2076        // Boilerplate structure to wrap LogicalPlan with something
2077        // that can be formatted
2078        struct Wrapper<'a>(&'a LogicalPlan);
2079        impl Display for Wrapper<'_> {
2080            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2081                let mut visitor = PgJsonVisitor::new(f);
2082                visitor.with_schema(true);
2083                match self.0.visit_with_subqueries(&mut visitor) {
2084                    Ok(_) => Ok(()),
2085                    Err(_) => Err(fmt::Error),
2086                }
2087            }
2088        }
2089        Wrapper(self)
2090    }
2091
2092    /// Return a `format`able structure that produces lines meant for
2093    /// graphical display using the `DOT` language. This format can be
2094    /// visualized using software from
2095    /// [`graphviz`](https://graphviz.org/)
2096    ///
2097    /// This currently produces two graphs -- one with the basic
2098    /// structure, and one with additional details such as schema.
2099    ///
2100    /// ```
2101    /// use arrow::datatypes::{DataType, Field, Schema};
2102    /// use datafusion_expr::{col, lit, logical_plan::table_scan, LogicalPlanBuilder};
2103    /// let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
2104    /// let plan = table_scan(Some("t1"), &schema, None)
2105    ///     .unwrap()
2106    ///     .filter(col("id").eq(lit(5)))
2107    ///     .unwrap()
2108    ///     .build()
2109    ///     .unwrap();
2110    ///
2111    /// // Format using display_graphviz
2112    /// let graphviz_string = format!("{}", plan.display_graphviz());
2113    /// ```
2114    ///
2115    /// If graphviz string is saved to a file such as `/tmp/example.dot`, the following
2116    /// commands can be used to render it as a pdf:
2117    ///
2118    /// ```bash
2119    ///   dot -Tpdf < /tmp/example.dot  > /tmp/example.pdf
2120    /// ```
2121    pub fn display_graphviz(&self) -> impl Display + '_ {
2122        // Boilerplate structure to wrap LogicalPlan with something
2123        // that can be formatted
2124        struct Wrapper<'a>(&'a LogicalPlan);
2125        impl Display for Wrapper<'_> {
2126            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2127                let mut visitor = GraphvizVisitor::new(f);
2128
2129                visitor.start_graph()?;
2130
2131                visitor.pre_visit_plan("LogicalPlan")?;
2132                self.0
2133                    .visit_with_subqueries(&mut visitor)
2134                    .map_err(|_| fmt::Error)?;
2135                visitor.post_visit_plan()?;
2136
2137                visitor.set_with_schema(true);
2138                visitor.pre_visit_plan("Detailed LogicalPlan")?;
2139                self.0
2140                    .visit_with_subqueries(&mut visitor)
2141                    .map_err(|_| fmt::Error)?;
2142                visitor.post_visit_plan()?;
2143
2144                visitor.end_graph()?;
2145                Ok(())
2146            }
2147        }
2148        Wrapper(self)
2149    }
2150
2151    /// Return a `format`able structure with the a human readable
2152    /// description of this LogicalPlan node per node, not including
2153    /// children. For example:
2154    ///
2155    /// ```text
2156    /// Projection: id
2157    /// ```
2158    /// ```
2159    /// use arrow::datatypes::{DataType, Field, Schema};
2160    /// use datafusion_expr::{col, lit, logical_plan::table_scan, LogicalPlanBuilder};
2161    /// let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
2162    /// let plan = table_scan(Some("t1"), &schema, None)
2163    ///     .unwrap()
2164    ///     .build()
2165    ///     .unwrap();
2166    ///
2167    /// // Format using display
2168    /// let display_string = format!("{}", plan.display());
2169    ///
2170    /// assert_eq!("TableScan: t1", display_string);
2171    /// ```
2172    pub fn display(&self) -> impl Display + '_ {
2173        // Boilerplate structure to wrap LogicalPlan with something
2174        // that can be formatted
2175        struct Wrapper<'a>(&'a LogicalPlan);
2176        impl Display for Wrapper<'_> {
2177            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2178                match self.0 {
2179                    LogicalPlan::EmptyRelation(EmptyRelation {
2180                        produce_one_row,
2181                        schema: _,
2182                    }) => {
2183                        let rows = i32::from(*produce_one_row);
2184                        write!(f, "EmptyRelation: rows={rows}")
2185                    }
2186                    LogicalPlan::RecursiveQuery(RecursiveQuery {
2187                        is_distinct, ..
2188                    }) => {
2189                        write!(f, "RecursiveQuery: is_distinct={is_distinct}")
2190                    }
2191                    LogicalPlan::Values(Values { values, .. }) => {
2192                        let str_values: Vec<_> = values
2193                            .iter()
2194                            // limit to only 5 values to avoid horrible display
2195                            .take(5)
2196                            .map(|row| {
2197                                let item = row
2198                                    .iter()
2199                                    .map(|expr| expr.to_string())
2200                                    .collect::<Vec<_>>()
2201                                    .join(", ");
2202                                format!("({item})")
2203                            })
2204                            .collect();
2205
2206                        let eclipse = if values.len() > 5 { "..." } else { "" };
2207                        write!(f, "Values: {}{}", str_values.join(", "), eclipse)
2208                    }
2209
2210                    LogicalPlan::TableScan(TableScan {
2211                        source,
2212                        table_name,
2213                        projection,
2214                        filters,
2215                        fetch,
2216                        skip,
2217                        ..
2218                    }) => {
2219                        let projected_fields = match projection {
2220                            Some(indices) => {
2221                                let schema = source.schema();
2222                                let names: Vec<&str> = indices
2223                                    .iter()
2224                                    .map(|i| schema.field(*i).name().as_str())
2225                                    .collect();
2226                                format!(" projection=[{}]", names.join(", "))
2227                            }
2228                            _ => "".to_string(),
2229                        };
2230
2231                        write!(f, "TableScan: {table_name}{projected_fields}")?;
2232
2233                        if !filters.is_empty() {
2234                            let mut full_filter = vec![];
2235                            let mut partial_filter = vec![];
2236                            let mut unsupported_filters = vec![];
2237                            let filters: Vec<&Expr> = filters.iter().collect();
2238
2239                            if let Ok(results) =
2240                                source.supports_filters_pushdown(&filters)
2241                            {
2242                                filters.iter().zip(results.iter()).for_each(
2243                                    |(x, res)| match res {
2244                                        TableProviderFilterPushDown::Exact => {
2245                                            full_filter.push(x)
2246                                        }
2247                                        TableProviderFilterPushDown::Inexact => {
2248                                            partial_filter.push(x)
2249                                        }
2250                                        TableProviderFilterPushDown::Unsupported => {
2251                                            unsupported_filters.push(x)
2252                                        }
2253                                    },
2254                                );
2255                            }
2256
2257                            if !full_filter.is_empty() {
2258                                write!(
2259                                    f,
2260                                    ", full_filters=[{}]",
2261                                    expr_vec_fmt!(full_filter)
2262                                )?;
2263                            }
2264                            if !partial_filter.is_empty() {
2265                                write!(
2266                                    f,
2267                                    ", partial_filters=[{}]",
2268                                    expr_vec_fmt!(partial_filter)
2269                                )?;
2270                            }
2271                            if !unsupported_filters.is_empty() {
2272                                write!(
2273                                    f,
2274                                    ", unsupported_filters=[{}]",
2275                                    expr_vec_fmt!(unsupported_filters)
2276                                )?;
2277                            }
2278                        }
2279
2280                        if let Some(n) = fetch {
2281                            write!(f, ", fetch={n}")?;
2282                        }
2283
2284                        if let Some(n) = skip {
2285                            write!(f, ", skip={n}")?;
2286                        }
2287
2288                        Ok(())
2289                    }
2290                    LogicalPlan::Projection(Projection { expr, .. }) => {
2291                        write!(f, "Projection:")?;
2292                        for (i, expr_item) in expr.iter().enumerate() {
2293                            if i > 0 {
2294                                write!(f, ",")?;
2295                            }
2296                            write!(f, " {expr_item}")?;
2297                        }
2298                        Ok(())
2299                    }
2300                    LogicalPlan::Dml(DmlStatement { table_name, op, .. }) => {
2301                        write!(f, "Dml: op=[{op}] table=[{table_name}]")?;
2302                        if let WriteOp::MergeInto(merge_op) = op {
2303                            write!(f, " {merge_op}")?;
2304                        }
2305                        Ok(())
2306                    }
2307                    LogicalPlan::Copy(CopyTo {
2308                        input: _,
2309                        output_url,
2310                        file_type,
2311                        options,
2312                        ..
2313                    }) => {
2314                        let op_str = options
2315                            .iter()
2316                            .map(|(k, v)| format!("{k} {v}"))
2317                            .collect::<Vec<String>>()
2318                            .join(", ");
2319
2320                        write!(
2321                            f,
2322                            "CopyTo: format={} output_url={output_url} options: ({op_str})",
2323                            file_type.get_ext()
2324                        )
2325                    }
2326                    LogicalPlan::Ddl(ddl) => {
2327                        write!(f, "{}", ddl.display())
2328                    }
2329                    LogicalPlan::Filter(Filter {
2330                        predicate: expr, ..
2331                    }) => write!(f, "Filter: {expr}"),
2332                    LogicalPlan::Window(Window { window_expr, .. }) => {
2333                        write!(
2334                            f,
2335                            "WindowAggr: windowExpr=[[{}]]",
2336                            expr_vec_fmt!(window_expr)
2337                        )
2338                    }
2339                    LogicalPlan::Aggregate(Aggregate {
2340                        group_expr,
2341                        aggr_expr,
2342                        ..
2343                    }) => write!(
2344                        f,
2345                        "Aggregate: groupBy=[[{}]], aggr=[[{}]]",
2346                        expr_vec_fmt!(group_expr),
2347                        expr_vec_fmt!(aggr_expr)
2348                    ),
2349                    LogicalPlan::Sort(Sort { expr, fetch, .. }) => {
2350                        write!(f, "Sort: ")?;
2351                        for (i, expr_item) in expr.iter().enumerate() {
2352                            if i > 0 {
2353                                write!(f, ", ")?;
2354                            }
2355                            write!(f, "{expr_item}")?;
2356                        }
2357                        if let Some(a) = fetch {
2358                            write!(f, ", fetch={a}")?;
2359                        }
2360
2361                        Ok(())
2362                    }
2363                    LogicalPlan::Join(Join {
2364                        on: keys,
2365                        filter,
2366                        join_constraint,
2367                        join_type,
2368                        null_aware,
2369                        null_aware_value_keys,
2370                        ..
2371                    }) => {
2372                        let join_expr: Vec<String> =
2373                            keys.iter().map(|(l, r)| format!("{l} = {r}")).collect();
2374                        let filter_expr = filter
2375                            .as_ref()
2376                            .map(|expr| format!(" Filter: {expr}"))
2377                            .unwrap_or_else(|| "".to_string());
2378                        let null_aware_expr = match (*null_aware, *null_aware_value_keys)
2379                        {
2380                            (false, _) => "".to_string(),
2381                            (true, 0 | 1) => " null_aware".to_string(),
2382                            (true, n) => format!(" null_aware(value_keys={n})"),
2383                        };
2384                        let join_type = if filter.is_none()
2385                            && keys.is_empty()
2386                            && *join_type == JoinType::Inner
2387                        {
2388                            "Cross".to_string()
2389                        } else {
2390                            join_type.to_string()
2391                        };
2392                        match join_constraint {
2393                            JoinConstraint::On => {
2394                                write!(f, "{join_type} Join:")?;
2395                                if !join_expr.is_empty() || !filter_expr.is_empty() {
2396                                    write!(
2397                                        f,
2398                                        " {}{}",
2399                                        join_expr.join(", "),
2400                                        filter_expr
2401                                    )?;
2402                                }
2403                                write!(f, "{null_aware_expr}")?;
2404                                Ok(())
2405                            }
2406                            JoinConstraint::Using => {
2407                                write!(
2408                                    f,
2409                                    "{} Join: Using {}{}{}",
2410                                    join_type,
2411                                    join_expr.join(", "),
2412                                    filter_expr,
2413                                    null_aware_expr,
2414                                )
2415                            }
2416                        }
2417                    }
2418                    LogicalPlan::AsOfJoin(AsOfJoin {
2419                        on,
2420                        match_condition,
2421                        join_constraint,
2422                        ..
2423                    }) => {
2424                        let equality = on
2425                            .iter()
2426                            .map(|(left, right)| format!("{left} = {right}"))
2427                            .join(", ");
2428                        write!(
2429                            f,
2430                            "AsOf Join: match=[{match_condition}], constraint={join_constraint:?}"
2431                        )?;
2432                        if !equality.is_empty() {
2433                            write!(f, ", on=[{equality}]")?;
2434                        }
2435                        Ok(())
2436                    }
2437                    LogicalPlan::Repartition(Repartition {
2438                        partitioning_scheme,
2439                        ..
2440                    }) => match partitioning_scheme {
2441                        Partitioning::RoundRobinBatch(n) => {
2442                            write!(f, "Repartition: RoundRobinBatch partition_count={n}")
2443                        }
2444                        Partitioning::Hash(expr, n) => {
2445                            let hash_expr: Vec<String> =
2446                                expr.iter().map(|e| format!("{e}")).collect();
2447                            write!(
2448                                f,
2449                                "Repartition: Hash({}) partition_count={}",
2450                                hash_expr.join(", "),
2451                                n
2452                            )
2453                        }
2454                        Partitioning::Range(range) => {
2455                            write!(f, "Repartition: {range}")
2456                        }
2457                        Partitioning::DistributeBy(expr) => {
2458                            let dist_by_expr: Vec<String> =
2459                                expr.iter().map(|e| format!("{e}")).collect();
2460                            write!(
2461                                f,
2462                                "Repartition: DistributeBy({})",
2463                                dist_by_expr.join(", "),
2464                            )
2465                        }
2466                    },
2467                    LogicalPlan::Limit(limit) => {
2468                        // Attempt to display `skip` and `fetch` as literals if possible, otherwise as expressions.
2469                        let skip_str = match limit.get_skip_type() {
2470                            Ok(SkipType::Literal(n)) => n.to_string(),
2471                            _ => limit
2472                                .skip
2473                                .as_ref()
2474                                .map_or_else(|| "None".to_string(), |x| x.to_string()),
2475                        };
2476                        let fetch_str = match limit.get_fetch_type() {
2477                            Ok(FetchType::Literal(Some(n))) => n.to_string(),
2478                            Ok(FetchType::Literal(None)) => "None".to_string(),
2479                            _ => limit
2480                                .fetch
2481                                .as_ref()
2482                                .map_or_else(|| "None".to_string(), |x| x.to_string()),
2483                        };
2484                        write!(f, "Limit: skip={skip_str}, fetch={fetch_str}")
2485                    }
2486                    LogicalPlan::Subquery(Subquery { .. }) => {
2487                        write!(f, "Subquery:")
2488                    }
2489                    LogicalPlan::SubqueryAlias(SubqueryAlias { alias, .. }) => {
2490                        write!(f, "SubqueryAlias: {alias}")
2491                    }
2492                    LogicalPlan::Statement(statement) => {
2493                        write!(f, "{}", statement.display())
2494                    }
2495                    LogicalPlan::Distinct(distinct) => match distinct {
2496                        Distinct::All(_) => write!(f, "Distinct:"),
2497                        Distinct::On(DistinctOn {
2498                            on_expr,
2499                            select_expr,
2500                            sort_expr,
2501                            ..
2502                        }) => write!(
2503                            f,
2504                            "DistinctOn: on_expr=[[{}]], select_expr=[[{}]], sort_expr=[[{}]]",
2505                            expr_vec_fmt!(on_expr),
2506                            expr_vec_fmt!(select_expr),
2507                            if let Some(sort_expr) = sort_expr {
2508                                expr_vec_fmt!(sort_expr)
2509                            } else {
2510                                "".to_string()
2511                            },
2512                        ),
2513                    },
2514                    LogicalPlan::Explain { .. } => write!(f, "Explain"),
2515                    LogicalPlan::Analyze { .. } => write!(f, "Analyze"),
2516                    LogicalPlan::Union(_) => write!(f, "Union"),
2517                    LogicalPlan::Extension(e) => e.node.fmt_for_explain(f),
2518                    LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
2519                        MaterializedCte { name, .. },
2520                    )) => {
2521                        write!(f, "MaterializedCte: name={name}")
2522                    }
2523                    LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(
2524                        MaterializedCteScan { name, .. },
2525                    )) => {
2526                        write!(f, "MaterializedCteScan: name={name}")
2527                    }
2528                    LogicalPlan::Show(Show { kind, .. }) => match kind {
2529                        ShowKind::Describe { .. }
2530                        | ShowKind::Columns {
2531                            detail: ColumnsDetail::Describe,
2532                            ..
2533                        } => write!(f, "DescribeTable"),
2534                        ShowKind::Tables => write!(f, "ShowTables"),
2535                        ShowKind::Columns { .. } => write!(f, "ShowColumns"),
2536                        ShowKind::CreateTable { .. } => write!(f, "ShowCreateTable"),
2537                        ShowKind::Variables { .. } => write!(f, "ShowVariables"),
2538                        ShowKind::Functions { .. } => write!(f, "ShowFunctions"),
2539                    },
2540                    LogicalPlan::Unnest(Unnest {
2541                        input: plan,
2542                        list_type_columns: list_col_indices,
2543                        struct_type_columns: struct_col_indices,
2544                        ..
2545                    }) => {
2546                        let input_columns = plan.schema().columns();
2547                        let list_type_columns = list_col_indices
2548                            .iter()
2549                            .map(|(i, unnest_info)| {
2550                                format!(
2551                                    "{}|depth={}",
2552                                    input_columns[*i], unnest_info.depth
2553                                )
2554                            })
2555                            .collect::<Vec<String>>();
2556                        let struct_type_columns = struct_col_indices
2557                            .iter()
2558                            .map(|i| &input_columns[*i])
2559                            .collect::<Vec<&Column>>();
2560                        // get items from input_columns indexed by list_col_indices
2561                        write!(
2562                            f,
2563                            "Unnest: lists[{}] structs[{}]",
2564                            expr_vec_fmt!(list_type_columns),
2565                            expr_vec_fmt!(struct_type_columns)
2566                        )
2567                    }
2568                }
2569            }
2570        }
2571        Wrapper(self)
2572    }
2573
2574    /// Return a `LogicalPLan` with all [`LambdaVariable`]'s resolved
2575    ///
2576    /// [`LambdaVariable`]: crate::expr::LambdaVariable
2577    pub fn resolve_lambda_variables(self) -> Result<Transformed<LogicalPlan>> {
2578        self.transform_with_subqueries(|plan| {
2579            let schema = merge_schema(&plan.inputs());
2580
2581            plan.map_expressions(|expr| expr.resolve_lambda_variables(&schema))
2582        })
2583    }
2584}
2585
2586impl Display for LogicalPlan {
2587    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2588        self.display_indent().fmt(f)
2589    }
2590}
2591
2592impl ToStringifiedPlan for LogicalPlan {
2593    fn to_stringified(&self, plan_type: PlanType) -> StringifiedPlan {
2594        StringifiedPlan::new(plan_type, self.display_indent().to_string())
2595    }
2596}
2597
2598/// Relationship produces 0 or 1 placeholder rows with specified output schema
2599/// In most cases the output schema for `EmptyRelation` would be empty,
2600/// however, it can be non-empty typically for optimizer rules
2601#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2602pub struct EmptyRelation {
2603    /// Whether to produce a placeholder row
2604    pub produce_one_row: bool,
2605    /// The schema description of the output
2606    pub schema: DFSchemaRef,
2607}
2608
2609// Manual implementation needed because of `schema` field. Comparison excludes this field.
2610impl PartialOrd for EmptyRelation {
2611    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2612        self.produce_one_row
2613            .partial_cmp(&other.produce_one_row)
2614            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
2615            .filter(|cmp| *cmp != Ordering::Equal || self == other)
2616    }
2617}
2618
2619/// A variadic query operation, Recursive CTE.
2620///
2621/// # Recursive Query Evaluation
2622///
2623/// From the [Postgres Docs]:
2624///
2625/// 1. Evaluate the non-recursive term. For `UNION` (but not `UNION ALL`),
2626///    discard duplicate rows. Include all remaining rows in the result of the
2627///    recursive query, and also place them in a temporary working table.
2628///
2629/// 2. So long as the working table is not empty, repeat these steps:
2630///
2631/// * Evaluate the recursive term, substituting the current contents of the
2632///   working table for the recursive self-reference. For `UNION` (but not `UNION
2633///   ALL`), discard duplicate rows and rows that duplicate any previous result
2634///   row. Include all remaining rows in the result of the recursive query, and
2635///   also place them in a temporary intermediate table.
2636///
2637/// * Replace the contents of the working table with the contents of the
2638///   intermediate table, then empty the intermediate table.
2639///
2640/// [Postgres Docs]: https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-RECURSIVE
2641#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2642pub struct RecursiveQuery {
2643    /// Name of the query
2644    pub name: String,
2645    /// The static term (initial contents of the working table)
2646    pub static_term: Arc<LogicalPlan>,
2647    /// The recursive term (evaluated on the contents of the working table until
2648    /// it returns an empty set)
2649    pub recursive_term: Arc<LogicalPlan>,
2650    /// Should the output of the recursive term be deduplicated (`UNION`) or
2651    /// not (`UNION ALL`).
2652    pub is_distinct: bool,
2653    /// Schema exposed to parent plans after reconciling the static and recursive terms.
2654    pub schema: DFSchemaRef,
2655}
2656
2657impl PartialOrd for RecursiveQuery {
2658    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2659        match self.name.partial_cmp(&other.name) {
2660            Some(Ordering::Equal) => {
2661                match self.static_term.partial_cmp(&other.static_term) {
2662                    Some(Ordering::Equal) => {
2663                        match self.recursive_term.partial_cmp(&other.recursive_term) {
2664                            Some(Ordering::Equal) => {
2665                                self.is_distinct.partial_cmp(&other.is_distinct)
2666                            }
2667                            cmp => cmp,
2668                        }
2669                    }
2670                    cmp => cmp,
2671                }
2672            }
2673            cmp => cmp,
2674        }
2675        // If the query definition compares equal but the derived schema differs,
2676        // return `None` instead of contradicting `PartialEq` with `Some(Equal)`.
2677        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
2678        .filter(|cmp| *cmp != Ordering::Equal || self == other)
2679    }
2680}
2681
2682impl RecursiveQuery {
2683    pub fn try_new(
2684        name: String,
2685        static_term: Arc<LogicalPlan>,
2686        recursive_term: Arc<LogicalPlan>,
2687        is_distinct: bool,
2688    ) -> Result<Self> {
2689        let schema =
2690            recursive_query_output_schema(static_term.schema(), recursive_term.schema())?;
2691        Ok(Self {
2692            name,
2693            static_term,
2694            recursive_term,
2695            is_distinct,
2696            schema,
2697        })
2698    }
2699}
2700
2701/// Compute a recursive query's output schema by considering both its static and
2702/// recursive terms.
2703///
2704/// Field names, types, and metadata come from the static term. A field is
2705/// nullable if either the static or the recursive term produces a nullable
2706/// value in that position, matching how `UNION` reconciles branch nullability.
2707///
2708/// Functional dependencies are intentionally dropped: the recursive term
2709/// appends rows that can duplicate values the static term guarantees unique, so
2710/// any FDs carried by the static term may not hold over the combined output.
2711fn recursive_query_output_schema(
2712    static_schema: &DFSchemaRef,
2713    recursive_schema: &DFSchemaRef,
2714) -> Result<DFSchemaRef> {
2715    if static_schema.fields().len() != recursive_schema.fields().len() {
2716        return Err(DataFusionError::Plan(format!(
2717            "Non-recursive term and recursive term must have the same number of columns ({} != {})",
2718            static_schema.fields().len(),
2719            recursive_schema.fields().len()
2720        )));
2721    }
2722
2723    let fields = static_schema
2724        .iter()
2725        .zip(recursive_schema.fields())
2726        .map(|((qualifier, static_field), recursive_field)| {
2727            let nullable = static_field.is_nullable() || recursive_field.is_nullable();
2728            (
2729                qualifier.cloned(),
2730                static_field.as_ref().clone().with_nullable(nullable).into(),
2731            )
2732        })
2733        .collect::<Vec<_>>();
2734
2735    DFSchema::new_with_metadata(fields, static_schema.metadata().clone())
2736        .map(DFSchemaRef::new)
2737}
2738
2739/// Values expression. See
2740/// [Postgres VALUES](https://www.postgresql.org/docs/current/queries-values.html)
2741/// documentation for more details.
2742#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2743pub struct Values {
2744    /// The table schema
2745    pub schema: DFSchemaRef,
2746    /// Values
2747    pub values: Vec<Vec<Expr>>,
2748}
2749
2750// Manual implementation needed because of `schema` field. Comparison excludes this field.
2751impl PartialOrd for Values {
2752    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2753        self.values
2754            .partial_cmp(&other.values)
2755            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
2756            .filter(|cmp| *cmp != Ordering::Equal || self == other)
2757    }
2758}
2759
2760/// Evaluates an arbitrary list of expressions (essentially a
2761/// SELECT with an expression list) on its input.
2762#[derive(Clone, PartialEq, Eq, Hash, Debug)]
2763// mark non_exhaustive to encourage use of try_new/new()
2764#[non_exhaustive]
2765pub struct Projection {
2766    /// The list of expressions
2767    pub expr: Vec<Expr>,
2768    /// The incoming logical plan
2769    pub input: Arc<LogicalPlan>,
2770    /// The schema description of the output
2771    pub schema: DFSchemaRef,
2772}
2773
2774// Manual implementation needed because of `schema` field. Comparison excludes this field.
2775impl PartialOrd for Projection {
2776    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2777        match self.expr.partial_cmp(&other.expr) {
2778            Some(Ordering::Equal) => self.input.partial_cmp(&other.input),
2779            cmp => cmp,
2780        }
2781        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
2782        .filter(|cmp| *cmp != Ordering::Equal || self == other)
2783    }
2784}
2785
2786impl Projection {
2787    /// Create a new Projection
2788    pub fn try_new(expr: Vec<Expr>, input: Arc<LogicalPlan>) -> Result<Self> {
2789        let projection_schema = projection_schema(&input, &expr)?;
2790        Self::try_new_with_schema(expr, input, projection_schema)
2791    }
2792
2793    /// Create a new Projection using the specified output schema
2794    pub fn try_new_with_schema(
2795        expr: Vec<Expr>,
2796        input: Arc<LogicalPlan>,
2797        schema: DFSchemaRef,
2798    ) -> Result<Self> {
2799        #[expect(deprecated)]
2800        if !expr.iter().any(|e| matches!(e, Expr::Wildcard { .. }))
2801            && expr.len() != schema.fields().len()
2802        {
2803            return plan_err!(
2804                "Projection has mismatch between number of expressions ({}) and number of fields in schema ({})",
2805                expr.len(),
2806                schema.fields().len()
2807            );
2808        }
2809        Ok(Self {
2810            expr,
2811            input,
2812            schema,
2813        })
2814    }
2815
2816    /// Create a new Projection using the specified output schema
2817    pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
2818        let expr: Vec<Expr> = schema.columns().into_iter().map(Expr::Column).collect();
2819        Self {
2820            expr,
2821            input,
2822            schema,
2823        }
2824    }
2825}
2826
2827/// Computes the schema of the result produced by applying a projection to the input logical plan.
2828///
2829/// # Arguments
2830///
2831/// * `input`: A reference to the input `LogicalPlan` for which the projection schema
2832///   will be computed.
2833/// * `exprs`: A slice of `Expr` expressions representing the projection operation to apply.
2834///
2835/// # Metadata Handling
2836///
2837/// - **Schema-level metadata**: Passed through unchanged from the input schema
2838/// - **Field-level metadata**: Determined by each expression via [`exprlist_to_fields`], which
2839///   calls [`Expr::to_field`] to handle expression-specific metadata (literals, aliases, etc.)
2840///
2841/// # Returns
2842///
2843/// A `Result` containing an `Arc<DFSchema>` representing the schema of the result
2844/// produced by the projection operation. If the schema computation is successful,
2845/// the `Result` will contain the schema; otherwise, it will contain an error.
2846pub fn projection_schema(input: &LogicalPlan, exprs: &[Expr]) -> Result<Arc<DFSchema>> {
2847    // Preserve input schema metadata at the schema level
2848    let metadata = input.schema().metadata().clone();
2849
2850    // Convert expressions to fields with Field properties determined by `Expr::to_field`
2851    let schema =
2852        DFSchema::new_with_metadata(exprlist_to_fields(exprs, input)?, metadata)?
2853            .with_functional_dependencies(calc_func_dependencies_for_project(
2854                exprs, input,
2855            )?)?;
2856
2857    Ok(Arc::new(schema))
2858}
2859
2860/// Aliased subquery
2861#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2862// mark non_exhaustive to encourage use of try_new/new()
2863#[non_exhaustive]
2864pub struct SubqueryAlias {
2865    /// The incoming logical plan
2866    pub input: Arc<LogicalPlan>,
2867    /// The alias for the input relation
2868    pub alias: TableReference,
2869    /// The schema with qualified field names
2870    pub schema: DFSchemaRef,
2871}
2872
2873impl SubqueryAlias {
2874    pub fn try_new(
2875        plan: Arc<LogicalPlan>,
2876        alias: impl Into<TableReference>,
2877    ) -> Result<Self> {
2878        let alias = alias.into();
2879
2880        // Since SubqueryAlias will replace all field qualification for the output schema of `plan`,
2881        // no field must share the same column name as this would lead to ambiguity when referencing
2882        // columns in parent logical nodes.
2883
2884        // Compute unique aliases, if any, for each column of the input's schema.
2885        let aliases = unique_field_aliases(plan.schema().fields());
2886        let is_projection_needed = aliases.iter().any(Option::is_some);
2887
2888        // Insert a projection node, if needed, to make sure aliases are applied.
2889        let plan = if is_projection_needed {
2890            let projection_expressions = aliases
2891                .iter()
2892                .zip(plan.schema().iter())
2893                .map(|(alias, (qualifier, field))| {
2894                    let column =
2895                        Expr::Column(Column::new(qualifier.cloned(), field.name()));
2896                    match alias {
2897                        None => column,
2898                        Some(alias) => {
2899                            Expr::Alias(Alias::new(column, qualifier.cloned(), alias))
2900                        }
2901                    }
2902                })
2903                .collect();
2904            let projection = Projection::try_new(projection_expressions, plan)?;
2905            Arc::new(LogicalPlan::Projection(projection))
2906        } else {
2907            plan
2908        };
2909
2910        // Requalify fields with the new `alias`.
2911        let fields = plan.schema().fields().clone();
2912        let meta_data = plan.schema().metadata().clone();
2913        let func_dependencies = plan.schema().functional_dependencies().clone();
2914
2915        let schema = DFSchema::from_unqualified_fields(fields, meta_data)?;
2916        let schema = schema.as_arrow();
2917
2918        let schema = DFSchemaRef::new(
2919            DFSchema::try_from_qualified_schema(alias.clone(), schema)?
2920                .with_functional_dependencies(func_dependencies)?,
2921        );
2922        Ok(SubqueryAlias {
2923            input: plan,
2924            alias,
2925            schema,
2926        })
2927    }
2928}
2929
2930// Manual implementation needed because of `schema` field. Comparison excludes this field.
2931impl PartialOrd for SubqueryAlias {
2932    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2933        match self.input.partial_cmp(&other.input) {
2934            Some(Ordering::Equal) => self.alias.partial_cmp(&other.alias),
2935            cmp => cmp,
2936        }
2937        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
2938        .filter(|cmp| *cmp != Ordering::Equal || self == other)
2939    }
2940}
2941
2942/// Filters rows from its input that do not match an
2943/// expression (essentially a WHERE clause with a predicate
2944/// expression).
2945///
2946/// Semantically, `<predicate>` is evaluated for each row of the input;
2947/// If the value of `<predicate>` is true, the input row is passed to
2948/// the output. If the value of `<predicate>` is false, the row is
2949/// discarded.
2950///
2951/// Filter should not be created directly but instead use `try_new()`
2952/// and that these fields are only pub to support pattern matching
2953#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
2954#[non_exhaustive]
2955pub struct Filter {
2956    /// The predicate expression, which must have Boolean type.
2957    pub predicate: Expr,
2958    /// The incoming logical plan
2959    pub input: Arc<LogicalPlan>,
2960}
2961
2962impl Filter {
2963    /// Create a new filter operator.
2964    ///
2965    /// Skips the type-checking, window function check and dealiasing done in
2966    /// [Self::try_new].
2967    ///
2968    /// **Preconditions:**
2969    /// - the `predicate` expression returns a boolean value
2970    /// - the `predicate` expression is not aliased
2971    /// - the `predicate` expression contains no window function calls
2972    ///
2973    /// # Public Only for Internal Use:
2974    ///
2975    /// This is not a public API and is for internal use only; see [API policy] for details.
2976    ///
2977    /// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis
2978    #[doc(hidden)]
2979    pub fn new(predicate: Expr, input: Arc<LogicalPlan>) -> Self {
2980        Self { predicate, input }
2981    }
2982
2983    /// Create a new filter operator.
2984    ///
2985    /// Returns an error if the predicate is not boolean or contains a window
2986    /// function call, which cannot be evaluated by a filter (see
2987    /// [`check_no_window_functions`]).
2988    ///
2989    /// Notes: as Aliases have no effect on the output of a filter operator,
2990    /// they are removed from the predicate expression.
2991    pub fn try_new(predicate: Expr, input: Arc<LogicalPlan>) -> Result<Self> {
2992        Self::try_new_internal(predicate, input)
2993    }
2994
2995    fn is_allowed_filter_type(data_type: &DataType) -> bool {
2996        match data_type {
2997            // Interpret NULL as a missing boolean value.
2998            DataType::Boolean | DataType::Null => true,
2999            DataType::Dictionary(_, value_type) => {
3000                Filter::is_allowed_filter_type(value_type.as_ref())
3001            }
3002            _ => false,
3003        }
3004    }
3005
3006    fn try_new_internal(predicate: Expr, input: Arc<LogicalPlan>) -> Result<Self> {
3007        // Filters are evaluated before window functions are computed, so a
3008        // window call in the predicate has no physical equivalent. Reject it
3009        // here rather than failing during physical planning.
3010        check_no_window_functions(&predicate, "filter predicates")?;
3011
3012        // Filter predicates must return a boolean value so we try and validate that here.
3013        // Note that it is not always possible to resolve the predicate expression during plan
3014        // construction (such as with correlated subqueries) so we make a best effort here and
3015        // ignore errors resolving the expression against the schema.
3016        if let Ok(predicate_type) = predicate.get_type(input.schema())
3017            && !Filter::is_allowed_filter_type(&predicate_type)
3018        {
3019            return plan_err!(
3020                "Cannot create filter with non-boolean predicate '{predicate}' returning {predicate_type}"
3021            );
3022        }
3023
3024        Ok(Self {
3025            predicate: predicate.unalias_nested().data,
3026            input,
3027        })
3028    }
3029
3030    /// Is this filter guaranteed to return 0 or 1 row in a given instantiation?
3031    ///
3032    /// This function will return `true` if its predicate contains a conjunction of
3033    /// `col(a) = <expr>`, where its schema has a unique filter that is covered
3034    /// by this conjunction.
3035    ///
3036    /// For example, for the table:
3037    /// ```sql
3038    /// CREATE TABLE t (a INTEGER PRIMARY KEY, b INTEGER);
3039    /// ```
3040    /// `Filter(a = 2).is_scalar() == true`
3041    /// , whereas
3042    /// `Filter(b = 2).is_scalar() == false`
3043    /// and
3044    /// `Filter(a = 2 OR b = 2).is_scalar() == false`
3045    fn is_scalar(&self) -> bool {
3046        let schema = self.input.schema();
3047
3048        let functional_dependencies = self.input.schema().functional_dependencies();
3049        let unique_keys = functional_dependencies.iter().filter(|dep| {
3050            let nullable = dep.nullable
3051                && dep
3052                    .source_indices
3053                    .iter()
3054                    .any(|&source| schema.field(source).is_nullable());
3055            !nullable
3056                && dep.mode == Dependency::Single
3057                && dep.target_indices.len() == schema.fields().len()
3058        });
3059
3060        let exprs = split_conjunction(&self.predicate);
3061        let eq_pred_cols: HashSet<_> = exprs
3062            .iter()
3063            .filter_map(|expr| {
3064                let Expr::BinaryExpr(BinaryExpr {
3065                    left,
3066                    op: Operator::Eq,
3067                    right,
3068                }) = expr
3069                else {
3070                    return None;
3071                };
3072                // This is a no-op filter expression
3073                if left == right {
3074                    return None;
3075                }
3076
3077                match (left.as_ref(), right.as_ref()) {
3078                    (Expr::Column(_), Expr::Column(_)) => None,
3079                    (Expr::Column(c), _) | (_, Expr::Column(c)) => {
3080                        Some(schema.index_of_column(c).unwrap())
3081                    }
3082                    _ => None,
3083                }
3084            })
3085            .collect();
3086
3087        // If we have a functional dependence that is a subset of our predicate,
3088        // this filter is scalar
3089        for key in unique_keys {
3090            if key.source_indices.iter().all(|c| eq_pred_cols.contains(c)) {
3091                return true;
3092            }
3093        }
3094        false
3095    }
3096}
3097
3098/// Window its input based on a set of window spec and window function (e.g. SUM or RANK)
3099///
3100/// # Output Schema
3101///
3102/// The output schema is the input schema followed by the window function
3103/// expressions, in order.
3104///
3105/// For example, given the input schema `"A", "B", "C"` and the window function
3106/// `SUM(A) OVER (PARTITION BY B+1 ORDER BY C)`, the output schema will be `"A",
3107/// "B", "C", "SUM(A) OVER ..."` where `"SUM(A) OVER ..."` is the name of the
3108/// output column.
3109///
3110/// Note that the `PARTITION BY` expression "B+1" is not produced in the output
3111/// schema.
3112#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3113pub struct Window {
3114    /// The incoming logical plan
3115    pub input: Arc<LogicalPlan>,
3116    /// The window function expression
3117    pub window_expr: Vec<Expr>,
3118    /// The schema description of the window output
3119    pub schema: DFSchemaRef,
3120}
3121
3122impl Window {
3123    /// Create a new window operator.
3124    pub fn try_new(window_expr: Vec<Expr>, input: Arc<LogicalPlan>) -> Result<Self> {
3125        // Reject e.g. `sum(sum(x) OVER ()) OVER ()` here rather than letting it
3126        // reach physical planning, which has no equivalent for a nested window
3127        // function.
3128        check_aggregate_and_window_nesting(window_expr.iter())?;
3129
3130        let fields: Vec<(Option<TableReference>, Arc<Field>)> = input
3131            .schema()
3132            .iter()
3133            .map(|(q, f)| (q.cloned(), Arc::clone(f)))
3134            .collect();
3135        let input_len = fields.len();
3136        let mut window_fields = fields;
3137        let expr_fields = exprlist_to_fields(window_expr.as_slice(), &input)?;
3138        window_fields.extend_from_slice(expr_fields.as_slice());
3139        let metadata = input.schema().metadata().clone();
3140
3141        // Update functional dependencies for window:
3142        let mut window_func_dependencies =
3143            input.schema().functional_dependencies().clone();
3144        window_func_dependencies.extend_target_indices(window_fields.len());
3145
3146        // Since we know that ROW_NUMBER outputs will be unique (i.e. it consists
3147        // of consecutive numbers per partition), we can represent this fact with
3148        // functional dependencies.
3149        let mut new_dependencies = window_expr
3150            .iter()
3151            .enumerate()
3152            .filter_map(|(idx, expr)| {
3153                let Expr::WindowFunction(window_fun) = expr else {
3154                    return None;
3155                };
3156                let WindowFunction {
3157                    fun: WindowFunctionDefinition::WindowUDF(udwf),
3158                    params: WindowFunctionParams { partition_by, .. },
3159                } = window_fun.as_ref()
3160                else {
3161                    return None;
3162                };
3163                // When there is no PARTITION BY, row number will be unique
3164                // across the entire table.
3165                if udwf.name() == "row_number" && partition_by.is_empty() {
3166                    Some(idx + input_len)
3167                } else {
3168                    None
3169                }
3170            })
3171            .map(|idx| {
3172                FunctionalDependence::new(vec![idx], vec![], false)
3173                    .with_mode(Dependency::Single)
3174            })
3175            .collect::<Vec<_>>();
3176
3177        if !new_dependencies.is_empty() {
3178            for dependence in new_dependencies.iter_mut() {
3179                dependence.target_indices = (0..window_fields.len()).collect();
3180            }
3181            // Add the dependency introduced because of ROW_NUMBER window function to the functional dependency
3182            let new_deps = FunctionalDependencies::new(new_dependencies);
3183            window_func_dependencies.extend(new_deps);
3184        }
3185
3186        // Validate that FILTER clauses are only used with aggregate window functions
3187        if let Some(e) = window_expr.iter().find(|e| {
3188            matches!(
3189                e,
3190                Expr::WindowFunction(wf)
3191                    if !matches!(wf.fun, WindowFunctionDefinition::AggregateUDF(_))
3192                        && wf.params.filter.is_some()
3193            )
3194        }) {
3195            return plan_err!(
3196                "FILTER clause can only be used with aggregate window functions. Found in '{e}'"
3197            );
3198        }
3199
3200        Self::try_new_with_schema(
3201            window_expr,
3202            input,
3203            Arc::new(
3204                DFSchema::new_with_metadata(window_fields, metadata)?
3205                    .with_functional_dependencies(window_func_dependencies)?,
3206            ),
3207        )
3208    }
3209
3210    /// Create a new window function using the provided schema to avoid the overhead of
3211    /// building the schema again when the schema is already known.
3212    ///
3213    /// This method should only be called when you are absolutely sure that the schema being
3214    /// provided is correct for the window function. If in doubt, call [try_new](Self::try_new) instead.
3215    pub fn try_new_with_schema(
3216        window_expr: Vec<Expr>,
3217        input: Arc<LogicalPlan>,
3218        schema: DFSchemaRef,
3219    ) -> Result<Self> {
3220        let input_fields_count = input.schema().fields().len();
3221        if schema.fields().len() != input_fields_count + window_expr.len() {
3222            return plan_err!(
3223                "Window schema has wrong number of fields. Expected {} got {}",
3224                input_fields_count + window_expr.len(),
3225                schema.fields().len()
3226            );
3227        }
3228
3229        Ok(Window {
3230            input,
3231            window_expr,
3232            schema,
3233        })
3234    }
3235}
3236
3237// Manual implementation needed because of `schema` field. Comparison excludes this field.
3238impl PartialOrd for Window {
3239    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3240        match self.input.partial_cmp(&other.input)? {
3241            Ordering::Equal => {} // continue
3242            not_equal => return Some(not_equal),
3243        }
3244
3245        match self.window_expr.partial_cmp(&other.window_expr)? {
3246            Ordering::Equal => {} // continue
3247            not_equal => return Some(not_equal),
3248        }
3249
3250        // Contract for PartialOrd and PartialEq consistency requires that
3251        // a == b if and only if partial_cmp(a, b) == Some(Equal).
3252        if self == other {
3253            Some(Ordering::Equal)
3254        } else {
3255            None
3256        }
3257    }
3258}
3259
3260/// Produces rows from a table provider by reference or from the context
3261#[derive(Clone)]
3262pub struct TableScan {
3263    /// The name of the table
3264    pub table_name: TableReference,
3265    /// The source of the table
3266    pub source: Arc<dyn TableSource>,
3267    /// Optional column indices to use as a projection
3268    pub projection: Option<Vec<usize>>,
3269    /// The schema description of the output
3270    pub projected_schema: DFSchemaRef,
3271    /// Optional expressions to be used as filters by the table provider
3272    pub filters: Vec<Expr>,
3273    /// Optional number of rows to read
3274    pub fetch: Option<usize>,
3275    /// Optional number of rows to skip
3276    pub skip: Option<usize>,
3277    /// Statistics the planner would like the provider to answer for this
3278    /// scan, typically attached by a custom optimizer rule from the
3279    /// surrounding plan (e.g. Min/Max for sort keys).
3280    ///
3281    /// A [`BTreeSet`], not a `Vec` to keep the resulting plan deterministic.
3282    ///
3283    // Boxed to keep this rarely-populated field from growing every
3284    // `TableScan` (and thus `LogicalPlan`) by its own size;
3285    // see `test_size_of_logical_plan`.
3286    pub statistics_requests: Box<BTreeSet<StatisticsRequest>>,
3287}
3288
3289impl Debug for TableScan {
3290    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
3291        f.debug_struct("TableScan")
3292            .field("table_name", &self.table_name)
3293            .field("source", &"...")
3294            .field("projection", &self.projection)
3295            .field("projected_schema", &self.projected_schema)
3296            .field("filters", &self.filters)
3297            .field("fetch", &self.fetch)
3298            .field("skip", &self.skip)
3299            .finish_non_exhaustive()
3300    }
3301}
3302
3303impl PartialEq for TableScan {
3304    fn eq(&self, other: &Self) -> bool {
3305        self.table_name == other.table_name
3306            && self.projection == other.projection
3307            && self.projected_schema == other.projected_schema
3308            && self.filters == other.filters
3309            && self.fetch == other.fetch
3310    }
3311}
3312
3313impl Eq for TableScan {}
3314
3315// Manual implementation needed because of `source` and `projected_schema` fields.
3316// Comparison excludes these field.
3317impl PartialOrd for TableScan {
3318    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3319        #[derive(PartialEq, PartialOrd)]
3320        struct ComparableTableScan<'a> {
3321            /// The name of the table
3322            pub table_name: &'a TableReference,
3323            /// Optional column indices to use as a projection
3324            pub projection: &'a Option<Vec<usize>>,
3325            /// Optional expressions to be used as filters by the table provider
3326            pub filters: &'a Vec<Expr>,
3327            /// Optional number of rows to read
3328            pub fetch: &'a Option<usize>,
3329        }
3330        let comparable_self = ComparableTableScan {
3331            table_name: &self.table_name,
3332            projection: &self.projection,
3333            filters: &self.filters,
3334            fetch: &self.fetch,
3335        };
3336        let comparable_other = ComparableTableScan {
3337            table_name: &other.table_name,
3338            projection: &other.projection,
3339            filters: &other.filters,
3340            fetch: &other.fetch,
3341        };
3342        comparable_self
3343            .partial_cmp(&comparable_other)
3344            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
3345            .filter(|cmp| *cmp != Ordering::Equal || self == other)
3346    }
3347}
3348
3349impl Hash for TableScan {
3350    fn hash<H: Hasher>(&self, state: &mut H) {
3351        self.table_name.hash(state);
3352        self.projection.hash(state);
3353        self.projected_schema.hash(state);
3354        self.filters.hash(state);
3355        self.fetch.hash(state);
3356    }
3357}
3358
3359impl TableScan {
3360    /// Initialize TableScan with appropriate schema from the given
3361    /// arguments.
3362    #[deprecated(since = "54.0.0", note = "use `TableScanBuilder` instead")]
3363    pub fn try_new(
3364        table_name: impl Into<TableReference>,
3365        table_source: Arc<dyn TableSource>,
3366        projection: Option<Vec<usize>>,
3367        filters: Vec<Expr>,
3368        fetch: Option<usize>,
3369    ) -> Result<Self> {
3370        TableScanBuilder::new(table_name, table_source)
3371            .with_projection(projection)
3372            .with_filters(filters)
3373            .with_fetch(fetch)
3374            .build()
3375    }
3376}
3377
3378/// Builder for [`TableScan`].
3379///
3380/// Prefer this over constructing a [`TableScan`] directly: it derives the
3381/// `projected_schema` from the source schema and projection, and is resilient
3382/// to new fields being added to [`TableScan`]. An existing scan can be turned
3383/// back into a builder with `TableScanBuilder::from(scan)`, tweaked, and
3384/// rebuilt with [`TableScanBuilder::build`].
3385pub struct TableScanBuilder {
3386    table_name: TableReference,
3387    source: Arc<dyn TableSource>,
3388    projection: Option<Vec<usize>>,
3389    filters: Vec<Expr>,
3390    fetch: Option<usize>,
3391    skip: Option<usize>,
3392    #[expect(clippy::box_collection)] // additional indirection for smaller size_of()
3393    statistics_requests: Box<BTreeSet<StatisticsRequest>>,
3394}
3395
3396impl TableScanBuilder {
3397    /// Create a new builder for a scan of `source` named `table_name`.
3398    pub fn new(
3399        table_name: impl Into<TableReference>,
3400        source: Arc<dyn TableSource>,
3401    ) -> Self {
3402        Self {
3403            table_name: table_name.into(),
3404            source,
3405            projection: None,
3406            filters: vec![],
3407            fetch: None,
3408            skip: None,
3409            statistics_requests: Box::default(),
3410        }
3411    }
3412
3413    /// Set the column projection (indices into the source schema).
3414    pub fn with_projection(mut self, projection: Option<Vec<usize>>) -> Self {
3415        self.projection = projection;
3416        self
3417    }
3418
3419    /// Set the filter expressions offered to the table provider.
3420    pub fn with_filters(mut self, filters: Vec<Expr>) -> Self {
3421        self.filters = filters;
3422        self
3423    }
3424
3425    /// Set the maximum number of rows to read.
3426    pub fn with_fetch(mut self, fetch: Option<usize>) -> Self {
3427        self.fetch = fetch;
3428        self
3429    }
3430
3431    /// Set the number of rows to skip.
3432    pub fn with_skip(mut self, skip: Option<usize>) -> Self {
3433        self.skip = skip;
3434        self
3435    }
3436
3437    /// Set the statistics requests for the scan. See
3438    /// [`TableScan::statistics_requests`].
3439    pub fn with_statistics_requests(
3440        mut self,
3441        statistics_requests: BTreeSet<StatisticsRequest>,
3442    ) -> Self {
3443        self.statistics_requests = Box::new(statistics_requests);
3444        self
3445    }
3446
3447    /// Build the [`TableScan`], deriving its `projected_schema` from the
3448    /// source schema and projection.
3449    pub fn build(self) -> Result<TableScan> {
3450        let TableScanBuilder {
3451            table_name,
3452            source,
3453            projection,
3454            filters,
3455            fetch,
3456            skip,
3457            statistics_requests,
3458        } = self;
3459
3460        if table_name.table().is_empty() {
3461            return plan_err!("table_name cannot be empty");
3462        }
3463        let schema = source.schema();
3464        let func_dependencies = FunctionalDependencies::new_from_constraints(
3465            source.constraints(),
3466            schema.fields.len(),
3467        );
3468        let projected_schema = projection
3469            .as_ref()
3470            .map(|p| {
3471                let projected_func_dependencies =
3472                    func_dependencies.project_functional_dependencies(p, p.len());
3473
3474                let df_schema = DFSchema::new_with_metadata(
3475                    p.iter()
3476                        .map(|i| {
3477                            (Some(table_name.clone()), Arc::clone(&schema.fields()[*i]))
3478                        })
3479                        .collect(),
3480                    schema.metadata.clone(),
3481                )?;
3482                df_schema.with_functional_dependencies(projected_func_dependencies)
3483            })
3484            .unwrap_or_else(|| {
3485                let df_schema =
3486                    DFSchema::try_from_qualified_schema(table_name.clone(), &schema)?;
3487                df_schema.with_functional_dependencies(func_dependencies)
3488            })?;
3489        let projected_schema = Arc::new(projected_schema);
3490
3491        Ok(TableScan {
3492            table_name,
3493            source,
3494            projection,
3495            projected_schema,
3496            filters,
3497            fetch,
3498            skip,
3499            statistics_requests,
3500        })
3501    }
3502}
3503
3504impl From<TableScan> for TableScanBuilder {
3505    fn from(scan: TableScan) -> Self {
3506        Self {
3507            table_name: scan.table_name,
3508            source: scan.source,
3509            projection: scan.projection,
3510            filters: scan.filters,
3511            fetch: scan.fetch,
3512            skip: scan.skip,
3513            statistics_requests: scan.statistics_requests,
3514        }
3515    }
3516}
3517
3518// Repartition the plan based on a partitioning scheme.
3519#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
3520pub struct Repartition {
3521    /// The incoming logical plan
3522    pub input: Arc<LogicalPlan>,
3523    /// The partitioning scheme
3524    pub partitioning_scheme: Partitioning,
3525}
3526
3527/// Union multiple inputs
3528#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3529pub struct Union {
3530    /// Inputs to merge
3531    pub inputs: Vec<Arc<LogicalPlan>>,
3532    /// Union schema. Should be the same for all inputs.
3533    pub schema: DFSchemaRef,
3534}
3535
3536impl Union {
3537    /// Constructs new Union instance deriving schema from inputs.
3538    /// Schema data types must match exactly.
3539    pub fn try_new(inputs: Vec<Arc<LogicalPlan>>) -> Result<Self> {
3540        let schema = Self::derive_schema_from_inputs(&inputs, false, false)?;
3541        Ok(Union { inputs, schema })
3542    }
3543
3544    /// Constructs new Union instance deriving schema from inputs.
3545    /// Infers common output types without inserting casts into the inputs.
3546    /// If a common type cannot be inferred, keeps the first input's type so
3547    /// the analyzer can resolve or reject the inputs later.
3548    // TODO (https://github.com/apache/datafusion/issues/14380): Inputs are still
3549    // uncast until the analyzer runs.
3550    pub fn try_new_with_loose_types(inputs: Vec<Arc<LogicalPlan>>) -> Result<Self> {
3551        let schema = Self::derive_schema_from_inputs(&inputs, true, false)?;
3552        Ok(Union { inputs, schema })
3553    }
3554
3555    /// Constructs a new Union instance that combines rows from different tables by name,
3556    /// instead of by position. This means that the specified inputs need not have schemas
3557    /// that are all the same width.
3558    ///
3559    /// Like [`Self::try_new_with_loose_types`], this infers common output types
3560    /// without inserting casts. Missing columns contribute `NULL` at their input
3561    /// position. For example, a missing `Dictionary(Int32, Utf8)` column and a
3562    /// present one produce `Utf8` in either input order.
3563    pub fn try_new_by_name(inputs: Vec<Arc<LogicalPlan>>) -> Result<Self> {
3564        let schema = Self::derive_schema_from_inputs(&inputs, true, true)?;
3565        let inputs = Self::rewrite_inputs_from_schema(&schema, inputs)?;
3566
3567        Ok(Union { inputs, schema })
3568    }
3569
3570    /// When constructing a `UNION BY NAME`, we need to wrap inputs
3571    /// in an additional `Projection` to account for absence of columns
3572    /// in input schemas or differing projection orders.
3573    fn rewrite_inputs_from_schema(
3574        schema: &Arc<DFSchema>,
3575        inputs: Vec<Arc<LogicalPlan>>,
3576    ) -> Result<Vec<Arc<LogicalPlan>>> {
3577        let schema_width = schema.iter().count();
3578        let mut wrapped_inputs = Vec::with_capacity(inputs.len());
3579        for input in inputs {
3580            // Any columns that exist within the derived schema but do not exist
3581            // within an input's schema should be replaced with `NULL` aliased
3582            // to the appropriate column in the derived schema.
3583            let mut expr = Vec::with_capacity(schema_width);
3584            for column in schema.columns() {
3585                if input
3586                    .schema()
3587                    .has_column_with_unqualified_name(column.name())
3588                {
3589                    expr.push(Expr::Column(column));
3590                } else {
3591                    expr.push(
3592                        Expr::Literal(ScalarValue::Null, None).alias(column.name()),
3593                    );
3594                }
3595            }
3596            wrapped_inputs.push(Arc::new(LogicalPlan::Projection(
3597                Projection::try_new_with_schema(expr, input, Arc::clone(schema))?,
3598            )));
3599        }
3600
3601        Ok(wrapped_inputs)
3602    }
3603
3604    /// Constructs new Union instance deriving schema from inputs.
3605    ///
3606    /// If `loose_types` is true, infers common types where possible without
3607    /// inserting casts. Otherwise, input types must match exactly.
3608    ///
3609    /// If `by_name` is `true`, input schemas need not be the same width. That is,
3610    /// the constructed schema follows `UNION BY NAME` semantics.
3611    fn derive_schema_from_inputs(
3612        inputs: &[Arc<LogicalPlan>],
3613        loose_types: bool,
3614        by_name: bool,
3615    ) -> Result<DFSchemaRef> {
3616        if inputs.len() < 2 {
3617            return plan_err!("UNION requires at least two inputs");
3618        }
3619
3620        if by_name {
3621            Self::derive_schema_from_inputs_by_name(inputs, loose_types)
3622        } else {
3623            Self::derive_schema_from_inputs_by_position(inputs, loose_types)
3624        }
3625    }
3626
3627    fn derive_schema_from_inputs_by_name(
3628        inputs: &[Arc<LogicalPlan>],
3629        loose_types: bool,
3630    ) -> Result<DFSchemaRef> {
3631        let mut cols: Vec<(&str, Vec<Option<&Field>>)> = Vec::new();
3632        for (input_index, input) in inputs.iter().enumerate() {
3633            for field in input.schema().fields() {
3634                if let Some((_, fields)) =
3635                    cols.iter_mut().find(|(name, _)| name == field.name())
3636                {
3637                    fields[input_index] = Some(field.as_ref());
3638                } else {
3639                    let mut fields = vec![None; inputs.len()];
3640                    fields[input_index] = Some(field.as_ref());
3641                    cols.push((field.name(), fields));
3642                }
3643            }
3644        }
3645
3646        // The analyzer sees missing fields as NULL literals in the alignment
3647        // projections. Include them so both passes infer the same type.
3648        let null_field = Field::new("", DataType::Null, true);
3649        let union_fields = cols
3650            .into_iter()
3651            .map(|(name, fields)| {
3652                let first_type = fields
3653                    .iter()
3654                    .flatten()
3655                    .next()
3656                    .expect("column has at least one input field")
3657                    .data_type();
3658                let data_type = if loose_types {
3659                    coerce_union_type(
3660                        fields.iter().map(|field| field.unwrap_or(&null_field)),
3661                    )
3662                    .unwrap_or_else(|_| first_type.clone())
3663                } else {
3664                    if fields
3665                        .iter()
3666                        .flatten()
3667                        .any(|field| field.data_type() != first_type)
3668                    {
3669                        return plan_err!("Found different types for field {name}");
3670                    }
3671                    first_type.clone()
3672                };
3673                let nullable = fields
3674                    .iter()
3675                    .any(|field| field.is_none_or(|field| field.is_nullable()));
3676                let metadata = merge_metadata_for_union(
3677                    fields.iter().flatten().map(|field| field.metadata()),
3678                );
3679                Ok((
3680                    None,
3681                    Arc::new(
3682                        Field::new(name, data_type, nullable).with_metadata(metadata),
3683                    ),
3684                ))
3685            })
3686            .collect::<Result<Vec<(Option<TableReference>, _)>>>()?;
3687
3688        let union_schema_metadata = merge_metadata_for_union(
3689            inputs.iter().map(|input| input.schema().metadata()),
3690        );
3691
3692        // Functional Dependencies are not preserved after UNION operation
3693        let schema = DFSchema::new_with_metadata(union_fields, union_schema_metadata)?;
3694        let schema = Arc::new(schema);
3695
3696        Ok(schema)
3697    }
3698
3699    fn derive_schema_from_inputs_by_position(
3700        inputs: &[Arc<LogicalPlan>],
3701        loose_types: bool,
3702    ) -> Result<DFSchemaRef> {
3703        let first_schema = inputs[0].schema();
3704        let fields_count = first_schema.fields().len();
3705        for input in inputs.iter().skip(1) {
3706            if fields_count != input.schema().fields().len() {
3707                return plan_err!(
3708                    "UNION queries have different number of columns: \
3709                    left has {} columns whereas right has {} columns",
3710                    fields_count,
3711                    input.schema().fields().len()
3712                );
3713            }
3714        }
3715
3716        let mut name_counts: HashMap<String, usize> =
3717            HashMap::with_capacity(fields_count);
3718        let mut fields: Vec<&FieldRef> = Vec::with_capacity(inputs.len());
3719        let union_fields = (0..fields_count)
3720            .map(|i| {
3721                fields.clear();
3722                fields.extend(inputs.iter().map(|input| input.schema().field(i)));
3723                let first_field = fields[0];
3724                let base_name = first_field.name().to_string();
3725
3726                let data_type = if loose_types {
3727                    coerce_union_type(fields.iter().map(|field| field.as_ref()))
3728                        .unwrap_or_else(|_| first_field.data_type().clone())
3729                } else {
3730                    fields
3731                        .iter()
3732                        .skip(1)
3733                        .try_fold(first_field.data_type(), |acc, field| {
3734                            if acc != field.data_type() {
3735                                return plan_err!(
3736                                    "UNION field {i} have different type in inputs: \
3737                                    left has {} whereas right has {}",
3738                                    first_field.data_type(),
3739                                    field.data_type()
3740                                );
3741                            }
3742                            Ok(acc)
3743                        })?
3744                        .clone()
3745                };
3746                let nullable = fields.iter().any(|field| field.is_nullable());
3747
3748                // Generate unique field name
3749                let name = if let Some(count) = name_counts.get_mut(&base_name) {
3750                    *count += 1;
3751                    format!("{base_name}_{count}")
3752                } else {
3753                    name_counts.insert(base_name.clone(), 0);
3754                    base_name
3755                };
3756
3757                let mut field = Field::new(&name, data_type, nullable);
3758                let field_metadata =
3759                    merge_metadata_for_union(fields.iter().map(|field| field.metadata()));
3760                field.set_metadata(field_metadata);
3761                Ok((None, Arc::new(field)))
3762            })
3763            .collect::<Result<_>>()?;
3764        let union_schema_metadata = merge_metadata_for_union(
3765            inputs.iter().map(|input| input.schema().metadata()),
3766        );
3767
3768        // Functional Dependencies are not preserved after UNION operation
3769        let schema = DFSchema::new_with_metadata(union_fields, union_schema_metadata)?;
3770        let schema = Arc::new(schema);
3771
3772        Ok(schema)
3773    }
3774}
3775
3776// Manual implementation needed because of `schema` field. Comparison excludes this field.
3777impl PartialOrd for Union {
3778    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3779        self.inputs
3780            .partial_cmp(&other.inputs)
3781            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
3782            .filter(|cmp| *cmp != Ordering::Equal || self == other)
3783    }
3784}
3785
3786/// A `SHOW`-class SQL statement: `SHOW TABLES`, `SHOW COLUMNS`, `SHOW
3787/// FUNCTIONS`, `SHOW <variable>`, `SHOW CREATE TABLE`, and `DESCRIBE`.
3788///
3789/// # Example output (`DESCRIBE`):
3790///
3791/// ```sql
3792/// > describe traces;
3793/// +--------------------+-----------------------------+-------------+
3794/// | column_name        | data_type                   | is_nullable |
3795/// +--------------------+-----------------------------+-------------+
3796/// | attributes         | Utf8                        | YES         |
3797/// | duration_nano      | Int64                       | YES         |
3798/// | end_time_unix_nano | Int64                       | YES         |
3799/// | service.name       | Dictionary(Int32, Utf8)     | YES         |
3800/// | span.kind          | Utf8                        | YES         |
3801/// | span.name          | Utf8                        | YES         |
3802/// | span_id            | Dictionary(Int32, Utf8)     | YES         |
3803/// | time               | Timestamp(Nanosecond, None) | NO          |
3804/// | trace_id           | Dictionary(Int32, Utf8)     | YES         |
3805/// | otel.status_code   | Utf8                        | YES         |
3806/// | parent_span_id     | Utf8                        | YES         |
3807/// +--------------------+-----------------------------+-------------+
3808/// ```
3809#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3810pub struct Show {
3811    /// Which `SHOW`-class statement this is, and any parameters it carries
3812    pub kind: ShowKind,
3813    /// schema of the output produced by this statement
3814    pub output_schema: DFSchemaRef,
3815}
3816
3817/// The specific `SHOW`-class statement carried by a [`Show`] plan.
3818#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3819pub enum ShowKind {
3820    /// `DESCRIBE <query>`
3821    Describe {
3822        /// The schema to describe
3823        schema: Arc<Schema>,
3824    },
3825    /// `SHOW TABLES`
3826    Tables,
3827    /// `SHOW [FULL|EXTENDED] COLUMNS FROM <table>` and `DESCRIBE <table>`
3828    Columns {
3829        /// Table to describe
3830        table_ref: TableReference,
3831        /// How detailed the output should be
3832        detail: ColumnsDetail,
3833    },
3834    /// `SHOW CREATE TABLE <table>`
3835    CreateTable {
3836        /// Table to describe
3837        table_ref: TableReference,
3838    },
3839    /// `SHOW <variable>` / `SHOW ALL`
3840    Variables {
3841        /// The name of the variable to show, or `None` if all variables should be shown.
3842        name: Option<String>,
3843        /// Whether to include the `description` column (`SHOW ... VERBOSE`)
3844        verbose: bool,
3845    },
3846    /// `SHOW FUNCTIONS [LIKE <pattern>]`
3847    Functions {
3848        /// The `LIKE` pattern to filter function names by, if any
3849        filter: Option<String>,
3850    },
3851}
3852
3853// Manual implementation of `PartialOrd`, returning none since there are no comparable types in
3854// `Show`. This allows `LogicalPlan` to derive `PartialOrd`.
3855impl PartialOrd for Show {
3856    fn partial_cmp(&self, _other: &Self) -> Option<Ordering> {
3857        // There is no relevant comparison for schemas
3858        None
3859    }
3860}
3861
3862/// Options for EXPLAIN
3863#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3864pub struct ExplainOption {
3865    /// Include detailed debug info
3866    pub verbose: bool,
3867    /// Actually execute the plan and report metrics
3868    pub analyze: bool,
3869    /// Output syntax/format
3870    pub format: ExplainFormat,
3871    /// Statement-level override for `datafusion.explain.show_statistics`.
3872    /// `None` means "fall back to session config".
3873    pub show_statistics: Option<bool>,
3874    /// Statement-level override for `datafusion.explain.analyze_level`.
3875    /// `None` means "fall back to session config".
3876    pub analyze_level: Option<MetricType>,
3877    /// Statement-level override for `datafusion.explain.analyze_categories`.
3878    /// `None` means "fall back to session config".
3879    pub analyze_categories: Option<ExplainAnalyzeCategories>,
3880}
3881
3882impl Default for ExplainOption {
3883    fn default() -> Self {
3884        ExplainOption {
3885            verbose: false,
3886            analyze: false,
3887            format: ExplainFormat::Indent,
3888            show_statistics: None,
3889            analyze_level: None,
3890            analyze_categories: None,
3891        }
3892    }
3893}
3894
3895impl ExplainOption {
3896    /// Builder‐style setter for `verbose`
3897    pub fn with_verbose(mut self, verbose: bool) -> Self {
3898        self.verbose = verbose;
3899        self
3900    }
3901
3902    /// Builder‐style setter for `analyze`
3903    pub fn with_analyze(mut self, analyze: bool) -> Self {
3904        self.analyze = analyze;
3905        self
3906    }
3907
3908    /// Builder‐style setter for `format`
3909    pub fn with_format(mut self, format: ExplainFormat) -> Self {
3910        self.format = format;
3911        self
3912    }
3913
3914    /// Builder-style setter for a statement-level override of
3915    /// `datafusion.explain.show_statistics`.
3916    pub fn with_show_statistics(mut self, show_statistics: Option<bool>) -> Self {
3917        self.show_statistics = show_statistics;
3918        self
3919    }
3920
3921    /// Builder-style setter for a statement-level override of
3922    /// `datafusion.explain.analyze_level`.
3923    pub fn with_analyze_level(mut self, analyze_level: Option<MetricType>) -> Self {
3924        self.analyze_level = analyze_level;
3925        self
3926    }
3927
3928    /// Builder-style setter for a statement-level override of
3929    /// `datafusion.explain.analyze_categories`.
3930    pub fn with_analyze_categories(
3931        mut self,
3932        analyze_categories: Option<ExplainAnalyzeCategories>,
3933    ) -> Self {
3934        self.analyze_categories = analyze_categories;
3935        self
3936    }
3937}
3938
3939/// Produces a relation with string representations of
3940/// various parts of the plan
3941///
3942/// See [the documentation] for more information
3943///
3944/// [the documentation]: https://datafusion.apache.org/user-guide/sql/explain.html
3945#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3946pub struct Explain {
3947    /// Should extra (detailed, intermediate plans) be included?
3948    pub verbose: bool,
3949    /// Output format for explain, if specified.
3950    /// If none, defaults to `text`
3951    pub explain_format: ExplainFormat,
3952    /// The logical plan that is being EXPLAIN'd
3953    pub plan: Arc<LogicalPlan>,
3954    /// Represent the various stages plans have gone through
3955    pub stringified_plans: Vec<StringifiedPlan>,
3956    /// The output schema of the explain (2 columns of text)
3957    pub schema: DFSchemaRef,
3958    /// Used by physical planner to check if should proceed with planning
3959    pub logical_optimization_succeeded: bool,
3960    /// Statement-level override for `datafusion.explain.show_statistics`.
3961    /// When `None`, the session-config value is used.
3962    pub show_statistics: Option<bool>,
3963}
3964
3965// Manual implementation needed because of `schema` field. Comparison excludes this field.
3966impl PartialOrd for Explain {
3967    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3968        #[derive(PartialEq, PartialOrd)]
3969        struct ComparableExplain<'a> {
3970            /// Should extra (detailed, intermediate plans) be included?
3971            pub verbose: &'a bool,
3972            /// The logical plan that is being EXPLAIN'd
3973            pub plan: &'a Arc<LogicalPlan>,
3974            /// Represent the various stages plans have gone through
3975            pub stringified_plans: &'a Vec<StringifiedPlan>,
3976            /// Used by physical planner to check if should proceed with planning
3977            pub logical_optimization_succeeded: &'a bool,
3978            /// Statement-level override for show_statistics
3979            pub show_statistics: &'a Option<bool>,
3980        }
3981        let comparable_self = ComparableExplain {
3982            verbose: &self.verbose,
3983            plan: &self.plan,
3984            stringified_plans: &self.stringified_plans,
3985            logical_optimization_succeeded: &self.logical_optimization_succeeded,
3986            show_statistics: &self.show_statistics,
3987        };
3988        let comparable_other = ComparableExplain {
3989            verbose: &other.verbose,
3990            plan: &other.plan,
3991            stringified_plans: &other.stringified_plans,
3992            logical_optimization_succeeded: &other.logical_optimization_succeeded,
3993            show_statistics: &other.show_statistics,
3994        };
3995        comparable_self
3996            .partial_cmp(&comparable_other)
3997            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
3998            .filter(|cmp| *cmp != Ordering::Equal || self == other)
3999    }
4000}
4001
4002/// Runs the actual plan, and then prints the physical plan with
4003/// with execution metrics.
4004#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4005pub struct Analyze {
4006    /// Should extra detail be included?
4007    pub verbose: bool,
4008    /// Output syntax/format for the rendered physical plan + metrics.
4009    pub format: ExplainFormat,
4010    /// The logical plan that is being EXPLAIN ANALYZE'd
4011    pub input: Arc<LogicalPlan>,
4012    /// The output schema of the explain (2 columns of text)
4013    pub schema: DFSchemaRef,
4014    /// Statement-level override for `datafusion.explain.analyze_level`.
4015    /// When `None`, the session-config value is used.
4016    pub analyze_level: Option<MetricType>,
4017    /// Statement-level override for `datafusion.explain.analyze_categories`.
4018    /// When `None`, the session-config value is used.
4019    pub analyze_categories: Option<ExplainAnalyzeCategories>,
4020}
4021
4022// Manual implementation needed because of `schema` field and the lack of
4023// `PartialOrd` on `MetricType` / `ExplainAnalyzeCategories`. Ordering is
4024// defined over `(verbose, input)` and then falls back to `==` for the
4025// remaining statement-level override fields.
4026impl PartialOrd for Analyze {
4027    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4028        match self.verbose.partial_cmp(&other.verbose) {
4029            Some(Ordering::Equal) => self.input.partial_cmp(&other.input),
4030            cmp => cmp,
4031        }
4032        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
4033        .filter(|cmp| *cmp != Ordering::Equal || self == other)
4034    }
4035}
4036
4037/// Extension operator defined outside of DataFusion
4038// TODO(clippy): This clippy `allow` should be removed if
4039// the manual `PartialEq` is removed in favor of a derive.
4040// (see `PartialEq` the impl for details.)
4041#[allow(clippy::allow_attributes)]
4042#[allow(clippy::derived_hash_with_manual_eq)]
4043#[derive(Debug, Clone, Eq, Hash)]
4044pub struct Extension {
4045    /// The runtime extension operator
4046    pub node: Arc<dyn UserDefinedLogicalNode>,
4047}
4048
4049// `PartialEq` cannot be derived for types containing `Arc<dyn Trait>`.
4050// This manual implementation should be removed if
4051// https://github.com/rust-lang/rust/issues/39128 is fixed.
4052impl PartialEq for Extension {
4053    fn eq(&self, other: &Self) -> bool {
4054        self.node.eq(&other.node)
4055    }
4056}
4057
4058impl PartialOrd for Extension {
4059    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4060        self.node.partial_cmp(&other.node)
4061    }
4062}
4063
4064/// Produces the first `n` tuples from its input and discards the rest.
4065#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
4066pub struct Limit {
4067    /// Number of rows to skip before fetch
4068    pub skip: Option<Box<Expr>>,
4069    /// Maximum number of rows to fetch,
4070    /// None means fetching all rows
4071    pub fetch: Option<Box<Expr>>,
4072    /// The logical plan
4073    pub input: Arc<LogicalPlan>,
4074}
4075
4076/// Different types of skip expression in Limit plan.
4077pub enum SkipType {
4078    /// The skip expression is a literal value.
4079    Literal(usize),
4080    /// Currently only supports expressions that can be folded into constants.
4081    UnsupportedExpr,
4082}
4083
4084/// Different types of fetch expression in Limit plan.
4085pub enum FetchType {
4086    /// The fetch expression is a literal value.
4087    /// `Literal(None)` means the fetch expression is not provided.
4088    Literal(Option<usize>),
4089    /// Currently only supports expressions that can be folded into constants.
4090    UnsupportedExpr,
4091}
4092
4093impl Limit {
4094    /// Get the skip type from the limit plan.
4095    pub fn get_skip_type(&self) -> Result<SkipType> {
4096        match self.skip.as_deref() {
4097            Some(expr) => match *expr {
4098                Expr::Literal(ScalarValue::Int64(s), _) => {
4099                    // `skip = NULL` is equivalent to `skip = 0`
4100                    let s = s.unwrap_or(0);
4101                    if s >= 0 {
4102                        let s = usize::try_from(s).map_err(|_| {
4103                            plan_datafusion_err!(
4104                                "OFFSET value {s} cannot be represented as usize"
4105                            )
4106                        })?;
4107                        Ok(SkipType::Literal(s))
4108                    } else {
4109                        plan_err!("OFFSET must be >=0, '{}' was provided", s)
4110                    }
4111                }
4112                _ => Ok(SkipType::UnsupportedExpr),
4113            },
4114            // `skip = None` is equivalent to `skip = 0`
4115            None => Ok(SkipType::Literal(0)),
4116        }
4117    }
4118
4119    /// Get the fetch type from the limit plan.
4120    pub fn get_fetch_type(&self) -> Result<FetchType> {
4121        match self.fetch.as_deref() {
4122            Some(expr) => match *expr {
4123                Expr::Literal(ScalarValue::Int64(Some(s)), _) => {
4124                    if s >= 0 {
4125                        let s = usize::try_from(s).map_err(|_| {
4126                            plan_datafusion_err!(
4127                                "LIMIT value {s} cannot be represented as usize"
4128                            )
4129                        })?;
4130                        Ok(FetchType::Literal(Some(s)))
4131                    } else {
4132                        plan_err!("LIMIT must be >= 0, '{}' was provided", s)
4133                    }
4134                }
4135                Expr::Literal(ScalarValue::Int64(None), _) => {
4136                    Ok(FetchType::Literal(None))
4137                }
4138                _ => Ok(FetchType::UnsupportedExpr),
4139            },
4140            None => Ok(FetchType::Literal(None)),
4141        }
4142    }
4143}
4144
4145/// Removes duplicate rows from the input
4146#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
4147pub enum Distinct {
4148    /// Plain `DISTINCT` referencing all selection expressions
4149    All(Arc<LogicalPlan>),
4150    /// The `Postgres` addition, allowing separate control over DISTINCT'd and selected columns
4151    On(DistinctOn),
4152}
4153
4154impl Distinct {
4155    /// return a reference to the nodes input
4156    pub fn input(&self) -> &Arc<LogicalPlan> {
4157        match self {
4158            Distinct::All(input) => input,
4159            Distinct::On(DistinctOn { input, .. }) => input,
4160        }
4161    }
4162}
4163
4164/// Removes duplicate rows from the input
4165#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4166pub struct DistinctOn {
4167    /// The `DISTINCT ON` clause expression list
4168    pub on_expr: Vec<Expr>,
4169    /// The selected projection expression list
4170    pub select_expr: Vec<Expr>,
4171    /// The `ORDER BY` clause, whose initial expressions must match those of the `ON` clause when
4172    /// present. Note that those matching expressions actually wrap the `ON` expressions with
4173    /// additional info pertaining to the sorting procedure (i.e. ASC/DESC, and NULLS FIRST/LAST).
4174    pub sort_expr: Option<Vec<SortExpr>>,
4175    /// The logical plan that is being DISTINCT'd
4176    pub input: Arc<LogicalPlan>,
4177    /// The schema description of the DISTINCT ON output
4178    pub schema: DFSchemaRef,
4179}
4180
4181impl DistinctOn {
4182    /// Create a new `DistinctOn` struct.
4183    pub fn try_new(
4184        on_expr: Vec<Expr>,
4185        select_expr: Vec<Expr>,
4186        sort_expr: Option<Vec<SortExpr>>,
4187        input: Arc<LogicalPlan>,
4188    ) -> Result<Self> {
4189        if on_expr.is_empty() {
4190            return plan_err!("No `ON` expressions provided");
4191        }
4192
4193        let on_expr = normalize_cols(on_expr, input.as_ref())?;
4194        let qualified_fields = exprlist_to_fields(select_expr.as_slice(), &input)?
4195            .into_iter()
4196            .collect();
4197
4198        let dfschema = DFSchema::new_with_metadata(
4199            qualified_fields,
4200            input.schema().metadata().clone(),
4201        )?;
4202
4203        let mut distinct_on = DistinctOn {
4204            on_expr,
4205            select_expr,
4206            sort_expr: None,
4207            input,
4208            schema: Arc::new(dfschema),
4209        };
4210
4211        if let Some(sort_expr) = sort_expr {
4212            distinct_on = distinct_on.with_sort_expr(sort_expr)?;
4213        }
4214
4215        Ok(distinct_on)
4216    }
4217
4218    /// Try to update `self` with a new sort expressions.
4219    ///
4220    /// Validates that the sort expressions are a super-set of the `ON` expressions.
4221    pub fn with_sort_expr(mut self, sort_expr: Vec<SortExpr>) -> Result<Self> {
4222        let sort_expr = normalize_sorts(sort_expr, self.input.as_ref())?;
4223
4224        // Check that the left-most sort expressions are the same as the `ON` expressions.
4225        let mut matched = true;
4226        for (on, sort) in self.on_expr.iter().zip(sort_expr.iter()) {
4227            if on != &sort.expr {
4228                matched = false;
4229                break;
4230            }
4231        }
4232
4233        if self.on_expr.len() > sort_expr.len() || !matched {
4234            return plan_err!(
4235                "SELECT DISTINCT ON expressions must match initial ORDER BY expressions"
4236            );
4237        }
4238
4239        self.sort_expr = Some(sort_expr);
4240        Ok(self)
4241    }
4242}
4243
4244// Manual implementation needed because of `schema` field. Comparison excludes this field.
4245impl PartialOrd for DistinctOn {
4246    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4247        #[derive(PartialEq, PartialOrd)]
4248        struct ComparableDistinctOn<'a> {
4249            /// The `DISTINCT ON` clause expression list
4250            pub on_expr: &'a Vec<Expr>,
4251            /// The selected projection expression list
4252            pub select_expr: &'a Vec<Expr>,
4253            /// The `ORDER BY` clause, whose initial expressions must match those of the `ON` clause when
4254            /// present. Note that those matching expressions actually wrap the `ON` expressions with
4255            /// additional info pertaining to the sorting procedure (i.e. ASC/DESC, and NULLS FIRST/LAST).
4256            pub sort_expr: &'a Option<Vec<SortExpr>>,
4257            /// The logical plan that is being DISTINCT'd
4258            pub input: &'a Arc<LogicalPlan>,
4259        }
4260        let comparable_self = ComparableDistinctOn {
4261            on_expr: &self.on_expr,
4262            select_expr: &self.select_expr,
4263            sort_expr: &self.sort_expr,
4264            input: &self.input,
4265        };
4266        let comparable_other = ComparableDistinctOn {
4267            on_expr: &other.on_expr,
4268            select_expr: &other.select_expr,
4269            sort_expr: &other.sort_expr,
4270            input: &other.input,
4271        };
4272        comparable_self
4273            .partial_cmp(&comparable_other)
4274            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
4275            .filter(|cmp| *cmp != Ordering::Equal || self == other)
4276    }
4277}
4278
4279/// Aggregates its input based on a set of grouping and aggregate
4280/// expressions (e.g. SUM).
4281///
4282/// # Output Schema
4283///
4284/// The output schema is the group expressions followed by the aggregate
4285/// expressions in order.
4286///
4287/// For example, given the input schema `"A", "B", "C"` and the aggregate
4288/// `SUM(A) GROUP BY C+B`, the output schema will be `"C+B", "SUM(A)"` where
4289/// "C+B" and "SUM(A)" are the names of the output columns. Note that "C+B" is a
4290/// single new column
4291#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4292// mark non_exhaustive to encourage use of try_new/new()
4293#[non_exhaustive]
4294pub struct Aggregate {
4295    /// The incoming logical plan
4296    pub input: Arc<LogicalPlan>,
4297    /// Grouping expressions
4298    pub group_expr: Vec<Expr>,
4299    /// Aggregate expressions.
4300    ///
4301    /// Note these *must* be either [`Expr::AggregateFunction`] or [`Expr::Alias`]
4302    pub aggr_expr: Vec<Expr>,
4303    /// The schema description of the aggregate output
4304    pub schema: DFSchemaRef,
4305}
4306
4307impl Aggregate {
4308    /// Create a new aggregate operator.
4309    pub fn try_new(
4310        input: Arc<LogicalPlan>,
4311        group_expr: Vec<Expr>,
4312        aggr_expr: Vec<Expr>,
4313    ) -> Result<Self> {
4314        // Reject e.g. `sum(sum(x))` here rather than letting it reach physical
4315        // planning, which has no equivalent for a nested aggregate.
4316        check_aggregate_and_window_nesting(group_expr.iter().chain(aggr_expr.iter()))?;
4317
4318        let group_expr = enumerate_grouping_sets(group_expr)?;
4319
4320        let is_grouping_set = matches!(group_expr.as_slice(), [Expr::GroupingSet(_)]);
4321
4322        let grouping_expr: Vec<&Expr> = grouping_set_to_exprlist(group_expr.as_slice())?;
4323
4324        let mut qualified_fields = exprlist_to_fields(grouping_expr, &input)?;
4325
4326        // Even columns that cannot be null will become nullable when used in a grouping set.
4327        if is_grouping_set {
4328            qualified_fields = qualified_fields
4329                .into_iter()
4330                .map(|(q, f)| (q, f.as_ref().clone().with_nullable(true).into()))
4331                .collect::<Vec<_>>();
4332            let max_ordinal = max_grouping_set_duplicate_ordinal(&group_expr);
4333            qualified_fields.push((
4334                None,
4335                Field::new(
4336                    Self::INTERNAL_GROUPING_ID,
4337                    Self::grouping_id_type(qualified_fields.len(), max_ordinal),
4338                    false,
4339                )
4340                .into(),
4341            ));
4342        }
4343
4344        qualified_fields.extend(exprlist_to_fields(aggr_expr.as_slice(), &input)?);
4345
4346        let schema = DFSchema::new_with_metadata(
4347            qualified_fields,
4348            input.schema().metadata().clone(),
4349        )?;
4350
4351        Self::try_new_with_schema(input, group_expr, aggr_expr, Arc::new(schema))
4352    }
4353
4354    /// Create a new aggregate operator using the provided schema to avoid the overhead of
4355    /// building the schema again when the schema is already known.
4356    ///
4357    /// This method should only be called when you are absolutely sure that the schema being
4358    /// provided is correct for the aggregate. If in doubt, call [try_new](Self::try_new) instead.
4359    pub fn try_new_with_schema(
4360        input: Arc<LogicalPlan>,
4361        group_expr: Vec<Expr>,
4362        aggr_expr: Vec<Expr>,
4363        schema: DFSchemaRef,
4364    ) -> Result<Self> {
4365        if group_expr.is_empty() && aggr_expr.is_empty() {
4366            return plan_err!(
4367                "Aggregate requires at least one grouping or aggregate expression. \
4368                Aggregate without grouping expressions nor aggregate expressions is \
4369                logically equivalent to, but less efficient than, VALUES producing \
4370                single row. Please use VALUES instead."
4371            );
4372        }
4373        let group_expr_count = grouping_set_expr_count(&group_expr)?;
4374        if schema.fields().len() != group_expr_count + aggr_expr.len() {
4375            return plan_err!(
4376                "Aggregate schema has wrong number of fields. Expected {} got {}",
4377                group_expr_count + aggr_expr.len(),
4378                schema.fields().len()
4379            );
4380        }
4381
4382        let aggregate_func_dependencies =
4383            calc_func_dependencies_for_aggregate(&group_expr, &input, &schema)?;
4384        let new_schema = Arc::unwrap_or_clone(schema);
4385        let schema = Arc::new(
4386            new_schema.with_functional_dependencies(aggregate_func_dependencies)?,
4387        );
4388        Ok(Self {
4389            input,
4390            group_expr,
4391            aggr_expr,
4392            schema,
4393        })
4394    }
4395
4396    fn is_grouping_set(&self) -> bool {
4397        matches!(self.group_expr.as_slice(), [Expr::GroupingSet(_)])
4398    }
4399
4400    /// Get the output expressions.
4401    fn output_expressions(&self) -> Result<Vec<&Expr>> {
4402        static INTERNAL_ID_EXPR: LazyLock<Expr> = LazyLock::new(|| {
4403            Expr::Column(Column::from_name(Aggregate::INTERNAL_GROUPING_ID))
4404        });
4405        let mut exprs = grouping_set_to_exprlist(self.group_expr.as_slice())?;
4406        if self.is_grouping_set() {
4407            exprs.push(&INTERNAL_ID_EXPR);
4408        }
4409        exprs.extend(self.aggr_expr.iter());
4410        debug_assert_eq!(exprs.len(), self.schema.fields().len());
4411        Ok(exprs)
4412    }
4413
4414    /// Get the length of the group by expression in the output schema
4415    /// This is not simply group by expression length. Expression may be
4416    /// GroupingSet, etc. In these case we need to get inner expression lengths.
4417    pub fn group_expr_len(&self) -> Result<usize> {
4418        grouping_set_expr_count(&self.group_expr)
4419    }
4420
4421    /// Returns the data type of the grouping id.
4422    ///
4423    /// The grouping ID packs two pieces of information into a single integer:
4424    /// - The low `group_exprs` bits are the semantic bitmask (a set bit means the
4425    ///   corresponding grouping expression is NULL for this grouping set).
4426    /// - The bits above position `group_exprs` encode a duplicate ordinal that
4427    ///   distinguishes multiple occurrences of the same grouping set pattern.
4428    ///
4429    /// `max_ordinal` is the highest ordinal value that will appear (0 when there
4430    /// are no duplicate grouping sets).  The type is chosen to be the smallest
4431    /// unsigned integer that can represent both parts.
4432    pub fn grouping_id_type(group_exprs: usize, max_ordinal: usize) -> DataType {
4433        let ordinal_bits = usize::BITS as usize - max_ordinal.leading_zeros() as usize;
4434        let total_bits = group_exprs + ordinal_bits;
4435        if total_bits <= 8 {
4436            DataType::UInt8
4437        } else if total_bits <= 16 {
4438            DataType::UInt16
4439        } else if total_bits <= 32 {
4440            DataType::UInt32
4441        } else {
4442            DataType::UInt64
4443        }
4444    }
4445
4446    /// Internal column used when the aggregation is a grouping set.
4447    ///
4448    /// This column packs two values into a single unsigned integer:
4449    ///
4450    /// - **Low bits (positions 0 .. n-1)**: a semantic bitmask where each bit
4451    ///   represents one of the `n` grouping expressions.  The least significant
4452    ///   bit corresponds to the rightmost grouping expression.  A `1` bit means
4453    ///   the corresponding column is replaced with `NULL` for this grouping set;
4454    ///   a `0` bit means it is included.
4455    /// - **High bits (positions n and above)**: a *duplicate ordinal* that
4456    ///   distinguishes multiple occurrences of the same semantic grouping set
4457    ///   pattern within a single query.  The ordinal is `0` for the first
4458    ///   occurrence, `1` for the second, and so on.
4459    ///
4460    /// The integer type is chosen by [`Self::grouping_id_type`] to be the
4461    /// smallest `UInt8 / UInt16 / UInt32 / UInt64` that can represent both
4462    /// parts.
4463    ///
4464    /// For example, for the grouping expressions CUBE(a, b) (no duplicates),
4465    /// the grouping ID column will have the following values:
4466    ///     0b00: Both `a` and `b` are included
4467    ///     0b01: `b` is excluded
4468    ///     0b10: `a` is excluded
4469    ///     0b11: Both `a` and `b` are excluded
4470    ///
4471    /// When the same set appears twice and `n = 2`, the duplicate ordinal is
4472    /// packed into bit 2:
4473    ///     first occurrence:  `0b0_01` (ordinal = 0, mask = 0b01)
4474    ///     second occurrence: `0b1_01` (ordinal = 1, mask = 0b01)
4475    ///
4476    /// The GROUPING function always masks the value with `(1 << n) - 1` before
4477    /// interpreting it so the ordinal bits are invisible to user-facing SQL.
4478    pub const INTERNAL_GROUPING_ID: &'static str = "__grouping_id";
4479}
4480
4481// Manual implementation needed because of `schema` field. Comparison excludes this field.
4482impl PartialOrd for Aggregate {
4483    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4484        match self.input.partial_cmp(&other.input) {
4485            Some(Ordering::Equal) => {
4486                match self.group_expr.partial_cmp(&other.group_expr) {
4487                    Some(Ordering::Equal) => self.aggr_expr.partial_cmp(&other.aggr_expr),
4488                    cmp => cmp,
4489                }
4490            }
4491            cmp => cmp,
4492        }
4493        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
4494        .filter(|cmp| *cmp != Ordering::Equal || self == other)
4495    }
4496}
4497
4498/// Returns the highest duplicate ordinal across all grouping sets in `group_expr`.
4499///
4500/// The ordinal for each occurrence of a grouping set pattern is its 0-based
4501/// index among identical entries. For example, if the same set appears three
4502/// times, the ordinals are 0, 1, 2 and this function returns 2.
4503/// Returns 0 when no grouping set is duplicated.
4504#[allow(clippy::allow_attributes, clippy::mutable_key_type)] // Expr contains Arc with interior mutability but is intentionally used as hash key
4505fn max_grouping_set_duplicate_ordinal(group_expr: &[Expr]) -> usize {
4506    if let Some(Expr::GroupingSet(GroupingSet::GroupingSets(sets))) = group_expr.first() {
4507        let mut counts: HashMap<&[Expr], usize> = HashMap::with_capacity(sets.len());
4508        for set in sets {
4509            *counts.entry(set).or_insert(0) += 1;
4510        }
4511        counts.into_values().max().unwrap_or(0).saturating_sub(1)
4512    } else {
4513        0
4514    }
4515}
4516
4517/// Checks whether any expression in `group_expr` contains `Expr::GroupingSet`.
4518fn contains_grouping_set(group_expr: &[Expr]) -> bool {
4519    group_expr
4520        .iter()
4521        .any(|expr| matches!(expr, Expr::GroupingSet(_)))
4522}
4523
4524/// Calculates functional dependencies for aggregate expressions.
4525fn calc_func_dependencies_for_aggregate(
4526    // Expressions in the GROUP BY clause:
4527    group_expr: &[Expr],
4528    // Input plan of the aggregate:
4529    input: &LogicalPlan,
4530    // Aggregate schema
4531    aggr_schema: &DFSchema,
4532) -> Result<FunctionalDependencies> {
4533    // We can do a case analysis on how to propagate functional dependencies based on
4534    // whether the GROUP BY in question contains a grouping set expression:
4535    // - If so, the functional dependencies will be empty because we cannot guarantee
4536    //   that GROUP BY expression results will be unique.
4537    // - Otherwise, it may be possible to propagate functional dependencies.
4538    if !contains_grouping_set(group_expr) {
4539        // One entry per GROUP BY output field, in the order of `aggr_schema`
4540        let group_by_input_indices = grouping_set_to_exprlist(group_expr)?
4541            .into_iter()
4542            .map(|item| passthrough_field_index(item, input.schema()))
4543            .collect::<Vec<_>>();
4544        let aggregate_func_dependencies = aggregate_functional_dependencies(
4545            input.schema(),
4546            &group_by_input_indices,
4547            aggr_schema,
4548        );
4549        Ok(aggregate_func_dependencies)
4550    } else {
4551        Ok(FunctionalDependencies::empty())
4552    }
4553}
4554
4555/// This function projects functional dependencies of the `input` plan according
4556/// to projection expressions `exprs`.
4557fn calc_func_dependencies_for_project(
4558    exprs: &[Expr],
4559    input: &LogicalPlan,
4560) -> Result<FunctionalDependencies> {
4561    // Sentinel for projection outputs that do not map back to any input field.
4562    const COMPUTED_EXPR_INDEX: usize = usize::MAX;
4563
4564    let input_func_dependencies = input.schema().functional_dependencies();
4565    // Projecting an empty set of dependencies always yields an empty set, so
4566    // skip resolving projection expressions against the input fields. This is
4567    // the common case because table sources carry no constraints by default.
4568    if input_func_dependencies.is_empty() {
4569        return Ok(FunctionalDependencies::empty());
4570    }
4571
4572    let input_schema = input.schema();
4573    let input_index = |expr: &Expr| {
4574        passthrough_field_index(expr, input_schema).unwrap_or(COMPUTED_EXPR_INDEX)
4575    };
4576
4577    // Map each projection output position to its input column index.
4578    // A projection expression can produce multiple output columns, such as `*`.
4579    let proj_indices = exprs
4580        .iter()
4581        .map(|expr| match expr {
4582            #[expect(deprecated)]
4583            Expr::Wildcard { qualifier, options } => {
4584                let wildcard_fields = exprlist_to_fields(
4585                    vec![&Expr::Wildcard {
4586                        qualifier: qualifier.clone(),
4587                        options: options.clone(),
4588                    }],
4589                    input,
4590                )?;
4591                Ok::<_, DataFusionError>(
4592                    wildcard_fields
4593                        .into_iter()
4594                        .map(|(qualifier, f)| {
4595                            input_schema
4596                                .index_of_column_by_name(qualifier.as_ref(), f.name())
4597                                .unwrap_or(COMPUTED_EXPR_INDEX)
4598                        })
4599                        .collect::<Vec<_>>(),
4600                )
4601            }
4602            _ => Ok(vec![input_index(expr)]),
4603        })
4604        .collect::<Result<Vec<_>>>()?
4605        .into_iter()
4606        .flatten()
4607        .collect::<Vec<_>>();
4608
4609    Ok(input_func_dependencies
4610        .project_functional_dependencies(&proj_indices, exprs.len()))
4611}
4612
4613/// Sorts its input according to a list of sort expressions.
4614#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
4615pub struct Sort {
4616    /// The sort expressions
4617    pub expr: Vec<SortExpr>,
4618    /// The incoming logical plan
4619    pub input: Arc<LogicalPlan>,
4620    /// Optional fetch limit
4621    pub fetch: Option<usize>,
4622}
4623
4624/// Join two logical plans on one or more join columns
4625#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4626pub struct Join {
4627    /// Left input
4628    pub left: Arc<LogicalPlan>,
4629    /// Right input
4630    pub right: Arc<LogicalPlan>,
4631    /// Equijoin clause expressed as pairs of (left, right) join expressions
4632    pub on: Vec<(Expr, Expr)>,
4633    /// Filters applied during join (non-equi conditions)
4634    pub filter: Option<Expr>,
4635    /// Join type
4636    pub join_type: JoinType,
4637    /// Join constraint
4638    pub join_constraint: JoinConstraint,
4639    /// The output schema, containing fields from the left and right inputs
4640    pub schema: DFSchemaRef,
4641    /// Defines the null equality for the join.
4642    pub null_equality: NullEquality,
4643    /// Whether this join needs null-aware NOT IN semantics.
4644    ///
4645    /// For `LeftAnti`, if the right side contains any NULL in join keys, no rows are output and
4646    /// left rows with NULL join keys are also excluded.
4647    ///
4648    /// For `LeftMark`, the generated `mark` column becomes nullable so unmatched rows can produce
4649    /// `NULL` rather than `false` when SQL three-valued logic requires it.
4650    pub null_aware: bool,
4651    /// Number of `NOT IN` value keys of a null-aware join; ignored unless
4652    /// [`Self::null_aware`] is set.
4653    ///
4654    /// A scalar `x NOT IN (SELECT y ...)` has one value key, a multi-column
4655    /// `(a, b) NOT IN (SELECT x, y ...)` one per tuple element. The value keys
4656    /// are the leading equi-join keys (`on[..n]`, or the leading equality
4657    /// conjuncts of `filter` before they are extracted into `on`); any keys
4658    /// after them are correlation scope keys of a correlated subquery. A NULL
4659    /// in a value key follows SQL three-valued logic across the whole tuple,
4660    /// while the scope keys only select which subquery rows are compared.
4661    ///
4662    /// `0` leaves the count unset, which is the default of [`Self::try_new`]
4663    /// and the `LogicalPlanBuilder` join methods. Physical planning accepts an
4664    /// unset count only for a single-key join, a scalar `NOT IN`, and rejects
4665    /// it for more keys: no default can tell which of them are value keys.
4666    pub null_aware_value_keys: usize,
4667}
4668
4669/// The ordered comparison used by an [`AsOfJoin`].
4670#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
4671pub struct AsOfMatch {
4672    /// Expression evaluated against the left input.
4673    pub left: Expr,
4674    /// One of [`Operator::Lt`], [`Operator::LtEq`], [`Operator::Gt`], or
4675    /// [`Operator::GtEq`].
4676    pub op: Operator,
4677    /// Expression evaluated against the right input.
4678    pub right: Expr,
4679}
4680
4681impl AsOfMatch {
4682    /// Creates an ordered ASOF match condition.
4683    pub fn new(left: Expr, op: Operator, right: Expr) -> Self {
4684        Self { left, op, right }
4685    }
4686}
4687
4688impl TryFrom<Expr> for AsOfMatch {
4689    type Error = DataFusionError;
4690
4691    fn try_from(condition: Expr) -> Result<Self> {
4692        let Expr::BinaryExpr(BinaryExpr { left, op, right }) = condition else {
4693            return plan_err!("ASOF MATCH_CONDITION must be a single comparison");
4694        };
4695        if !matches!(
4696            op,
4697            Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq
4698        ) {
4699            return plan_err!(
4700                "ASOF MATCH_CONDITION requires <, <=, >, or >=, found {op}"
4701            );
4702        }
4703        Ok(Self::new(*left, op, *right))
4704    }
4705}
4706
4707impl Display for AsOfMatch {
4708    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
4709        write!(f, "{} {} {}", self.left, self.op, self.right)
4710    }
4711}
4712
4713/// Match each left row with at most one ordered row from the right input.
4714#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4715pub struct AsOfJoin {
4716    /// Left input. Every left row is preserved exactly once.
4717    pub left: Arc<LogicalPlan>,
4718    /// Right input.
4719    pub right: Arc<LogicalPlan>,
4720    /// Equality clauses expressed as pairs of left and right expressions.
4721    pub on: Vec<(Expr, Expr)>,
4722    /// Ordered match condition.
4723    pub match_condition: Box<AsOfMatch>,
4724    /// Whether equality keys came from `ON` or `USING`.
4725    pub join_constraint: JoinConstraint,
4726    /// Output schema.
4727    pub schema: DFSchemaRef,
4728}
4729
4730impl AsOfJoin {
4731    /// Creates an ASOF join and validates its logical contract.
4732    ///
4733    /// This is the pre-coercion boundary. The physical ASOF constructor repeats
4734    /// the shared operator, side-ownership, and determinism checks for direct
4735    /// physical-plan callers and adds execution-only constraints. Keep the
4736    /// shared checks aligned across both entry points.
4737    pub fn try_new(
4738        left: Arc<LogicalPlan>,
4739        right: Arc<LogicalPlan>,
4740        on: Vec<(Expr, Expr)>,
4741        match_condition: AsOfMatch,
4742        join_constraint: JoinConstraint,
4743    ) -> Result<Self> {
4744        if !matches!(
4745            match_condition.op,
4746            Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq
4747        ) {
4748            return plan_err!(
4749                "ASOF MATCH_CONDITION requires <, <=, >, or >=, found {}",
4750                match_condition.op
4751            );
4752        }
4753
4754        Self::validate_side(&match_condition.left, left.schema(), "left match")?;
4755        Self::validate_side(&match_condition.right, right.schema(), "right match")?;
4756        if match_condition.left.is_volatile() || match_condition.right.is_volatile() {
4757            return plan_err!("ASOF MATCH_CONDITION must be deterministic");
4758        }
4759
4760        let left_type = match_condition.left.get_type(left.schema())?;
4761        let right_type = match_condition.right.get_type(right.schema())?;
4762        if crate::type_coercion::binary::comparison_coercion(&left_type, &right_type)
4763            .is_none()
4764        {
4765            return plan_err!(
4766                "ASOF match expressions have incompatible types {left_type} and {right_type}"
4767            );
4768        }
4769
4770        for (left_expr, right_expr) in &on {
4771            Self::validate_side(left_expr, left.schema(), "left equality")?;
4772            Self::validate_side(right_expr, right.schema(), "right equality")?;
4773            if left_expr.is_volatile() || right_expr.is_volatile() {
4774                return plan_err!("ASOF equality expressions must be deterministic");
4775            }
4776            let left_type = left_expr.get_type(left.schema())?;
4777            let right_type = right_expr.get_type(right.schema())?;
4778            let Some(common_type) = crate::type_coercion::binary::comparison_coercion(
4779                &left_type,
4780                &right_type,
4781            ) else {
4782                return plan_err!(
4783                    "ASOF equality expressions have incompatible types {left_type} and {right_type}"
4784                );
4785            };
4786            if !crate::utils::can_hash(&common_type) {
4787                return plan_err!(
4788                    "ASOF equality expressions have unsupported hash type {common_type}"
4789                );
4790            }
4791        }
4792
4793        if join_constraint == JoinConstraint::Using
4794            && on.iter().any(|(left, right)| {
4795                left.get_as_join_column().is_none()
4796                    || right.get_as_join_column().is_none()
4797            })
4798        {
4799            return plan_err!("ASOF USING keys must be columns");
4800        }
4801
4802        let schema = build_asof_join_schema(left.schema(), right.schema())?;
4803        Ok(Self {
4804            left,
4805            right,
4806            on,
4807            match_condition: Box::new(match_condition),
4808            join_constraint,
4809            schema: Arc::new(schema),
4810        })
4811    }
4812
4813    fn validate_side(expr: &Expr, schema: &DFSchema, name: &str) -> Result<()> {
4814        let mut columns = HashSet::new();
4815        expr_to_columns(expr, &mut columns)?;
4816        if columns.is_empty() {
4817            return plan_err!("ASOF {name} expression must reference its input");
4818        }
4819        if let Some(column) = columns
4820            .iter()
4821            .find(|column| !schema.is_column_from_schema(column))
4822        {
4823            return plan_err!(
4824                "ASOF {name} expression references column {column} outside its input"
4825            );
4826        }
4827        Ok(())
4828    }
4829}
4830
4831impl PartialOrd for AsOfJoin {
4832    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4833        (
4834            &self.left,
4835            &self.right,
4836            &self.on,
4837            &self.match_condition,
4838            &self.join_constraint,
4839        )
4840            .partial_cmp(&(
4841                &other.left,
4842                &other.right,
4843                &other.on,
4844                &other.match_condition,
4845                &other.join_constraint,
4846            ))
4847            .filter(|cmp| *cmp != Ordering::Equal || self == other)
4848    }
4849}
4850
4851impl Join {
4852    /// Creates a new Join operator with automatically computed schema.
4853    ///
4854    /// This constructor computes the schema based on the join type and inputs,
4855    /// removing the need to manually specify the schema or call `recompute_schema`.
4856    ///
4857    /// # Arguments
4858    ///
4859    /// * `left` - Left input plan
4860    /// * `right` - Right input plan
4861    /// * `on` - Join condition as a vector of (left_expr, right_expr) pairs
4862    /// * `filter` - Optional filter expression (for non-equijoin conditions)
4863    /// * `join_type` - Type of join (Inner, Left, Right, etc.)
4864    /// * `join_constraint` - Join constraint (On, Using)
4865    /// * `null_equality` - How to handle nulls in join comparisons
4866    /// * `null_aware` - Whether this join needs null-aware NOT IN semantics
4867    ///
4868    /// # Returns
4869    ///
4870    /// A new Join operator with the computed schema
4871    #[expect(clippy::too_many_arguments)]
4872    pub fn try_new(
4873        left: Arc<LogicalPlan>,
4874        right: Arc<LogicalPlan>,
4875        on: Vec<(Expr, Expr)>,
4876        filter: Option<Expr>,
4877        join_type: JoinType,
4878        join_constraint: JoinConstraint,
4879        null_equality: NullEquality,
4880        null_aware: bool,
4881    ) -> Result<Self> {
4882        let join_schema = build_join_schema(left.schema(), right.schema(), &join_type)?;
4883
4884        Ok(Join {
4885            left,
4886            right,
4887            on,
4888            filter,
4889            join_type,
4890            join_constraint,
4891            schema: Arc::new(join_schema),
4892            null_equality,
4893            null_aware,
4894            null_aware_value_keys: 0,
4895        })
4896    }
4897
4898    /// Sets the number of `NOT IN` value keys of a null-aware join, see
4899    /// [`Self::null_aware_value_keys`].
4900    pub fn with_null_aware_value_keys(mut self, null_aware_value_keys: usize) -> Self {
4901        self.null_aware_value_keys = null_aware_value_keys;
4902        self
4903    }
4904
4905    /// Create Join with input which wrapped with projection, this method is used in physical planning only to help
4906    /// create the physical join.
4907    pub fn try_new_with_project_input(
4908        original: &LogicalPlan,
4909        left: Arc<LogicalPlan>,
4910        right: Arc<LogicalPlan>,
4911        column_on: (Vec<Column>, Vec<Column>),
4912    ) -> Result<(Self, bool)> {
4913        let LogicalPlan::Join(original_join) = original else {
4914            return plan_err!("Could not create join with project input");
4915        };
4916
4917        let mut left_sch = LogicalPlanBuilder::from(Arc::clone(&left));
4918        let mut right_sch = LogicalPlanBuilder::from(Arc::clone(&right));
4919
4920        let mut requalified = false;
4921
4922        // By definition, the resulting schema of an inner/left/right & full join will have first the left side fields and then the right,
4923        // potentially having duplicate field names. Note this will only qualify fields if they have not been qualified before.
4924        if original_join.join_type == JoinType::Inner
4925            || original_join.join_type == JoinType::Left
4926            || original_join.join_type == JoinType::Right
4927            || original_join.join_type == JoinType::Full
4928        {
4929            (left_sch, right_sch, requalified) =
4930                requalify_sides_if_needed(left_sch.clone(), right_sch.clone())?;
4931        }
4932
4933        let on: Vec<(Expr, Expr)> = column_on
4934            .0
4935            .into_iter()
4936            .zip(column_on.1)
4937            .map(|(l, r)| (Expr::Column(l), Expr::Column(r)))
4938            .collect();
4939
4940        let join_schema = build_join_schema(
4941            left_sch.schema(),
4942            right_sch.schema(),
4943            &original_join.join_type,
4944        )?;
4945
4946        Ok((
4947            Join {
4948                left,
4949                right,
4950                on,
4951                filter: original_join.filter.clone(),
4952                join_type: original_join.join_type,
4953                join_constraint: original_join.join_constraint,
4954                schema: Arc::new(join_schema),
4955                null_equality: original_join.null_equality,
4956                null_aware: original_join.null_aware,
4957                null_aware_value_keys: original_join.null_aware_value_keys,
4958            },
4959            requalified,
4960        ))
4961    }
4962}
4963
4964// Manual implementation needed because of `schema` field. Comparison excludes this field.
4965impl PartialOrd for Join {
4966    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4967        #[derive(PartialEq, PartialOrd)]
4968        struct ComparableJoin<'a> {
4969            /// Left input
4970            pub left: &'a Arc<LogicalPlan>,
4971            /// Right input
4972            pub right: &'a Arc<LogicalPlan>,
4973            /// Equijoin clause expressed as pairs of (left, right) join expressions
4974            pub on: &'a Vec<(Expr, Expr)>,
4975            /// Filters applied during join (non-equi conditions)
4976            pub filter: &'a Option<Expr>,
4977            /// Join type
4978            pub join_type: &'a JoinType,
4979            /// Join constraint
4980            pub join_constraint: &'a JoinConstraint,
4981            /// The null handling behavior for equalities
4982            pub null_equality: &'a NullEquality,
4983        }
4984        let comparable_self = ComparableJoin {
4985            left: &self.left,
4986            right: &self.right,
4987            on: &self.on,
4988            filter: &self.filter,
4989            join_type: &self.join_type,
4990            join_constraint: &self.join_constraint,
4991            null_equality: &self.null_equality,
4992        };
4993        let comparable_other = ComparableJoin {
4994            left: &other.left,
4995            right: &other.right,
4996            on: &other.on,
4997            filter: &other.filter,
4998            join_type: &other.join_type,
4999            join_constraint: &other.join_constraint,
5000            null_equality: &other.null_equality,
5001        };
5002        comparable_self
5003            .partial_cmp(&comparable_other)
5004            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
5005            .filter(|cmp| *cmp != Ordering::Equal || self == other)
5006    }
5007}
5008
5009/// Subquery
5010#[derive(Clone, PartialEq, Eq, PartialOrd, Hash)]
5011pub struct Subquery {
5012    /// The subquery
5013    pub subquery: Arc<LogicalPlan>,
5014    /// The outer references used in the subquery
5015    pub outer_ref_columns: Vec<Expr>,
5016    /// Span information for subquery projection columns
5017    pub spans: Spans,
5018}
5019
5020impl Normalizeable for Subquery {
5021    fn can_normalize(&self) -> bool {
5022        false
5023    }
5024}
5025
5026impl NormalizeEq for Subquery {
5027    fn normalize_eq(&self, other: &Self) -> bool {
5028        // TODO: may be implement NormalizeEq for LogicalPlan?
5029        *self.subquery == *other.subquery
5030            && self.outer_ref_columns.len() == other.outer_ref_columns.len()
5031            && self
5032                .outer_ref_columns
5033                .iter()
5034                .zip(other.outer_ref_columns.iter())
5035                .all(|(a, b)| a.normalize_eq(b))
5036    }
5037}
5038
5039impl Subquery {
5040    pub fn try_from_expr(plan: &Expr) -> Result<&Subquery> {
5041        match plan {
5042            Expr::ScalarSubquery(it) => Ok(it),
5043            Expr::Cast(cast) => Subquery::try_from_expr(cast.expr.as_ref()),
5044            _ => plan_err!("Could not coerce into ScalarSubquery!"),
5045        }
5046    }
5047
5048    pub fn with_plan(&self, plan: Arc<LogicalPlan>) -> Subquery {
5049        Subquery {
5050            subquery: plan,
5051            outer_ref_columns: self.outer_ref_columns.clone(),
5052            spans: Spans::new(),
5053        }
5054    }
5055}
5056
5057impl Debug for Subquery {
5058    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
5059        write!(f, "<subquery>")
5060    }
5061}
5062
5063/// Logical partitioning schemes.
5064///
5065/// A scheme can describe either requested repartitioning in
5066/// [`LogicalPlan::Repartition`] or a partitioning property declared by a source.
5067/// Some schemes are only valid as metadata until planner support is added.
5068///
5069/// For physical execution partitioning, see
5070/// [`datafusion_physical_expr::Partitioning`].
5071///
5072/// [`datafusion_physical_expr::Partitioning`]: https://docs.rs/datafusion/latest/datafusion/physical_expr/enum.Partitioning.html#
5073#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
5074pub enum Partitioning {
5075    /// Allocate batches using a round-robin algorithm and the specified number of partitions
5076    RoundRobinBatch(usize),
5077    /// Allocate rows based on a hash of one of more expressions and the specified number
5078    /// of partitions.
5079    Hash(Vec<Expr>, usize),
5080    /// Partition rows by ranges.
5081    /// See [`RangePartitioning`] for the logical contract.
5082    Range(RangePartitioning),
5083    /// The DISTRIBUTE BY clause is used to repartition the data based on the input expressions
5084    DistributeBy(Vec<Expr>),
5085}
5086
5087impl Partitioning {
5088    /// Return the number of partitions, if known.
5089    pub fn partition_count(&self) -> Option<usize> {
5090        match self {
5091            Self::RoundRobinBatch(partition_count) | Self::Hash(_, partition_count) => {
5092                Some(*partition_count)
5093            }
5094            Self::Range(range) => Some(range.partition_count()),
5095            Self::DistributeBy(_) => None,
5096        }
5097    }
5098}
5099
5100/// Logical range partitioning.
5101///
5102/// [`RangePartitioning`] describes an ordered logical key space with split points.
5103///
5104/// - `ordering` defines the partitioning key and ordering using logical
5105///   [`SortExpr`]s.
5106/// - `split_points` define the boundaries between adjacent partitions.
5107///
5108/// Comparisons use the lexicographic order defined by `ordering`,
5109/// including `ASC`/`DESC` and null ordering. Split points must be ordered
5110/// according to that ordering, and each split point must have one value per
5111/// ordering expression. See [`SplitPoint`] for the shared boundary contract.
5112///
5113/// The expressions are resolved against the declaring plan's schema. This
5114/// constructor does not validate split point value types against the resolved
5115/// expression types. Like other user-specified data properties such as
5116/// sortedness, if a source declares range partitioning, it is responsible for
5117/// placing each row in the partition described by the split points. DataFusion
5118/// will not validate this is upheld.
5119///
5120/// NOTE: Range-aware optimizer and execution behavior will be introduced
5121/// incrementally. See
5122/// <https://github.com/apache/datafusion/issues/22395>.
5123#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
5124pub struct RangePartitioning {
5125    /// Ordered logical partitioning key.
5126    ordering: Vec<SortExpr>,
5127    /// Boundaries between adjacent partitions.
5128    split_points: Vec<SplitPoint>,
5129}
5130
5131impl RangePartitioning {
5132    /// Creates logical range partitioning metadata and validates split point
5133    /// shape and ordering.
5134    pub fn try_new(
5135        ordering: Vec<SortExpr>,
5136        split_points: Vec<SplitPoint>,
5137    ) -> Result<Self> {
5138        if ordering.is_empty() {
5139            return plan_err!("Range partitioning requires non-empty ordering");
5140        }
5141
5142        validate_range_split_points(&split_points, &logical_sort_options(&ordering))?;
5143
5144        Ok(Self {
5145            ordering,
5146            split_points,
5147        })
5148    }
5149
5150    /// Return the number of partitions.
5151    pub fn partition_count(&self) -> usize {
5152        self.split_points.len() + 1
5153    }
5154
5155    /// Returns the ordering that defines the range key.
5156    pub fn ordering(&self) -> &[SortExpr] {
5157        &self.ordering
5158    }
5159
5160    /// Returns the ordered split points between partitions.
5161    pub fn split_points(&self) -> &[SplitPoint] {
5162        &self.split_points
5163    }
5164}
5165
5166fn logical_sort_options(ordering: &[SortExpr]) -> Vec<SortOptions> {
5167    ordering
5168        .iter()
5169        .map(|sort_expr| SortOptions {
5170            descending: !sort_expr.asc,
5171            nulls_first: sort_expr.nulls_first,
5172        })
5173        .collect()
5174}
5175
5176impl Display for RangePartitioning {
5177    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
5178        let ordering = self.ordering().iter().map(ToString::to_string).join(", ");
5179        let split_points = self
5180            .split_points()
5181            .iter()
5182            .map(ToString::to_string)
5183            .join(", ");
5184        write!(
5185            f,
5186            "Range([{ordering}], [{split_points}], {})",
5187            self.partition_count()
5188        )
5189    }
5190}
5191
5192/// Represent the unnesting operation on a list column, such as the recursion depth and
5193/// the output column name after unnesting
5194///
5195/// Example: given `ColumnUnnestList { output_column: "output_name", depth: 2 }`
5196///
5197/// ```text
5198///   input             output_name
5199///  ┌─────────┐      ┌─────────┐
5200///  │{{1,2}}  │      │ 1       │
5201///  ├─────────┼─────►├─────────┤
5202///  │{{3}}    │      │ 2       │
5203///  ├─────────┤      ├─────────┤
5204///  │{{4},{5}}│      │ 3       │
5205///  └─────────┘      ├─────────┤
5206///                   │ 4       │
5207///                   ├─────────┤
5208///                   │ 5       │
5209///                   └─────────┘
5210/// ```
5211#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd)]
5212pub struct ColumnUnnestList {
5213    pub output_column: Column,
5214    pub depth: usize,
5215}
5216
5217impl Display for ColumnUnnestList {
5218    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
5219        write!(f, "{}|depth={}", self.output_column, self.depth)
5220    }
5221}
5222
5223/// Unnest a column that contains a nested list type. See
5224/// [`UnnestOptions`] for more details.
5225#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5226pub struct Unnest {
5227    /// The incoming logical plan
5228    pub input: Arc<LogicalPlan>,
5229    /// Columns to run unnest on, can be a list of (List/Struct) columns
5230    pub exec_columns: Vec<Column>,
5231    /// refer to the indices(in the input schema) of columns
5232    /// that have type list to run unnest on
5233    pub list_type_columns: Vec<(usize, ColumnUnnestList)>,
5234    /// refer to the indices (in the input schema) of columns
5235    /// that have type struct to run unnest on
5236    pub struct_type_columns: Vec<usize>,
5237    /// Having items aligned with the output columns
5238    /// representing which column in the input schema each output column depends on
5239    pub dependency_indices: Vec<usize>,
5240    /// The output schema, containing the unnested field column.
5241    pub schema: DFSchemaRef,
5242    /// Options
5243    pub options: UnnestOptions,
5244}
5245
5246// Manual implementation needed because of `schema` field. Comparison excludes this field.
5247impl PartialOrd for Unnest {
5248    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
5249        #[derive(PartialEq, PartialOrd)]
5250        struct ComparableUnnest<'a> {
5251            /// The incoming logical plan
5252            pub input: &'a Arc<LogicalPlan>,
5253            /// Columns to run unnest on, can be a list of (List/Struct) columns
5254            pub exec_columns: &'a Vec<Column>,
5255            /// refer to the indices(in the input schema) of columns
5256            /// that have type list to run unnest on
5257            pub list_type_columns: &'a Vec<(usize, ColumnUnnestList)>,
5258            /// refer to the indices (in the input schema) of columns
5259            /// that have type struct to run unnest on
5260            pub struct_type_columns: &'a Vec<usize>,
5261            /// Having items aligned with the output columns
5262            /// representing which column in the input schema each output column depends on
5263            pub dependency_indices: &'a Vec<usize>,
5264            /// Options
5265            pub options: &'a UnnestOptions,
5266        }
5267        let comparable_self = ComparableUnnest {
5268            input: &self.input,
5269            exec_columns: &self.exec_columns,
5270            list_type_columns: &self.list_type_columns,
5271            struct_type_columns: &self.struct_type_columns,
5272            dependency_indices: &self.dependency_indices,
5273            options: &self.options,
5274        };
5275        let comparable_other = ComparableUnnest {
5276            input: &other.input,
5277            exec_columns: &other.exec_columns,
5278            list_type_columns: &other.list_type_columns,
5279            struct_type_columns: &other.struct_type_columns,
5280            dependency_indices: &other.dependency_indices,
5281            options: &other.options,
5282        };
5283        comparable_self
5284            .partial_cmp(&comparable_other)
5285            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
5286            .filter(|cmp| *cmp != Ordering::Equal || self == other)
5287    }
5288}
5289
5290impl Unnest {
5291    pub fn try_new(
5292        input: Arc<LogicalPlan>,
5293        exec_columns: Vec<Column>,
5294        options: UnnestOptions,
5295    ) -> Result<Self> {
5296        if exec_columns.is_empty() {
5297            return plan_err!("unnest plan requires at least 1 column to unnest");
5298        }
5299
5300        let mut list_columns: Vec<(usize, ColumnUnnestList)> = vec![];
5301        let mut struct_columns = vec![];
5302        let indices_to_unnest = exec_columns
5303            .iter()
5304            .map(|c| Ok((input.schema().index_of_column(c)?, c)))
5305            .collect::<Result<HashMap<usize, &Column>>>()?;
5306
5307        let input_schema = input.schema();
5308
5309        let mut dependency_indices = Vec::with_capacity(input_schema.fields().len());
5310        // Transform input schema into new schema
5311        // Given this comprehensive example
5312        //
5313        // input schema:
5314        // 1.col1_unnest_placeholder: list[list[int]],
5315        // 2.col1: list[list[int]]
5316        // 3.col2: list[int]
5317        // with unnest on unnest(col1,depth=2), unnest(col1,depth=1) and unnest(col2,depth=1)
5318        // output schema:
5319        // 1.unnest_col1_depth_2: int
5320        // 2.unnest_col1_depth_1: list[int]
5321        // 3.col1: list[list[int]]
5322        // 4.unnest_col2_depth_1: int
5323        // Meaning the placeholder column will be replaced by its unnested variation(s), note
5324        // the plural.
5325        let fields = input_schema
5326            .iter()
5327            .enumerate()
5328            .map(|(index, (original_qualifier, original_field))| {
5329                match indices_to_unnest.get(&index) {
5330                    Some(column_to_unnest) => {
5331                        let recursions_on_column = options
5332                            .recursions
5333                            .iter()
5334                            .filter(|p| -> bool { &p.input_column == *column_to_unnest })
5335                            .collect::<Vec<_>>();
5336                        let mut transformed_columns = recursions_on_column
5337                            .iter()
5338                            .map(|r| {
5339                                list_columns.push((
5340                                    index,
5341                                    ColumnUnnestList {
5342                                        output_column: r.output_column.clone(),
5343                                        depth: r.depth,
5344                                    },
5345                                ));
5346                                Ok(get_unnested_columns(
5347                                    &r.output_column.name,
5348                                    original_field,
5349                                    r.depth,
5350                                )?
5351                                .into_iter()
5352                                .next()
5353                                .unwrap()) // because unnesting a list column always result into one result
5354                            })
5355                            .collect::<Result<Vec<(Column, Arc<Field>)>>>()?;
5356                        if transformed_columns.is_empty() {
5357                            transformed_columns = get_unnested_columns(
5358                                &column_to_unnest.name,
5359                                original_field,
5360                                1,
5361                            )?;
5362                            match original_field.data_type() {
5363                                DataType::Struct(_) => {
5364                                    struct_columns.push(index);
5365                                }
5366                                DataType::List(_)
5367                                | DataType::FixedSizeList(_, _)
5368                                | DataType::LargeList(_)
5369                                | DataType::ListView(_)
5370                                | DataType::LargeListView(_) => {
5371                                    list_columns.push((
5372                                        index,
5373                                        ColumnUnnestList {
5374                                            output_column: Column::from_name(
5375                                                &column_to_unnest.name,
5376                                            ),
5377                                            depth: 1,
5378                                        },
5379                                    ));
5380                                }
5381                                _ => {}
5382                            }
5383                        }
5384
5385                        // new columns dependent on the same original index
5386                        dependency_indices.extend(std::iter::repeat_n(
5387                            index,
5388                            transformed_columns.len(),
5389                        ));
5390                        Ok(transformed_columns
5391                            .iter()
5392                            .map(|(col, field)| {
5393                                (col.relation.to_owned(), field.to_owned())
5394                            })
5395                            .collect())
5396                    }
5397                    None => {
5398                        dependency_indices.push(index);
5399                        Ok(vec![(
5400                            original_qualifier.cloned(),
5401                            Arc::clone(original_field),
5402                        )])
5403                    }
5404                }
5405            })
5406            .collect::<Result<Vec<_>>>()?
5407            .into_iter()
5408            .flatten()
5409            .collect::<Vec<_>>();
5410
5411        let metadata = input_schema.metadata().clone();
5412        let df_schema = DFSchema::new_with_metadata(fields, metadata)?;
5413        let list_indices: HashSet<_> =
5414            list_columns.iter().map(|(index, _)| *index).collect();
5415        // Struct unnest may replace one input column with several output columns,
5416        // so remap dependencies using the input index of each output column.
5417        let remap_indices = |indices: &[usize], exclude_lists: bool| {
5418            dependency_indices
5419                .iter()
5420                .enumerate()
5421                .filter_map(|(output_index, input_index)| {
5422                    (indices.contains(input_index)
5423                        && (!exclude_lists || !list_indices.contains(input_index)))
5424                    .then_some(output_index)
5425                })
5426                .collect()
5427        };
5428        let deps = FunctionalDependencies::new(
5429            input_schema
5430                .functional_dependencies()
5431                .iter()
5432                // A list input no longer determines the rows produced by unnest.
5433                // A struct input is also unsafe as a source: a null struct and
5434                // a non-null struct with all-null fields have the same outputs.
5435                .filter(|dep| {
5436                    dep.source_indices.iter().all(|index| {
5437                        !list_indices.contains(index) && !struct_columns.contains(index)
5438                    })
5439                })
5440                .map(|dep| FunctionalDependence {
5441                    source_indices: remap_indices(&dep.source_indices, false),
5442                    // The unnested values are not determined by the input key.
5443                    target_indices: remap_indices(&dep.target_indices, true),
5444                    // One input row can produce multiple output rows.
5445                    mode: if list_indices.is_empty() {
5446                        dep.mode
5447                    } else {
5448                        Dependency::Multi
5449                    },
5450                    ..dep.clone()
5451                })
5452                .collect(),
5453        );
5454        let schema = Arc::new(df_schema.with_functional_dependencies(deps)?);
5455
5456        Ok(Unnest {
5457            input,
5458            exec_columns,
5459            list_type_columns: list_columns,
5460            struct_type_columns: struct_columns,
5461            dependency_indices,
5462            schema,
5463            options,
5464        })
5465    }
5466}
5467
5468// Based on data type, either struct or a variant of list
5469// return a set of columns as the result of unnesting
5470// the input columns.
5471// For example, given a column with name "a",
5472// - List(Element) returns ["a"] with data type Element
5473// - Struct(field1, field2) returns ["a.field1","a.field2"]
5474// For list data type, an argument depth is used to specify
5475// the recursion level
5476fn get_unnested_columns(
5477    col_name: &String,
5478    field: &Field,
5479    depth: usize,
5480) -> Result<Vec<(Column, Arc<Field>)>> {
5481    let data_type = field.data_type();
5482    let mut qualified_columns = Vec::with_capacity(1);
5483
5484    match data_type {
5485        DataType::List(_)
5486        | DataType::FixedSizeList(_, _)
5487        | DataType::LargeList(_)
5488        | DataType::ListView(_)
5489        | DataType::LargeListView(_) => {
5490            let field = get_unnested_list_field(data_type, depth)?;
5491            let new_field = Arc::new(
5492                field
5493                    .clone()
5494                    .with_name(col_name)
5495                    // Unnesting may produce NULLs even if the list is not null.
5496                    // For example: unnest([1], []) -> 1, null
5497                    .with_nullable(true),
5498            );
5499            let column = Column::from_name(col_name);
5500            // let column = Column::from((None, &new_field));
5501            qualified_columns.push((column, new_field));
5502        }
5503        DataType::Struct(fields) => {
5504            qualified_columns.extend(fields.iter().map(|f| {
5505                let new_name = format!("{}.{}", col_name, f.name());
5506                let column = Column::from_name(&new_name);
5507                let new_field = f
5508                    .as_ref()
5509                    .clone()
5510                    .with_name(new_name)
5511                    .with_nullable(field.is_nullable() || f.is_nullable());
5512                // let column = Column::from((None, &f));
5513                (column, Arc::new(new_field))
5514            }))
5515        }
5516        _ => {
5517            return internal_err!("trying to unnest on invalid data type {data_type}");
5518        }
5519    }
5520    Ok(qualified_columns)
5521}
5522
5523#[cfg(test)]
5524mod tests {
5525    use super::*;
5526    use crate::builder::LogicalTableSource;
5527    use crate::logical_plan::table_scan;
5528    use crate::select_expr::SelectExpr;
5529    use crate::test::function_stub::{count, count_udaf};
5530    use crate::{
5531        GroupingSet, binary_expr, col, exists, in_subquery, lit, placeholder,
5532        scalar_subquery,
5533    };
5534    use arrow::datatypes::Metadata;
5535    use datafusion_common::metadata::ScalarAndMetadata;
5536    use datafusion_common::tree_node::{
5537        TransformedResult, TreeNodeRewriter, TreeNodeVisitor,
5538    };
5539    use datafusion_common::{Constraint, RecursionUnnestOption, not_impl_err};
5540    use insta::{assert_debug_snapshot, assert_snapshot};
5541    use std::hash::DefaultHasher;
5542
5543    /// `LogicalPlan` is moved/swapped on every step of the planning hot path
5544    /// (every `mem::take` in an in-place rewriter, every `Arc<LogicalPlan>`
5545    /// write, every owned `map_*` traversal). Its size is set by the largest
5546    /// variant, so an oversized variant balloons cost for every other variant.
5547    ///
5548    /// Today the size-setter should be `Join` (~176 bytes); `DdlStatement` is
5549    /// boxed precisely so it does not dominate. If you grow a variant, please
5550    /// box the new large fields rather than letting this number creep up —
5551    /// see the analogous `test_size_of_expr` in `expr.rs`.
5552    #[test]
5553    fn test_size_of_logical_plan() {
5554        // `LogicalPlan` enum on aarch64 / x86_64. Today this matches
5555        // `Join`'s 176 bytes (the enum discriminant fits in `Join`'s
5556        // alignment padding); if `Join` grows or another variant overtakes
5557        // it, this number will move with the new size-setter.
5558        assert_eq!(size_of::<LogicalPlan>(), 176);
5559        // `DdlStatement` is `Ddl(DdlStatement)`'s payload; keep it below the
5560        // `Join` ceiling so it never re-becomes the size-setter.
5561        assert!(
5562            size_of::<DdlStatement>() < size_of::<Join>(),
5563            "DdlStatement ({} bytes) should stay smaller than Join ({} bytes); \
5564             box the new large variant rather than letting it dominate `LogicalPlan`.",
5565            size_of::<DdlStatement>(),
5566            size_of::<Join>(),
5567        );
5568        // Sanity check the two boxed variants stay boxed (so the payload
5569        // sits on the heap, not in the enum).
5570        assert_eq!(
5571            size_of::<Box<crate::CreateExternalTable>>(),
5572            8,
5573            "CreateExternalTable should be Box'd inside DdlStatement"
5574        );
5575        assert_eq!(
5576            size_of::<Box<crate::CreateFunction>>(),
5577            8,
5578            "CreateFunction should be Box'd inside DdlStatement"
5579        );
5580    }
5581
5582    #[test]
5583    fn limit_literals_use_checked_usize_conversion() -> Result<()> {
5584        let value = i64::from(u32::MAX) + 1;
5585        let input = Arc::new(LogicalPlanBuilder::empty(false).build()?);
5586        let limit = Limit {
5587            skip: Some(Box::new(lit(value))),
5588            fetch: Some(Box::new(lit(value))),
5589            input,
5590        };
5591
5592        if usize::BITS < 64 {
5593            assert!(limit.get_skip_type().is_err());
5594            assert!(limit.get_fetch_type().is_err());
5595        } else {
5596            let expected = usize::try_from(value).unwrap();
5597            let SkipType::Literal(skip) = limit.get_skip_type()? else {
5598                panic!("expected literal skip")
5599            };
5600            let FetchType::Literal(Some(fetch)) = limit.get_fetch_type()? else {
5601                panic!("expected literal fetch")
5602            };
5603            assert_eq!(skip, expected);
5604            assert_eq!(fetch, expected);
5605        }
5606        Ok(())
5607    }
5608
5609    fn employee_schema() -> Schema {
5610        Schema::new(vec![
5611            Field::new("id", DataType::Int32, false),
5612            Field::new("first_name", DataType::Utf8, false),
5613            Field::new("last_name", DataType::Utf8, false),
5614            Field::new("state", DataType::Utf8, false),
5615            Field::new("salary", DataType::Int32, false),
5616        ])
5617    }
5618
5619    #[test]
5620    fn unnest_remaps_functional_dependencies() -> Result<()> {
5621        let schema = Arc::new(Schema::new(vec![
5622            Field::new_struct(
5623                "s",
5624                vec![
5625                    Field::new("a", DataType::Int32, true),
5626                    Field::new("b", DataType::Int32, true),
5627                ],
5628                true,
5629            ),
5630            Field::new("k", DataType::Int32, false),
5631            Field::new_list(
5632                "xs",
5633                Field::new_list(
5634                    "item",
5635                    Field::new_list_field(DataType::Int32, true),
5636                    true,
5637                ),
5638                true,
5639            ),
5640            Field::new("payload", DataType::Utf8, true),
5641        ]));
5642        let constraints = Constraints::new_unverified(vec![
5643            Constraint::PrimaryKey(vec![1]),
5644            Constraint::Unique(vec![0]),
5645            Constraint::Unique(vec![2]),
5646        ]);
5647        let source: Arc<dyn TableSource> =
5648            Arc::new(LogicalTableSource::new(schema).with_constraints(constraints));
5649
5650        // Expanding a struct preserves row count and remaps keys and targets,
5651        // but a dependency sourced from the struct itself cannot be kept.
5652        let struct_only = LogicalPlanBuilder::scan("t", Arc::clone(&source), None)?
5653            .unnest_column("s")?
5654            .build()?;
5655        assert_eq!(
5656            struct_only.schema().functional_dependencies(),
5657            &FunctionalDependencies::new(vec![
5658                FunctionalDependence::new(vec![2], vec![0, 1, 2, 3, 4], false)
5659                    .with_mode(Dependency::Single),
5660                FunctionalDependence::new(vec![3], vec![0, 1, 2, 3, 4], true)
5661                    .with_mode(Dependency::Single),
5662            ])
5663        );
5664
5665        // The two recursion outputs both replace the same list input. Neither
5666        // is determined by k, and a list-sourced dependency is no longer valid.
5667        let options = UnnestOptions::default()
5668            .with_recursions(RecursionUnnestOption {
5669                input_column: "xs".into(),
5670                output_column: "xs_depth_1".into(),
5671                depth: 1,
5672            })
5673            .with_recursions(RecursionUnnestOption {
5674                input_column: "xs".into(),
5675                output_column: "xs_depth_2".into(),
5676                depth: 2,
5677            });
5678        let plan = LogicalPlanBuilder::scan("t", source, None)?
5679            .unnest_columns_with_options(vec!["s".into(), "xs".into()], options)?
5680            .build()?;
5681        assert_eq!(plan.schema().fields().len(), 6);
5682        assert_eq!(
5683            plan.schema().functional_dependencies(),
5684            &FunctionalDependencies::new(vec![
5685                FunctionalDependence::new(vec![2], vec![0, 1, 2, 5], false,)
5686                    .with_mode(Dependency::Multi)
5687            ])
5688        );
5689
5690        Ok(())
5691    }
5692
5693    #[test]
5694    fn projection_with_leading_computed_column_preserves_pk() -> Result<()> {
5695        let constraints =
5696            Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
5697        let source = Arc::new(
5698            LogicalTableSource::new(Arc::new(employee_schema()))
5699                .with_constraints(constraints),
5700        );
5701        let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5702            .project(vec![
5703                lit(1i32).alias("__common_expr_1"),
5704                col("id"),
5705                col("first_name"),
5706                col("salary"),
5707            ])?
5708            .build()?;
5709
5710        let deps = plan.schema().functional_dependencies();
5711        assert_eq!(deps.len(), 1);
5712        assert_eq!(deps[0].source_indices, vec![1]);
5713
5714        Ok(())
5715    }
5716
5717    #[test]
5718    fn projection_with_leading_computed_column_and_wildcard_preserves_pk() -> Result<()> {
5719        let constraints =
5720            Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
5721        let source = Arc::new(
5722            LogicalTableSource::new(Arc::new(employee_schema()))
5723                .with_constraints(constraints),
5724        );
5725        let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5726            .project(vec![
5727                SelectExpr::Expression(lit(1i32).alias("__common_expr_1")),
5728                SelectExpr::Wildcard(Default::default()),
5729            ])?
5730            .build()?;
5731
5732        let deps = plan.schema().functional_dependencies();
5733        assert_eq!(plan.schema().fields().len(), 6);
5734        assert_eq!(deps.len(), 1);
5735        assert_eq!(deps[0].source_indices, vec![1]);
5736        assert_eq!(deps[0].target_indices, vec![0, 1, 2, 3, 4, 5]);
5737
5738        Ok(())
5739    }
5740
5741    #[test]
5742    fn projection_with_wildcard_expr_before_pk_preserves_pk() -> Result<()> {
5743        let constraints =
5744            Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
5745        let source = Arc::new(
5746            LogicalTableSource::new(Arc::new(employee_schema()))
5747                .with_constraints(constraints),
5748        );
5749        let input = LogicalPlanBuilder::scan("employee_csv", source, None)?.build()?;
5750        #[expect(deprecated)]
5751        let projection = Projection::try_new(
5752            vec![
5753                Expr::Wildcard {
5754                    qualifier: None,
5755                    options: Box::new(crate::expr::WildcardOptions::default()),
5756                },
5757                col("employee_csv.id"),
5758            ],
5759            Arc::new(input),
5760        )?;
5761
5762        let deps = projection.schema.functional_dependencies();
5763        assert_eq!(deps.len(), 1);
5764        assert_eq!(deps[0].source_indices, vec![1]);
5765
5766        Ok(())
5767    }
5768
5769    #[test]
5770    fn projection_with_alias_preserves_pk() -> Result<()> {
5771        let constraints =
5772            Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
5773        let source = Arc::new(
5774            LogicalTableSource::new(Arc::new(employee_schema()))
5775                .with_constraints(constraints),
5776        );
5777        let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5778            .project(vec![col("id").alias("emp_id"), col("first_name")])?
5779            .build()?;
5780
5781        let deps = plan.schema().functional_dependencies();
5782        assert_eq!(deps.len(), 1);
5783        assert_eq!(deps[0].source_indices, vec![0]);
5784        assert_eq!(deps[0].target_indices, vec![0, 1]);
5785
5786        Ok(())
5787    }
5788
5789    #[test]
5790    fn projection_over_unconstrained_table_has_no_dependencies() -> Result<()> {
5791        let source = Arc::new(LogicalTableSource::new(Arc::new(employee_schema())));
5792        let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5793            .project(vec![col("id"), col("first_name")])?
5794            .build()?;
5795
5796        let deps = plan.schema().functional_dependencies();
5797        assert!(deps.is_empty());
5798
5799        Ok(())
5800    }
5801
5802    #[test]
5803    fn aggregate_group_by_repeated_key_keeps_key_dependency() -> Result<()> {
5804        let constraints =
5805            Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
5806        let source = Arc::new(
5807            LogicalTableSource::new(Arc::new(employee_schema()))
5808                .with_constraints(constraints),
5809        );
5810        // `id` is in the GROUP BY list two times: as itself and as `k`.
5811        let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5812            .aggregate(
5813                vec![col("id"), col("state"), col("id").alias("k")],
5814                Vec::<Expr>::new(),
5815            )?
5816            .build()?;
5817
5818        // `id` alone still determines the row.
5819        let deps = plan.schema().functional_dependencies();
5820        assert_eq!(deps.len(), 1);
5821        assert_eq!(deps[0].source_indices, vec![0]);
5822        assert_eq!(deps[0].target_indices, vec![0, 1, 2]);
5823
5824        Ok(())
5825    }
5826
5827    #[test]
5828    fn projection_resolves_columns_not_flattened_names() -> Result<()> {
5829        // Build an input schema where a qualified field (`orders`.`id`) and an
5830        // unqualified field that is literally named `"orders.id"` (the name of
5831        // e.g. `CAST(orders.id AS INT)`) have the same flattened name. The
5832        // projection must resolve the column it references, not the first
5833        // field with the same flattened name.
5834        let schema = DFSchema::new_with_metadata(
5835            vec![
5836                (
5837                    Some(TableReference::bare("orders")),
5838                    Arc::new(Field::new("id", DataType::Int32, false)),
5839                ),
5840                (
5841                    None,
5842                    Arc::new(Field::new("orders.id", DataType::Int32, false)),
5843                ),
5844            ],
5845            Metadata::default(),
5846        )?
5847        .with_functional_dependencies(FunctionalDependencies::new(vec![
5848            FunctionalDependence::new(vec![0], vec![0, 1], false)
5849                .with_mode(Dependency::Single),
5850        ]))?;
5851        let input = LogicalPlan::EmptyRelation(EmptyRelation {
5852            produce_one_row: true,
5853            schema: Arc::new(schema),
5854        });
5855
5856        // References the *unqualified* second field, which is not a key.
5857        let exprs = vec![Expr::Column(Column::new_unqualified("orders.id"))];
5858        let deps = calc_func_dependencies_for_project(&exprs, &input)?;
5859        assert!(deps.is_empty());
5860
5861        // References the qualified first field, which is a key.
5862        let exprs = vec![Expr::Column(Column::new(Some("orders"), "id"))];
5863        let deps = calc_func_dependencies_for_project(&exprs, &input)?;
5864        assert_eq!(deps.len(), 1);
5865        assert_eq!(deps[0].source_indices, vec![0]);
5866
5867        Ok(())
5868    }
5869
5870    #[test]
5871    fn aggregate_group_by_on_primary_key_reports_single_dependency() -> Result<()> {
5872        let constraints =
5873            Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
5874        let source = Arc::new(
5875            LogicalTableSource::new(Arc::new(employee_schema()))
5876                .with_constraints(constraints),
5877        );
5878        let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5879            .aggregate(vec![col("id")], vec![count(lit(true))])?
5880            .build()?;
5881
5882        let deps = plan.schema().functional_dependencies();
5883        assert_eq!(deps.len(), 1);
5884        assert_eq!(deps[0].source_indices, vec![0]);
5885        assert_eq!(deps[0].mode, Dependency::Single);
5886
5887        Ok(())
5888    }
5889
5890    #[test]
5891    fn aggregate_group_by_without_constraints_still_reports_single_dependency()
5892    -> Result<()> {
5893        // Grouping guarantees uniqueness of the GROUP BY key regardless of
5894        // whether the input table carries any PRIMARY KEY / UNIQUE
5895        // constraints, so `aggregate_functional_dependencies` must still
5896        // report a `Single` dependency spanning the whole aggregate output.
5897        // This pins that behavior so the early return added for the (far
5898        // more common) case of an input with no functional dependencies at
5899        // all cannot be mistakenly widened to also skip this GROUP BY-only
5900        // dependency.
5901        let source = Arc::new(LogicalTableSource::new(Arc::new(employee_schema())));
5902        let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5903            .aggregate(vec![col("id")], vec![count(lit(true))])?
5904            .build()?;
5905
5906        let deps = plan.schema().functional_dependencies();
5907        assert_eq!(deps.len(), 1);
5908        assert_eq!(deps[0].source_indices, vec![0]);
5909        assert_eq!(deps[0].mode, Dependency::Single);
5910
5911        Ok(())
5912    }
5913
5914    fn i32_split_point(value: i32) -> SplitPoint {
5915        SplitPoint::new(vec![ScalarValue::Int32(Some(value))])
5916    }
5917
5918    fn null_i32_split_point() -> SplitPoint {
5919        SplitPoint::new(vec![ScalarValue::Int32(None)])
5920    }
5921
5922    #[test]
5923    fn logical_range_partitioning_validates_shape() {
5924        let range = RangePartitioning::try_new(
5925            vec![col("id").sort(true, true)],
5926            vec![i32_split_point(10), i32_split_point(20)],
5927        )
5928        .unwrap();
5929        assert_eq!(range.partition_count(), 3);
5930
5931        let range = RangePartitioning::try_new(
5932            vec![col("id").sort(false, true)],
5933            vec![i32_split_point(20), i32_split_point(10)],
5934        )
5935        .unwrap();
5936        assert_eq!(range.partition_count(), 3);
5937
5938        let err = RangePartitioning::try_new(vec![], vec![]).unwrap_err();
5939        assert!(err.to_string().contains("non-empty ordering"));
5940
5941        let err = RangePartitioning::try_new(
5942            vec![col("id").sort(true, true), col("salary").sort(true, true)],
5943            vec![i32_split_point(10)],
5944        )
5945        .unwrap_err();
5946        assert!(
5947            err.to_string()
5948                .contains("split point 0 has width 1, but ordering has width 2")
5949        );
5950
5951        let err = RangePartitioning::try_new(
5952            vec![col("id").sort(true, true)],
5953            vec![i32_split_point(20), i32_split_point(10)],
5954        )
5955        .unwrap_err();
5956        assert!(
5957            err.to_string()
5958                .contains("split points must be strictly ordered")
5959        );
5960
5961        let err = RangePartitioning::try_new(
5962            vec![col("id").sort(true, true)],
5963            vec![i32_split_point(10), i32_split_point(10)],
5964        )
5965        .unwrap_err();
5966        assert!(
5967            err.to_string()
5968                .contains("split points must be strictly ordered")
5969        );
5970
5971        let range = RangePartitioning::try_new(
5972            vec![col("id").sort(true, true)],
5973            vec![null_i32_split_point(), i32_split_point(10)],
5974        )
5975        .unwrap();
5976        assert_eq!(range.partition_count(), 3);
5977    }
5978
5979    #[test]
5980    fn logical_partitioning_reports_known_partition_count() -> Result<()> {
5981        let range = RangePartitioning::try_new(
5982            vec![col("id").sort(true, true)],
5983            vec![i32_split_point(10)],
5984        )?;
5985
5986        assert_eq!(Partitioning::RoundRobinBatch(4).partition_count(), Some(4));
5987        assert_eq!(
5988            Partitioning::Hash(vec![col("id")], 8).partition_count(),
5989            Some(8)
5990        );
5991        assert_eq!(Partitioning::Range(range).partition_count(), Some(2));
5992        assert_eq!(
5993            Partitioning::DistributeBy(vec![col("id")]).partition_count(),
5994            None
5995        );
5996
5997        Ok(())
5998    }
5999
6000    #[test]
6001    fn logical_range_partitioning_participates_in_expression_rewrite() -> Result<()> {
6002        let input =
6003            table_scan(Some("employee_csv"), &employee_schema(), None)?.build()?;
6004        let plan = LogicalPlan::Repartition(Repartition {
6005            input: Arc::new(input),
6006            partitioning_scheme: Partitioning::Range(RangePartitioning::try_new(
6007                vec![col("id").sort(true, true)],
6008                vec![i32_split_point(10)],
6009            )?),
6010        });
6011
6012        let mut visited_exprs = vec![];
6013        plan.apply_expressions(|expr| {
6014            visited_exprs.push(expr.to_string());
6015            Ok(TreeNodeRecursion::Continue)
6016        })?;
6017        assert_eq!(visited_exprs, vec!["id"]);
6018
6019        let plan = plan
6020            .map_expressions(|expr| {
6021                if expr == col("id") {
6022                    Ok(Transformed::yes(col("salary")))
6023                } else {
6024                    Ok(Transformed::no(expr))
6025                }
6026            })?
6027            .data;
6028
6029        let LogicalPlan::Repartition(Repartition {
6030            partitioning_scheme: Partitioning::Range(range),
6031            ..
6032        }) = plan
6033        else {
6034            unreachable!("expected range repartition");
6035        };
6036        assert_eq!(range.ordering()[0].expr, col("salary"));
6037        assert_eq!(range.partition_count(), 2);
6038
6039        Ok(())
6040    }
6041
6042    fn display_plan() -> Result<LogicalPlan> {
6043        let plan1 = table_scan(Some("employee_csv"), &employee_schema(), Some(vec![3]))?
6044            .build()?;
6045
6046        table_scan(Some("employee_csv"), &employee_schema(), Some(vec![0, 3]))?
6047            .filter(in_subquery(col("state"), Arc::new(plan1)))?
6048            .project(vec![col("id")])?
6049            .build()
6050    }
6051
6052    fn recursive_term_scan(name: &str, fields: Vec<Field>) -> Result<Arc<LogicalPlan>> {
6053        Ok(Arc::new(
6054            table_scan(Some(name), &Schema::new(fields), None)?.build()?,
6055        ))
6056    }
6057
6058    #[test]
6059    fn recursive_query_widens_nullability_per_column() -> Result<()> {
6060        // Column `a` is non-nullable in both terms and must stay non-nullable;
6061        // column `b` is non-nullable in the static term but nullable in the
6062        // recursive term, so the output must widen it to nullable.
6063        let static_term = recursive_term_scan(
6064            "static",
6065            vec![
6066                Field::new("a", DataType::Int32, false),
6067                Field::new("b", DataType::Int32, false),
6068            ],
6069        )?;
6070        let recursive_term = recursive_term_scan(
6071            "rec",
6072            vec![
6073                Field::new("a", DataType::Int32, false),
6074                Field::new("b", DataType::Int32, true),
6075            ],
6076        )?;
6077
6078        let query =
6079            RecursiveQuery::try_new("t".to_string(), static_term, recursive_term, false)?;
6080
6081        // Names and types are taken from the static term.
6082        assert_eq!(query.schema.field(0).name(), "a");
6083        assert_eq!(query.schema.field(1).name(), "b");
6084        assert_eq!(query.schema.field(0).data_type(), &DataType::Int32);
6085        assert_eq!(query.schema.field(1).data_type(), &DataType::Int32);
6086        // Nullability is widened independently per column.
6087        assert!(!query.schema.field(0).is_nullable());
6088        assert!(query.schema.field(1).is_nullable());
6089        // `schema()` returns the widened recursive-query schema.
6090        assert_eq!(
6091            LogicalPlan::RecursiveQuery(query.clone()).schema(),
6092            &query.schema
6093        );
6094        Ok(())
6095    }
6096
6097    #[test]
6098    fn recursive_query_rejects_column_count_mismatch() -> Result<()> {
6099        let static_term =
6100            recursive_term_scan("static", vec![Field::new("a", DataType::Int32, false)])?;
6101        let recursive_term = recursive_term_scan(
6102            "rec",
6103            vec![
6104                Field::new("a", DataType::Int32, false),
6105                Field::new("b", DataType::Int32, false),
6106            ],
6107        )?;
6108
6109        let err =
6110            RecursiveQuery::try_new("t".to_string(), static_term, recursive_term, false)
6111                .unwrap_err();
6112        assert!(
6113            err.strip_backtrace()
6114                .contains("must have the same number of columns"),
6115            "unexpected error: {err}"
6116        );
6117        Ok(())
6118    }
6119
6120    #[test]
6121    fn test_display_indent() -> Result<()> {
6122        let plan = display_plan()?;
6123
6124        assert_snapshot!(plan.display_indent(), @r"
6125        Projection: employee_csv.id
6126          Filter: employee_csv.state IN (<subquery>)
6127            Subquery:
6128              TableScan: employee_csv projection=[state]
6129            TableScan: employee_csv projection=[id, state]
6130        ");
6131        Ok(())
6132    }
6133
6134    #[test]
6135    fn test_display_indent_schema() -> Result<()> {
6136        let plan = display_plan()?;
6137
6138        assert_snapshot!(plan.display_indent_schema(), @r"
6139        Projection: employee_csv.id [id:Int32]
6140          Filter: employee_csv.state IN (<subquery>) [id:Int32, state:Utf8]
6141            Subquery: [state:Utf8]
6142              TableScan: employee_csv projection=[state] [state:Utf8]
6143            TableScan: employee_csv projection=[id, state] [id:Int32, state:Utf8]
6144        ");
6145        Ok(())
6146    }
6147
6148    #[test]
6149    fn test_display_subquery_alias() -> Result<()> {
6150        let plan1 = table_scan(Some("employee_csv"), &employee_schema(), Some(vec![3]))?
6151            .build()?;
6152        let plan1 = Arc::new(plan1);
6153
6154        let plan =
6155            table_scan(Some("employee_csv"), &employee_schema(), Some(vec![0, 3]))?
6156                .project(vec![col("id"), exists(plan1).alias("exists")])?
6157                .build();
6158
6159        assert_snapshot!(plan?.display_indent(), @r"
6160        Projection: employee_csv.id, EXISTS (<subquery>) AS exists
6161          Subquery:
6162            TableScan: employee_csv projection=[state]
6163          TableScan: employee_csv projection=[id, state]
6164        ");
6165        Ok(())
6166    }
6167
6168    #[test]
6169    fn test_display_graphviz() -> Result<()> {
6170        let plan = display_plan()?;
6171
6172        // just test for a few key lines in the output rather than the
6173        // whole thing to make test maintenance easier.
6174        assert_snapshot!(plan.display_graphviz(), @r#"
6175        // Begin DataFusion GraphViz Plan,
6176        // display it online here: https://dreampuf.github.io/GraphvizOnline
6177
6178        digraph {
6179          subgraph cluster_1
6180          {
6181            graph[label="LogicalPlan"]
6182            2[shape=box label="Projection: employee_csv.id"]
6183            3[shape=box label="Filter: employee_csv.state IN (<subquery>)"]
6184            2 -> 3 [arrowhead=none, arrowtail=normal, dir=back]
6185            4[shape=box label="Subquery:"]
6186            3 -> 4 [arrowhead=none, arrowtail=normal, dir=back]
6187            5[shape=box label="TableScan: employee_csv projection=[state]"]
6188            4 -> 5 [arrowhead=none, arrowtail=normal, dir=back]
6189            6[shape=box label="TableScan: employee_csv projection=[id, state]"]
6190            3 -> 6 [arrowhead=none, arrowtail=normal, dir=back]
6191          }
6192          subgraph cluster_7
6193          {
6194            graph[label="Detailed LogicalPlan"]
6195            8[shape=box label="Projection: employee_csv.id\nSchema: [id:Int32]"]
6196            9[shape=box label="Filter: employee_csv.state IN (<subquery>)\nSchema: [id:Int32, state:Utf8]"]
6197            8 -> 9 [arrowhead=none, arrowtail=normal, dir=back]
6198            10[shape=box label="Subquery:\nSchema: [state:Utf8]"]
6199            9 -> 10 [arrowhead=none, arrowtail=normal, dir=back]
6200            11[shape=box label="TableScan: employee_csv projection=[state]\nSchema: [state:Utf8]"]
6201            10 -> 11 [arrowhead=none, arrowtail=normal, dir=back]
6202            12[shape=box label="TableScan: employee_csv projection=[id, state]\nSchema: [id:Int32, state:Utf8]"]
6203            9 -> 12 [arrowhead=none, arrowtail=normal, dir=back]
6204          }
6205        }
6206        // End DataFusion GraphViz Plan
6207        "#);
6208        Ok(())
6209    }
6210
6211    #[test]
6212    fn test_display_pg_json() -> Result<()> {
6213        let plan = display_plan()?;
6214
6215        assert_snapshot!(plan.display_pg_json(), @r#"
6216        [
6217          {
6218            "Plan": {
6219              "Node Type": "Projection",
6220              "Expressions": [
6221                "employee_csv.id"
6222              ],
6223              "Plans": [
6224                {
6225                  "Node Type": "Filter",
6226                  "Condition": "employee_csv.state IN (<subquery>)",
6227                  "Plans": [
6228                    {
6229                      "Node Type": "Subquery",
6230                      "Plans": [
6231                        {
6232                          "Node Type": "TableScan",
6233                          "Relation Name": "employee_csv",
6234                          "Plans": [],
6235                          "Output": [
6236                            "state"
6237                          ]
6238                        }
6239                      ],
6240                      "Output": [
6241                        "state"
6242                      ]
6243                    },
6244                    {
6245                      "Node Type": "TableScan",
6246                      "Relation Name": "employee_csv",
6247                      "Plans": [],
6248                      "Output": [
6249                        "id",
6250                        "state"
6251                      ]
6252                    }
6253                  ],
6254                  "Output": [
6255                    "id",
6256                    "state"
6257                  ]
6258                }
6259              ],
6260              "Output": [
6261                "id"
6262              ]
6263            }
6264          }
6265        ]
6266        "#);
6267        Ok(())
6268    }
6269
6270    /// Tests for the Visitor trait and walking logical plan nodes
6271    #[derive(Debug, Default)]
6272    struct OkVisitor {
6273        strings: Vec<String>,
6274    }
6275
6276    impl<'n> TreeNodeVisitor<'n> for OkVisitor {
6277        type Node = LogicalPlan;
6278
6279        fn f_down(&mut self, plan: &'n LogicalPlan) -> Result<TreeNodeRecursion> {
6280            let s = match plan {
6281                LogicalPlan::Projection { .. } => "pre_visit Projection",
6282                LogicalPlan::Filter { .. } => "pre_visit Filter",
6283                LogicalPlan::TableScan { .. } => "pre_visit TableScan",
6284                _ => {
6285                    return not_impl_err!("unknown plan type");
6286                }
6287            };
6288
6289            self.strings.push(s.into());
6290            Ok(TreeNodeRecursion::Continue)
6291        }
6292
6293        fn f_up(&mut self, plan: &'n LogicalPlan) -> Result<TreeNodeRecursion> {
6294            let s = match plan {
6295                LogicalPlan::Projection { .. } => "post_visit Projection",
6296                LogicalPlan::Filter { .. } => "post_visit Filter",
6297                LogicalPlan::TableScan { .. } => "post_visit TableScan",
6298                _ => {
6299                    return not_impl_err!("unknown plan type");
6300                }
6301            };
6302
6303            self.strings.push(s.into());
6304            Ok(TreeNodeRecursion::Continue)
6305        }
6306    }
6307
6308    #[test]
6309    fn visit_order() {
6310        let mut visitor = OkVisitor::default();
6311        let plan = test_plan();
6312        let res = plan.visit_with_subqueries(&mut visitor);
6313        assert!(res.is_ok());
6314
6315        assert_debug_snapshot!(visitor.strings, @r#"
6316        [
6317            "pre_visit Projection",
6318            "pre_visit Filter",
6319            "pre_visit TableScan",
6320            "post_visit TableScan",
6321            "post_visit Filter",
6322            "post_visit Projection",
6323        ]
6324        "#);
6325    }
6326
6327    #[derive(Debug, Default)]
6328    /// Counter than counts to zero and returns true when it gets there
6329    struct OptionalCounter {
6330        val: Option<usize>,
6331    }
6332
6333    impl OptionalCounter {
6334        fn new(val: usize) -> Self {
6335            Self { val: Some(val) }
6336        }
6337        // Decrements the counter by 1, if any, returning true if it hits zero
6338        fn dec(&mut self) -> bool {
6339            if Some(0) == self.val {
6340                true
6341            } else {
6342                self.val = self.val.take().map(|i| i - 1);
6343                false
6344            }
6345        }
6346    }
6347
6348    #[derive(Debug, Default)]
6349    /// Visitor that returns false after some number of visits
6350    struct StoppingVisitor {
6351        inner: OkVisitor,
6352        /// When Some(0) returns false from pre_visit
6353        return_false_from_pre_in: OptionalCounter,
6354        /// When Some(0) returns false from post_visit
6355        return_false_from_post_in: OptionalCounter,
6356    }
6357
6358    impl<'n> TreeNodeVisitor<'n> for StoppingVisitor {
6359        type Node = LogicalPlan;
6360
6361        fn f_down(&mut self, plan: &'n LogicalPlan) -> Result<TreeNodeRecursion> {
6362            if self.return_false_from_pre_in.dec() {
6363                return Ok(TreeNodeRecursion::Stop);
6364            }
6365            self.inner.f_down(plan)?;
6366
6367            Ok(TreeNodeRecursion::Continue)
6368        }
6369
6370        fn f_up(&mut self, plan: &'n LogicalPlan) -> Result<TreeNodeRecursion> {
6371            if self.return_false_from_post_in.dec() {
6372                return Ok(TreeNodeRecursion::Stop);
6373            }
6374
6375            self.inner.f_up(plan)
6376        }
6377    }
6378
6379    /// test early stopping in pre-visit
6380    #[test]
6381    fn early_stopping_pre_visit() {
6382        let mut visitor = StoppingVisitor {
6383            return_false_from_pre_in: OptionalCounter::new(2),
6384            ..Default::default()
6385        };
6386        let plan = test_plan();
6387        let res = plan.visit_with_subqueries(&mut visitor);
6388        assert!(res.is_ok());
6389
6390        assert_debug_snapshot!(
6391            visitor.inner.strings,
6392            @r#"
6393        [
6394            "pre_visit Projection",
6395            "pre_visit Filter",
6396        ]
6397        "#
6398        );
6399    }
6400
6401    #[test]
6402    fn early_stopping_post_visit() {
6403        let mut visitor = StoppingVisitor {
6404            return_false_from_post_in: OptionalCounter::new(1),
6405            ..Default::default()
6406        };
6407        let plan = test_plan();
6408        let res = plan.visit_with_subqueries(&mut visitor);
6409        assert!(res.is_ok());
6410
6411        assert_debug_snapshot!(
6412            visitor.inner.strings,
6413            @r#"
6414        [
6415            "pre_visit Projection",
6416            "pre_visit Filter",
6417            "pre_visit TableScan",
6418            "post_visit TableScan",
6419        ]
6420        "#
6421        );
6422    }
6423
6424    #[derive(Debug, Default)]
6425    /// Visitor that returns an error after some number of visits
6426    struct ErrorVisitor {
6427        inner: OkVisitor,
6428        /// When Some(0) returns false from pre_visit
6429        return_error_from_pre_in: OptionalCounter,
6430        /// When Some(0) returns false from post_visit
6431        return_error_from_post_in: OptionalCounter,
6432    }
6433
6434    impl<'n> TreeNodeVisitor<'n> for ErrorVisitor {
6435        type Node = LogicalPlan;
6436
6437        fn f_down(&mut self, plan: &'n LogicalPlan) -> Result<TreeNodeRecursion> {
6438            if self.return_error_from_pre_in.dec() {
6439                return not_impl_err!("Error in pre_visit");
6440            }
6441
6442            self.inner.f_down(plan)
6443        }
6444
6445        fn f_up(&mut self, plan: &'n LogicalPlan) -> Result<TreeNodeRecursion> {
6446            if self.return_error_from_post_in.dec() {
6447                return not_impl_err!("Error in post_visit");
6448            }
6449
6450            self.inner.f_up(plan)
6451        }
6452    }
6453
6454    #[test]
6455    fn error_pre_visit() {
6456        let mut visitor = ErrorVisitor {
6457            return_error_from_pre_in: OptionalCounter::new(2),
6458            ..Default::default()
6459        };
6460        let plan = test_plan();
6461        let res = plan.visit_with_subqueries(&mut visitor).unwrap_err();
6462        assert_snapshot!(
6463            res.strip_backtrace(),
6464            @"This feature is not implemented: Error in pre_visit"
6465        );
6466        assert_debug_snapshot!(
6467            visitor.inner.strings,
6468            @r#"
6469        [
6470            "pre_visit Projection",
6471            "pre_visit Filter",
6472        ]
6473        "#
6474        );
6475    }
6476
6477    #[test]
6478    fn error_post_visit() {
6479        let mut visitor = ErrorVisitor {
6480            return_error_from_post_in: OptionalCounter::new(1),
6481            ..Default::default()
6482        };
6483        let plan = test_plan();
6484        let res = plan.visit_with_subqueries(&mut visitor).unwrap_err();
6485        assert_snapshot!(
6486            res.strip_backtrace(),
6487            @"This feature is not implemented: Error in post_visit"
6488        );
6489        assert_debug_snapshot!(
6490            visitor.inner.strings,
6491            @r#"
6492        [
6493            "pre_visit Projection",
6494            "pre_visit Filter",
6495            "pre_visit TableScan",
6496            "post_visit TableScan",
6497        ]
6498        "#
6499        );
6500    }
6501
6502    #[test]
6503    fn test_partial_eq_hash_and_partial_ord() {
6504        let empty_values = Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
6505            produce_one_row: true,
6506            schema: Arc::new(DFSchema::empty()),
6507        }));
6508
6509        let count_window_function = |schema| {
6510            Window::try_new_with_schema(
6511                vec![Expr::WindowFunction(Box::new(WindowFunction::new(
6512                    WindowFunctionDefinition::AggregateUDF(count_udaf()),
6513                    vec![],
6514                )))],
6515                Arc::clone(&empty_values),
6516                Arc::new(schema),
6517            )
6518            .unwrap()
6519        };
6520
6521        let schema_without_metadata = || {
6522            DFSchema::from_unqualified_fields(
6523                vec![Field::new("count", DataType::Int64, false)].into(),
6524                HashMap::new(),
6525            )
6526            .unwrap()
6527        };
6528
6529        let schema_with_metadata = || {
6530            DFSchema::from_unqualified_fields(
6531                vec![Field::new("count", DataType::Int64, false)].into(),
6532                Metadata::new().with("key", "value"),
6533            )
6534            .unwrap()
6535        };
6536
6537        // A Window
6538        let f = count_window_function(schema_without_metadata());
6539
6540        // Same like `f`, different instance
6541        let f2 = count_window_function(schema_without_metadata());
6542        assert_eq!(f, f2);
6543        assert_eq!(hash(&f), hash(&f2));
6544        assert_eq!(f.partial_cmp(&f2), Some(Ordering::Equal));
6545
6546        // Same like `f`, except for schema metadata
6547        let o = count_window_function(schema_with_metadata());
6548        assert_ne!(f, o);
6549        assert_ne!(hash(&f), hash(&o)); // hash can collide for different values but does not collide in this test
6550        assert_eq!(f.partial_cmp(&o), None);
6551    }
6552
6553    fn hash<T: Hash>(value: &T) -> u64 {
6554        let hasher = &mut DefaultHasher::new();
6555        value.hash(hasher);
6556        hasher.finish()
6557    }
6558
6559    #[test]
6560    fn projection_expr_schema_mismatch() -> Result<()> {
6561        let empty_schema = Arc::new(DFSchema::empty());
6562        let p = Projection::try_new_with_schema(
6563            vec![col("a")],
6564            Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
6565                produce_one_row: false,
6566                schema: Arc::clone(&empty_schema),
6567            })),
6568            empty_schema,
6569        );
6570        assert_snapshot!(p.unwrap_err().strip_backtrace(), @"Error during planning: Projection has mismatch between number of expressions (1) and number of fields in schema (0)");
6571        Ok(())
6572    }
6573
6574    fn test_plan() -> LogicalPlan {
6575        let schema = Schema::new(vec![
6576            Field::new("id", DataType::Int32, false),
6577            Field::new("state", DataType::Utf8, false),
6578        ]);
6579
6580        table_scan(TableReference::none(), &schema, Some(vec![0, 1]))
6581            .unwrap()
6582            .filter(col("state").eq(lit("CO")))
6583            .unwrap()
6584            .project(vec![col("id")])
6585            .unwrap()
6586            .build()
6587            .unwrap()
6588    }
6589
6590    #[test]
6591    fn min_rows_is_a_conservative_lower_bound() -> Result<()> {
6592        let no_rows = LogicalPlanBuilder::empty(false).build()?;
6593        let one_row = LogicalPlanBuilder::empty(true).build()?;
6594        assert_eq!(no_rows.min_rows(), 0);
6595        assert_eq!(no_rows.max_rows(), Some(0));
6596        assert_eq!(one_row.min_rows(), 1);
6597        assert_eq!(one_row.max_rows(), Some(1));
6598
6599        let projection = LogicalPlanBuilder::from(one_row.clone())
6600            .project(vec![lit(1)])?
6601            .build()?;
6602        assert_eq!(projection.min_rows(), 1);
6603
6604        let filter = LogicalPlanBuilder::from(projection.clone())
6605            .filter(lit(true))?
6606            .build()?;
6607        assert_eq!(filter.min_rows(), 0);
6608
6609        let aggregate = LogicalPlanBuilder::from(no_rows)
6610            .aggregate(Vec::<Expr>::new(), vec![count(lit(1))])?
6611            .build()?;
6612        assert_eq!(aggregate.min_rows(), 1);
6613
6614        let offset = LogicalPlanBuilder::from(projection.clone())
6615            .limit(1, None)?
6616            .build()?;
6617        assert_eq!(offset.min_rows(), 0);
6618
6619        let union = LogicalPlanBuilder::from(projection.clone())
6620            .union(projection)?
6621            .build()?;
6622        assert_eq!(union.min_rows(), 2);
6623        assert_eq!(
6624            LogicalPlanBuilder::from(union)
6625                .distinct()?
6626                .build()?
6627                .min_rows(),
6628            1
6629        );
6630
6631        let values =
6632            LogicalPlanBuilder::values(vec![vec![lit(1)], vec![lit(2)]])?.build()?;
6633        assert_eq!(values.min_rows(), 2);
6634
6635        let sort_key = col("column1").sort(true, false);
6636        let sort = LogicalPlanBuilder::from(values.clone())
6637            .sort(vec![sort_key.clone()])?
6638            .build()?;
6639        assert_eq!(sort.min_rows(), 2);
6640        let sort_with_fetch = LogicalPlanBuilder::from(values.clone())
6641            .sort_with_limit(vec![sort_key], Some(1))?
6642            .build()?;
6643        assert_eq!(sort_with_fetch.min_rows(), 1);
6644
6645        let limit = LogicalPlanBuilder::from(values.clone())
6646            .limit(1, Some(5))?
6647            .build()?;
6648        assert_eq!(limit.min_rows(), 1);
6649
6650        let grouped = LogicalPlanBuilder::from(values)
6651            .aggregate(vec![col("column1")], vec![count(lit(1))])?
6652            .build()?;
6653        assert_eq!(grouped.min_rows(), 0);
6654
6655        let scan = table_scan(Some("employee"), &employee_schema(), None)?.build()?;
6656        assert_eq!(scan.min_rows(), 0);
6657
6658        Ok(())
6659    }
6660
6661    #[test]
6662    fn min_rows_of_joins() -> Result<()> {
6663        let two_rows = LogicalPlanBuilder::values(vec![vec![lit(1)], vec![lit(2)]])?
6664            .alias("l")?
6665            .build()?;
6666        let one_row = LogicalPlanBuilder::values(vec![vec![lit(1)]])?
6667            .alias("r")?
6668            .build()?;
6669
6670        let cross_join = LogicalPlanBuilder::from(two_rows.clone())
6671            .cross_join(one_row.clone())?
6672            .build()?;
6673        assert_eq!(cross_join.min_rows(), 2);
6674
6675        let asof_join = LogicalPlanBuilder::from(two_rows.clone())
6676            .asof_join_on(
6677                one_row.clone(),
6678                None,
6679                col("l.column1").gt_eq(col("r.column1")),
6680            )?
6681            .build()?;
6682        assert_eq!(asof_join.min_rows(), 2);
6683
6684        for (join_type, expected_min_rows) in [
6685            // An inner join with a join condition may filter out every row,
6686            // while outer joins preserve the rows of the outer side(s).
6687            (JoinType::Inner, 0),
6688            (JoinType::Left, 2),
6689            (JoinType::Right, 1),
6690            (JoinType::Full, 2),
6691            (JoinType::LeftSemi, 0),
6692        ] {
6693            let join = LogicalPlanBuilder::from(two_rows.clone())
6694                .join_on(
6695                    one_row.clone(),
6696                    join_type,
6697                    [col("l.column1").eq(col("r.column1"))],
6698                )?
6699                .build()?;
6700            assert_eq!(join.min_rows(), expected_min_rows, "{join_type} join");
6701        }
6702
6703        Ok(())
6704    }
6705
6706    #[test]
6707    fn test_replace_invalid_placeholder() {
6708        // test empty placeholder
6709        let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
6710
6711        let plan = table_scan(TableReference::none(), &schema, None)
6712            .unwrap()
6713            .filter(col("id").eq(placeholder("")))
6714            .unwrap()
6715            .build()
6716            .unwrap();
6717
6718        let param_values = vec![ScalarValue::Int32(Some(42))];
6719        plan.replace_params_with_values(&param_values.clone().into())
6720            .expect_err("unexpectedly succeeded to replace an invalid placeholder");
6721
6722        // test $0 placeholder
6723        let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
6724
6725        let plan = table_scan(TableReference::none(), &schema, None)
6726            .unwrap()
6727            .filter(col("id").eq(placeholder("$0")))
6728            .unwrap()
6729            .build()
6730            .unwrap();
6731
6732        plan.replace_params_with_values(&param_values.clone().into())
6733            .expect_err("unexpectedly succeeded to replace an invalid placeholder");
6734
6735        // test $00 placeholder
6736        let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
6737
6738        let plan = table_scan(TableReference::none(), &schema, None)
6739            .unwrap()
6740            .filter(col("id").eq(placeholder("$00")))
6741            .unwrap()
6742            .build()
6743            .unwrap();
6744
6745        plan.replace_params_with_values(&param_values.into())
6746            .expect_err("unexpectedly succeeded to replace an invalid placeholder");
6747    }
6748
6749    #[test]
6750    fn test_replace_placeholder_mismatched_metadata() {
6751        let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
6752
6753        // Create a prepared statement with explicit fields that do not have metadata
6754        let plan = table_scan(TableReference::none(), &schema, None)
6755            .unwrap()
6756            .filter(col("id").eq(placeholder("$1")))
6757            .unwrap()
6758            .build()
6759            .unwrap();
6760        let prepared_builder = LogicalPlanBuilder::new(plan)
6761            .prepare(
6762                "".to_string(),
6763                vec![Field::new("", DataType::Int32, true).into()],
6764            )
6765            .unwrap();
6766
6767        // Attempt to bind a parameter with metadata
6768        let mut scalar_meta = HashMap::new();
6769        scalar_meta.insert("some_key".to_string(), "some_value".to_string());
6770        let param_values = ParamValues::List(vec![ScalarAndMetadata::new(
6771            ScalarValue::Int32(Some(42)),
6772            Some(scalar_meta.into()),
6773        )]);
6774        prepared_builder
6775            .plan()
6776            .clone()
6777            .with_param_values(param_values)
6778            .expect_err("prepared field metadata mismatch unexpectedly succeeded");
6779    }
6780
6781    #[test]
6782    fn test_replace_placeholder_empty_relation_valid_schema() {
6783        // SELECT $1, $2;
6784        let plan = LogicalPlanBuilder::empty(false)
6785            .project(vec![
6786                SelectExpr::from(placeholder("$1")),
6787                SelectExpr::from(placeholder("$2")),
6788            ])
6789            .unwrap()
6790            .build()
6791            .unwrap();
6792
6793        // original
6794        assert_snapshot!(plan.display_indent_schema(), @r"
6795        Projection: $1, $2 [$1:Null;N, $2:Null;N]
6796          EmptyRelation: rows=0 []
6797        ");
6798
6799        let plan = plan
6800            .with_param_values(vec![ScalarValue::from(1i32), ScalarValue::from("s")])
6801            .unwrap();
6802
6803        // replaced
6804        assert_snapshot!(plan.display_indent_schema(), @r#"
6805        Projection: Int32(1) AS $1, Utf8("s") AS $2 [$1:Int32, $2:Utf8]
6806          EmptyRelation: rows=0 []
6807        "#);
6808    }
6809
6810    #[test]
6811    fn test_nullable_schema_after_grouping_set() {
6812        let schema = Schema::new(vec![
6813            Field::new("foo", DataType::Int32, false),
6814            Field::new("bar", DataType::Int32, false),
6815        ]);
6816
6817        let plan = table_scan(TableReference::none(), &schema, None)
6818            .unwrap()
6819            .aggregate(
6820                vec![Expr::GroupingSet(GroupingSet::GroupingSets(vec![
6821                    vec![col("foo")],
6822                    vec![col("bar")],
6823                ]))],
6824                vec![count(lit(true))],
6825            )
6826            .unwrap()
6827            .build()
6828            .unwrap();
6829
6830        let output_schema = plan.schema();
6831
6832        assert!(
6833            output_schema
6834                .field_with_name(None, "foo")
6835                .unwrap()
6836                .is_nullable(),
6837        );
6838        assert!(
6839            output_schema
6840                .field_with_name(None, "bar")
6841                .unwrap()
6842                .is_nullable()
6843        );
6844    }
6845
6846    #[test]
6847    fn grouping_id_type_accounts_for_duplicate_ordinal_bits() {
6848        // 8 grouping columns fit in UInt8 when there are no duplicate ordinals,
6849        // but adding one duplicate ordinal bit widens the type to UInt16.
6850        assert_eq!(Aggregate::grouping_id_type(8, 0), DataType::UInt8);
6851        assert_eq!(Aggregate::grouping_id_type(8, 1), DataType::UInt16);
6852    }
6853
6854    #[test]
6855    fn test_filter_is_scalar() {
6856        // test empty placeholder
6857        let schema =
6858            Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
6859
6860        let source = Arc::new(LogicalTableSource::new(schema));
6861        let schema = Arc::new(
6862            DFSchema::try_from_qualified_schema(
6863                TableReference::bare("tab"),
6864                &source.schema(),
6865            )
6866            .unwrap(),
6867        );
6868        let scan = Arc::new(LogicalPlan::TableScan(TableScan {
6869            table_name: TableReference::bare("tab"),
6870            source: Arc::clone(&source) as Arc<dyn TableSource>,
6871            projection: None,
6872            projected_schema: Arc::clone(&schema),
6873            filters: vec![],
6874            fetch: None,
6875            skip: None,
6876            statistics_requests: Box::default(),
6877        }));
6878        let col = schema.field_names()[0].clone();
6879
6880        let filter = Filter::try_new(
6881            Expr::Column(col.into()).eq(Expr::Literal(ScalarValue::Int32(Some(1)), None)),
6882            scan,
6883        )
6884        .unwrap();
6885        assert!(!filter.is_scalar());
6886        let unique_schema = Arc::new(
6887            schema
6888                .as_ref()
6889                .clone()
6890                .with_functional_dependencies(
6891                    FunctionalDependencies::new_from_constraints(
6892                        Some(&Constraints::new_unverified(vec![Constraint::Unique(
6893                            vec![0],
6894                        )])),
6895                        1,
6896                    ),
6897                )
6898                .unwrap(),
6899        );
6900        let scan = Arc::new(LogicalPlan::TableScan(TableScan {
6901            table_name: TableReference::bare("tab"),
6902            source,
6903            projection: None,
6904            projected_schema: Arc::clone(&unique_schema),
6905            filters: vec![],
6906            fetch: None,
6907            skip: None,
6908            statistics_requests: Box::default(),
6909        }));
6910        let col = schema.field_names()[0].clone();
6911
6912        let filter =
6913            Filter::try_new(Expr::Column(col.into()).eq(lit(1i32)), scan).unwrap();
6914        assert!(filter.is_scalar());
6915    }
6916
6917    #[test]
6918    fn test_transform_explain() {
6919        let schema = Schema::new(vec![
6920            Field::new("foo", DataType::Int32, false),
6921            Field::new("bar", DataType::Int32, false),
6922        ]);
6923
6924        let plan = table_scan(TableReference::none(), &schema, None)
6925            .unwrap()
6926            .explain(false, false)
6927            .unwrap()
6928            .build()
6929            .unwrap();
6930
6931        let external_filter = col("foo").eq(lit(true));
6932
6933        // after transformation, because plan is not the same anymore,
6934        // the parent plan is built again with call to LogicalPlan::with_new_inputs -> with_new_exprs
6935        let plan = plan
6936            .transform(|plan| match plan {
6937                LogicalPlan::TableScan(table) => {
6938                    let filter = Filter::try_new(
6939                        external_filter.clone(),
6940                        Arc::new(LogicalPlan::TableScan(table)),
6941                    )
6942                    .unwrap();
6943                    Ok(Transformed::yes(LogicalPlan::Filter(filter)))
6944                }
6945                x => Ok(Transformed::no(x)),
6946            })
6947            .data()
6948            .unwrap();
6949
6950        let actual = format!("{}", plan.display_indent());
6951        assert_snapshot!(actual, @r"
6952        Explain
6953          Filter: foo = Boolean(true)
6954            TableScan: ?table?
6955        ")
6956    }
6957
6958    #[test]
6959    fn test_plan_partial_ord() {
6960        let empty_relation = LogicalPlan::EmptyRelation(EmptyRelation {
6961            produce_one_row: false,
6962            schema: Arc::new(DFSchema::empty()),
6963        });
6964
6965        let describe_table = LogicalPlan::Show(Show {
6966            kind: ShowKind::Describe {
6967                schema: Arc::new(Schema::new(vec![Field::new(
6968                    "foo",
6969                    DataType::Int32,
6970                    false,
6971                )])),
6972            },
6973            output_schema: DFSchemaRef::new(DFSchema::empty()),
6974        });
6975
6976        let describe_table_clone = LogicalPlan::Show(Show {
6977            kind: ShowKind::Describe {
6978                schema: Arc::new(Schema::new(vec![Field::new(
6979                    "foo",
6980                    DataType::Int32,
6981                    false,
6982                )])),
6983            },
6984            output_schema: DFSchemaRef::new(DFSchema::empty()),
6985        });
6986
6987        assert_eq!(
6988            empty_relation.partial_cmp(&describe_table),
6989            Some(Ordering::Less)
6990        );
6991        assert_eq!(
6992            describe_table.partial_cmp(&empty_relation),
6993            Some(Ordering::Greater)
6994        );
6995        assert_eq!(describe_table.partial_cmp(&describe_table_clone), None);
6996    }
6997
6998    #[test]
6999    fn test_limit_with_new_children() {
7000        let input = Arc::new(LogicalPlan::Values(Values {
7001            schema: Arc::new(DFSchema::empty()),
7002            values: vec![vec![]],
7003        }));
7004        let cases = [
7005            LogicalPlan::Limit(Limit {
7006                skip: None,
7007                fetch: None,
7008                input: Arc::clone(&input),
7009            }),
7010            LogicalPlan::Limit(Limit {
7011                skip: None,
7012                fetch: Some(Box::new(Expr::Literal(
7013                    ScalarValue::new_ten(&DataType::UInt32).unwrap(),
7014                    None,
7015                ))),
7016                input: Arc::clone(&input),
7017            }),
7018            LogicalPlan::Limit(Limit {
7019                skip: Some(Box::new(Expr::Literal(
7020                    ScalarValue::new_ten(&DataType::UInt32).unwrap(),
7021                    None,
7022                ))),
7023                fetch: None,
7024                input: Arc::clone(&input),
7025            }),
7026            LogicalPlan::Limit(Limit {
7027                skip: Some(Box::new(Expr::Literal(
7028                    ScalarValue::new_one(&DataType::UInt32).unwrap(),
7029                    None,
7030                ))),
7031                fetch: Some(Box::new(Expr::Literal(
7032                    ScalarValue::new_ten(&DataType::UInt32).unwrap(),
7033                    None,
7034                ))),
7035                input,
7036            }),
7037        ];
7038
7039        for limit in cases {
7040            let new_limit = limit
7041                .with_new_exprs(
7042                    limit.expressions(),
7043                    limit.inputs().into_iter().cloned().collect(),
7044                )
7045                .unwrap();
7046            assert_eq!(limit, new_limit);
7047        }
7048    }
7049
7050    #[test]
7051    fn test_with_subqueries_jump() {
7052        // The test plan contains a `Project` node above a `Filter` node, and the
7053        // `Project` node contains a subquery plan with a `Filter` root node, so returning
7054        // `TreeNodeRecursion::Jump` on `Project` should cause not visiting any of the
7055        // `Filter`s.
7056        let subquery_schema =
7057            Schema::new(vec![Field::new("sub_id", DataType::Int32, false)]);
7058
7059        let subquery_plan =
7060            table_scan(TableReference::none(), &subquery_schema, Some(vec![0]))
7061                .unwrap()
7062                .filter(col("sub_id").eq(lit(0)))
7063                .unwrap()
7064                .build()
7065                .unwrap();
7066
7067        let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
7068
7069        let plan = table_scan(TableReference::none(), &schema, Some(vec![0]))
7070            .unwrap()
7071            .filter(col("id").eq(lit(0)))
7072            .unwrap()
7073            .project(vec![col("id"), scalar_subquery(Arc::new(subquery_plan))])
7074            .unwrap()
7075            .build()
7076            .unwrap();
7077
7078        let mut filter_found = false;
7079        plan.apply_with_subqueries(|plan| {
7080            match plan {
7081                LogicalPlan::Projection(..) => return Ok(TreeNodeRecursion::Jump),
7082                LogicalPlan::Filter(..) => filter_found = true,
7083                _ => {}
7084            }
7085            Ok(TreeNodeRecursion::Continue)
7086        })
7087        .unwrap();
7088        assert!(!filter_found);
7089
7090        struct ProjectJumpVisitor {
7091            filter_found: bool,
7092        }
7093
7094        impl ProjectJumpVisitor {
7095            fn new() -> Self {
7096                Self {
7097                    filter_found: false,
7098                }
7099            }
7100        }
7101
7102        impl<'n> TreeNodeVisitor<'n> for ProjectJumpVisitor {
7103            type Node = LogicalPlan;
7104
7105            fn f_down(&mut self, node: &'n Self::Node) -> Result<TreeNodeRecursion> {
7106                match node {
7107                    LogicalPlan::Projection(..) => return Ok(TreeNodeRecursion::Jump),
7108                    LogicalPlan::Filter(..) => self.filter_found = true,
7109                    _ => {}
7110                }
7111                Ok(TreeNodeRecursion::Continue)
7112            }
7113        }
7114
7115        let mut visitor = ProjectJumpVisitor::new();
7116        plan.visit_with_subqueries(&mut visitor).unwrap();
7117        assert!(!visitor.filter_found);
7118
7119        let mut filter_found = false;
7120        plan.clone()
7121            .transform_down_with_subqueries(|plan| {
7122                match plan {
7123                    LogicalPlan::Projection(..) => {
7124                        return Ok(Transformed::new(
7125                            plan,
7126                            false,
7127                            TreeNodeRecursion::Jump,
7128                        ));
7129                    }
7130                    LogicalPlan::Filter(..) => filter_found = true,
7131                    _ => {}
7132                }
7133                Ok(Transformed::no(plan))
7134            })
7135            .unwrap();
7136        assert!(!filter_found);
7137
7138        let mut filter_found = false;
7139        plan.clone()
7140            .transform_down_up_with_subqueries(
7141                |plan| {
7142                    match plan {
7143                        LogicalPlan::Projection(..) => {
7144                            return Ok(Transformed::new(
7145                                plan,
7146                                false,
7147                                TreeNodeRecursion::Jump,
7148                            ));
7149                        }
7150                        LogicalPlan::Filter(..) => filter_found = true,
7151                        _ => {}
7152                    }
7153                    Ok(Transformed::no(plan))
7154                },
7155                |plan| Ok(Transformed::no(plan)),
7156            )
7157            .unwrap();
7158        assert!(!filter_found);
7159
7160        struct ProjectJumpRewriter {
7161            filter_found: bool,
7162        }
7163
7164        impl ProjectJumpRewriter {
7165            fn new() -> Self {
7166                Self {
7167                    filter_found: false,
7168                }
7169            }
7170        }
7171
7172        impl TreeNodeRewriter for ProjectJumpRewriter {
7173            type Node = LogicalPlan;
7174
7175            fn f_down(&mut self, node: Self::Node) -> Result<Transformed<Self::Node>> {
7176                match node {
7177                    LogicalPlan::Projection(..) => {
7178                        return Ok(Transformed::new(
7179                            node,
7180                            false,
7181                            TreeNodeRecursion::Jump,
7182                        ));
7183                    }
7184                    LogicalPlan::Filter(..) => self.filter_found = true,
7185                    _ => {}
7186                }
7187                Ok(Transformed::no(node))
7188            }
7189        }
7190
7191        let mut rewriter = ProjectJumpRewriter::new();
7192        plan.rewrite_with_subqueries(&mut rewriter).unwrap();
7193        assert!(!rewriter.filter_found);
7194    }
7195
7196    #[test]
7197    fn test_with_unresolved_placeholders() {
7198        let field_name = "id";
7199        let placeholder_value = "$1";
7200        let schema = Schema::new(vec![Field::new(field_name, DataType::Int32, false)]);
7201
7202        let plan = table_scan(TableReference::none(), &schema, None)
7203            .unwrap()
7204            .filter(col(field_name).eq(placeholder(placeholder_value)))
7205            .unwrap()
7206            .build()
7207            .unwrap();
7208
7209        // Check that the placeholder parameters have not received a DataType.
7210        let params = plan.get_parameter_fields().unwrap();
7211        assert_eq!(params.len(), 1);
7212
7213        let parameter_type = params.clone().get(placeholder_value).unwrap().clone();
7214        assert_eq!(parameter_type, None);
7215    }
7216
7217    #[test]
7218    fn test_join_with_new_exprs() -> Result<()> {
7219        fn create_test_join(
7220            on: Vec<(Expr, Expr)>,
7221            filter: Option<Expr>,
7222        ) -> Result<LogicalPlan> {
7223            let schema = Schema::new(vec![
7224                Field::new("a", DataType::Int32, false),
7225                Field::new("b", DataType::Int32, false),
7226            ]);
7227
7228            let left_schema = DFSchema::try_from_qualified_schema("t1", &schema)?;
7229            let right_schema = DFSchema::try_from_qualified_schema("t2", &schema)?;
7230
7231            Ok(LogicalPlan::Join(Join {
7232                left: Arc::new(
7233                    table_scan(Some("t1"), left_schema.as_arrow(), None)?.build()?,
7234                ),
7235                right: Arc::new(
7236                    table_scan(Some("t2"), right_schema.as_arrow(), None)?.build()?,
7237                ),
7238                on,
7239                filter,
7240                join_type: JoinType::Inner,
7241                join_constraint: JoinConstraint::On,
7242                schema: Arc::new(left_schema.join(&right_schema)?),
7243                null_equality: NullEquality::NullEqualsNothing,
7244                null_aware: false,
7245                null_aware_value_keys: 0,
7246            }))
7247        }
7248
7249        {
7250            let join = create_test_join(vec![(col("t1.a"), (col("t2.a")))], None)?;
7251            let LogicalPlan::Join(join) = join.with_new_exprs(
7252                join.expressions(),
7253                join.inputs().into_iter().cloned().collect(),
7254            )?
7255            else {
7256                unreachable!()
7257            };
7258            assert_eq!(join.on, vec![(col("t1.a"), (col("t2.a")))]);
7259            assert_eq!(join.filter, None);
7260        }
7261
7262        {
7263            let join = create_test_join(vec![], Some(col("t1.a").gt(col("t2.a"))))?;
7264            let LogicalPlan::Join(join) = join.with_new_exprs(
7265                join.expressions(),
7266                join.inputs().into_iter().cloned().collect(),
7267            )?
7268            else {
7269                unreachable!()
7270            };
7271            assert_eq!(join.on, vec![]);
7272            assert_eq!(join.filter, Some(col("t1.a").gt(col("t2.a"))));
7273        }
7274
7275        {
7276            let join = create_test_join(
7277                vec![(col("t1.a"), (col("t2.a")))],
7278                Some(col("t1.b").gt(col("t2.b"))),
7279            )?;
7280            let LogicalPlan::Join(join) = join.with_new_exprs(
7281                join.expressions(),
7282                join.inputs().into_iter().cloned().collect(),
7283            )?
7284            else {
7285                unreachable!()
7286            };
7287            assert_eq!(join.on, vec![(col("t1.a"), (col("t2.a")))]);
7288            assert_eq!(join.filter, Some(col("t1.b").gt(col("t2.b"))));
7289        }
7290
7291        {
7292            let join = create_test_join(
7293                vec![(col("t1.a"), (col("t2.a"))), (col("t1.b"), (col("t2.b")))],
7294                None,
7295            )?;
7296            let LogicalPlan::Join(join) = join.with_new_exprs(
7297                vec![
7298                    binary_expr(col("t1.a"), Operator::Plus, lit(1)),
7299                    binary_expr(col("t2.a"), Operator::Plus, lit(2)),
7300                    col("t1.b"),
7301                    col("t2.b"),
7302                    lit(true),
7303                ],
7304                join.inputs().into_iter().cloned().collect(),
7305            )?
7306            else {
7307                unreachable!()
7308            };
7309            assert_eq!(
7310                join.on,
7311                vec![
7312                    (
7313                        binary_expr(col("t1.a"), Operator::Plus, lit(1)),
7314                        binary_expr(col("t2.a"), Operator::Plus, lit(2))
7315                    ),
7316                    (col("t1.b"), (col("t2.b")))
7317                ]
7318            );
7319            assert_eq!(join.filter, Some(lit(true)));
7320        }
7321
7322        Ok(())
7323    }
7324
7325    #[test]
7326    fn test_join_try_new() -> Result<()> {
7327        let schema = Schema::new(vec![
7328            Field::new("a", DataType::Int32, false),
7329            Field::new("b", DataType::Int32, false),
7330        ]);
7331
7332        let left_scan = table_scan(Some("t1"), &schema, None)?.build()?;
7333
7334        let right_scan = table_scan(Some("t2"), &schema, None)?.build()?;
7335
7336        let join_types = vec![
7337            JoinType::Inner,
7338            JoinType::Left,
7339            JoinType::Right,
7340            JoinType::Full,
7341            JoinType::LeftSemi,
7342            JoinType::LeftAnti,
7343            JoinType::RightSemi,
7344            JoinType::RightAnti,
7345            JoinType::LeftMark,
7346        ];
7347
7348        for join_type in join_types {
7349            let join = Join::try_new(
7350                Arc::new(left_scan.clone()),
7351                Arc::new(right_scan.clone()),
7352                vec![(col("t1.a"), col("t2.a"))],
7353                Some(col("t1.b").gt(col("t2.b"))),
7354                join_type,
7355                JoinConstraint::On,
7356                NullEquality::NullEqualsNothing,
7357                false,
7358            )?;
7359
7360            match join_type {
7361                JoinType::LeftSemi | JoinType::LeftAnti => {
7362                    assert_eq!(join.schema.fields().len(), 2);
7363
7364                    let fields = join.schema.fields();
7365                    assert_eq!(
7366                        fields[0].name(),
7367                        "a",
7368                        "First field should be 'a' from left table"
7369                    );
7370                    assert_eq!(
7371                        fields[1].name(),
7372                        "b",
7373                        "Second field should be 'b' from left table"
7374                    );
7375                }
7376                JoinType::RightSemi | JoinType::RightAnti => {
7377                    assert_eq!(join.schema.fields().len(), 2);
7378
7379                    let fields = join.schema.fields();
7380                    assert_eq!(
7381                        fields[0].name(),
7382                        "a",
7383                        "First field should be 'a' from right table"
7384                    );
7385                    assert_eq!(
7386                        fields[1].name(),
7387                        "b",
7388                        "Second field should be 'b' from right table"
7389                    );
7390                }
7391                JoinType::LeftMark => {
7392                    assert_eq!(join.schema.fields().len(), 3);
7393
7394                    let fields = join.schema.fields();
7395                    assert_eq!(
7396                        fields[0].name(),
7397                        "a",
7398                        "First field should be 'a' from left table"
7399                    );
7400                    assert_eq!(
7401                        fields[1].name(),
7402                        "b",
7403                        "Second field should be 'b' from left table"
7404                    );
7405                    assert_eq!(
7406                        fields[2].name(),
7407                        "mark",
7408                        "Third field should be the mark column"
7409                    );
7410
7411                    assert!(!fields[0].is_nullable());
7412                    assert!(!fields[1].is_nullable());
7413                    // The mark column is always nullable: null-aware `LeftMark`
7414                    // joins use NULL to represent SQL UNKNOWN for `NOT IN`.
7415                    assert!(fields[2].is_nullable());
7416                }
7417                _ => {
7418                    assert_eq!(join.schema.fields().len(), 4);
7419
7420                    let fields = join.schema.fields();
7421                    assert_eq!(
7422                        fields[0].name(),
7423                        "a",
7424                        "First field should be 'a' from left table"
7425                    );
7426                    assert_eq!(
7427                        fields[1].name(),
7428                        "b",
7429                        "Second field should be 'b' from left table"
7430                    );
7431                    assert_eq!(
7432                        fields[2].name(),
7433                        "a",
7434                        "Third field should be 'a' from right table"
7435                    );
7436                    assert_eq!(
7437                        fields[3].name(),
7438                        "b",
7439                        "Fourth field should be 'b' from right table"
7440                    );
7441
7442                    if join_type == JoinType::Left {
7443                        // Left side fields (first two) shouldn't be nullable
7444                        assert!(!fields[0].is_nullable());
7445                        assert!(!fields[1].is_nullable());
7446                        // Right side fields (third and fourth) should be nullable
7447                        assert!(fields[2].is_nullable());
7448                        assert!(fields[3].is_nullable());
7449                    } else if join_type == JoinType::Right {
7450                        // Left side fields (first two) should be nullable
7451                        assert!(fields[0].is_nullable());
7452                        assert!(fields[1].is_nullable());
7453                        // Right side fields (third and fourth) shouldn't be nullable
7454                        assert!(!fields[2].is_nullable());
7455                        assert!(!fields[3].is_nullable());
7456                    } else if join_type == JoinType::Full {
7457                        assert!(fields[0].is_nullable());
7458                        assert!(fields[1].is_nullable());
7459                        assert!(fields[2].is_nullable());
7460                        assert!(fields[3].is_nullable());
7461                    }
7462                }
7463            }
7464
7465            assert_eq!(join.on, vec![(col("t1.a"), col("t2.a"))]);
7466            assert_eq!(join.filter, Some(col("t1.b").gt(col("t2.b"))));
7467            assert_eq!(join.join_type, join_type);
7468            assert_eq!(join.join_constraint, JoinConstraint::On);
7469            assert_eq!(join.null_equality, NullEquality::NullEqualsNothing);
7470        }
7471
7472        Ok(())
7473    }
7474
7475    #[test]
7476    fn test_join_try_new_with_using_constraint_and_overlapping_columns() -> Result<()> {
7477        let left_schema = Schema::new(vec![
7478            Field::new("id", DataType::Int32, false), // Common column in both tables
7479            Field::new("name", DataType::Utf8, false), // Unique to left
7480            Field::new("value", DataType::Int32, false), // Common column, different meaning
7481        ]);
7482
7483        let right_schema = Schema::new(vec![
7484            Field::new("id", DataType::Int32, false), // Common column in both tables
7485            Field::new("category", DataType::Utf8, false), // Unique to right
7486            Field::new("value", DataType::Float64, true), // Common column, different meaning
7487        ]);
7488
7489        let left_plan = table_scan(Some("t1"), &left_schema, None)?.build()?;
7490
7491        let right_plan = table_scan(Some("t2"), &right_schema, None)?.build()?;
7492
7493        // Test 1: USING constraint with a common column
7494        {
7495            // In the logical plan, both copies of the `id` column are preserved
7496            // The USING constraint is handled later during physical execution, where the common column appears once
7497            let join = Join::try_new(
7498                Arc::new(left_plan.clone()),
7499                Arc::new(right_plan.clone()),
7500                vec![(col("t1.id"), col("t2.id"))],
7501                None,
7502                JoinType::Inner,
7503                JoinConstraint::Using,
7504                NullEquality::NullEqualsNothing,
7505                false,
7506            )?;
7507
7508            let fields = join.schema.fields();
7509
7510            assert_eq!(fields.len(), 6);
7511
7512            assert_eq!(
7513                fields[0].name(),
7514                "id",
7515                "First field should be 'id' from left table"
7516            );
7517            assert_eq!(
7518                fields[1].name(),
7519                "name",
7520                "Second field should be 'name' from left table"
7521            );
7522            assert_eq!(
7523                fields[2].name(),
7524                "value",
7525                "Third field should be 'value' from left table"
7526            );
7527            assert_eq!(
7528                fields[3].name(),
7529                "id",
7530                "Fourth field should be 'id' from right table"
7531            );
7532            assert_eq!(
7533                fields[4].name(),
7534                "category",
7535                "Fifth field should be 'category' from right table"
7536            );
7537            assert_eq!(
7538                fields[5].name(),
7539                "value",
7540                "Sixth field should be 'value' from right table"
7541            );
7542
7543            assert_eq!(join.join_constraint, JoinConstraint::Using);
7544        }
7545
7546        // Test 2: Complex join condition with expressions
7547        {
7548            // Complex condition: join on id equality AND where left.value < right.value
7549            let join = Join::try_new(
7550                Arc::new(left_plan.clone()),
7551                Arc::new(right_plan.clone()),
7552                vec![(col("t1.id"), col("t2.id"))], // Equijoin condition
7553                Some(col("t1.value").lt(col("t2.value"))), // Non-equi filter condition
7554                JoinType::Inner,
7555                JoinConstraint::On,
7556                NullEquality::NullEqualsNothing,
7557                false,
7558            )?;
7559
7560            let fields = join.schema.fields();
7561            assert_eq!(fields.len(), 6);
7562
7563            assert_eq!(
7564                fields[0].name(),
7565                "id",
7566                "First field should be 'id' from left table"
7567            );
7568            assert_eq!(
7569                fields[1].name(),
7570                "name",
7571                "Second field should be 'name' from left table"
7572            );
7573            assert_eq!(
7574                fields[2].name(),
7575                "value",
7576                "Third field should be 'value' from left table"
7577            );
7578            assert_eq!(
7579                fields[3].name(),
7580                "id",
7581                "Fourth field should be 'id' from right table"
7582            );
7583            assert_eq!(
7584                fields[4].name(),
7585                "category",
7586                "Fifth field should be 'category' from right table"
7587            );
7588            assert_eq!(
7589                fields[5].name(),
7590                "value",
7591                "Sixth field should be 'value' from right table"
7592            );
7593
7594            assert_eq!(join.filter, Some(col("t1.value").lt(col("t2.value"))));
7595        }
7596
7597        // Test 3: Join with null equality behavior set to true
7598        {
7599            let join = Join::try_new(
7600                Arc::new(left_plan.clone()),
7601                Arc::new(right_plan.clone()),
7602                vec![(col("t1.id"), col("t2.id"))],
7603                None,
7604                JoinType::Inner,
7605                JoinConstraint::On,
7606                NullEquality::NullEqualsNull,
7607                false,
7608            )?;
7609
7610            assert_eq!(join.null_equality, NullEquality::NullEqualsNull);
7611        }
7612
7613        Ok(())
7614    }
7615
7616    #[test]
7617    fn test_asof_using_preserves_qualified_keys() -> Result<()> {
7618        let schema = Schema::new(vec![
7619            Field::new("id", DataType::Int32, false),
7620            Field::new("ts", DataType::Int64, false),
7621        ]);
7622        let left = Arc::new(table_scan(Some("t1"), &schema, None)?.build()?);
7623        let right = Arc::new(table_scan(Some("t2"), &schema, None)?.build()?);
7624        let join = AsOfJoin::try_new(
7625            left,
7626            right,
7627            vec![(col("t1.id"), col("t2.id"))],
7628            AsOfMatch::new(col("t1.ts"), Operator::GtEq, col("t2.ts")),
7629            JoinConstraint::Using,
7630        )?;
7631
7632        assert_eq!(join.schema.fields().len(), 4);
7633        assert_eq!(
7634            join.schema
7635                .index_of_column(&Column::from_qualified_name("t2.id"))?,
7636            2
7637        );
7638        assert!(join.schema.field(2).is_nullable());
7639        Ok(())
7640    }
7641
7642    #[test]
7643    fn test_join_try_new_schema_validation() -> Result<()> {
7644        let left_schema = Schema::new(vec![
7645            Field::new("id", DataType::Int32, false),
7646            Field::new("name", DataType::Utf8, false),
7647            Field::new("value", DataType::Float64, true),
7648        ]);
7649
7650        let right_schema = Schema::new(vec![
7651            Field::new("id", DataType::Int32, false),
7652            Field::new("category", DataType::Utf8, true),
7653            Field::new("code", DataType::Int16, false),
7654        ]);
7655
7656        let left_plan = table_scan(Some("t1"), &left_schema, None)?.build()?;
7657
7658        let right_plan = table_scan(Some("t2"), &right_schema, None)?.build()?;
7659
7660        let join_types = vec![
7661            JoinType::Inner,
7662            JoinType::Left,
7663            JoinType::Right,
7664            JoinType::Full,
7665        ];
7666
7667        for join_type in join_types {
7668            let join = Join::try_new(
7669                Arc::new(left_plan.clone()),
7670                Arc::new(right_plan.clone()),
7671                vec![(col("t1.id"), col("t2.id"))],
7672                Some(col("t1.value").gt(lit(5.0))),
7673                join_type,
7674                JoinConstraint::On,
7675                NullEquality::NullEqualsNothing,
7676                false,
7677            )?;
7678
7679            let fields = join.schema.fields();
7680            assert_eq!(fields.len(), 6, "Expected 6 fields for {join_type} join");
7681
7682            for (i, field) in fields.iter().enumerate() {
7683                let expected_nullable = match (i, &join_type) {
7684                    // Left table fields (indices 0, 1, 2)
7685                    (0, JoinType::Right | JoinType::Full) => true, // id becomes nullable in RIGHT/FULL
7686                    (1, JoinType::Right | JoinType::Full) => true, // name becomes nullable in RIGHT/FULL
7687                    (2, _) => true, // value is already nullable
7688
7689                    // Right table fields (indices 3, 4, 5)
7690                    (3, JoinType::Left | JoinType::Full) => true, // id becomes nullable in LEFT/FULL
7691                    (4, _) => true, // category is already nullable
7692                    (5, JoinType::Left | JoinType::Full) => true, // code becomes nullable in LEFT/FULL
7693
7694                    _ => false,
7695                };
7696
7697                assert_eq!(
7698                    field.is_nullable(),
7699                    expected_nullable,
7700                    "Field {} ({}) nullability incorrect for {:?} join",
7701                    i,
7702                    field.name(),
7703                    join_type
7704                );
7705            }
7706        }
7707
7708        let using_join = Join::try_new(
7709            Arc::new(left_plan.clone()),
7710            Arc::new(right_plan.clone()),
7711            vec![(col("t1.id"), col("t2.id"))],
7712            None,
7713            JoinType::Inner,
7714            JoinConstraint::Using,
7715            NullEquality::NullEqualsNothing,
7716            false,
7717        )?;
7718
7719        assert_eq!(
7720            using_join.schema.fields().len(),
7721            6,
7722            "USING join should have all fields"
7723        );
7724        assert_eq!(using_join.join_constraint, JoinConstraint::Using);
7725
7726        Ok(())
7727    }
7728
7729    #[test]
7730    fn test_unnest_with_new_exprs_accepts_expressions() -> Result<()> {
7731        use crate::LogicalPlanBuilder;
7732        use arrow::datatypes::{DataType, Field, Schema};
7733
7734        let schema = Schema::new(vec![
7735            Field::new("list_col", DataType::new_list(DataType::Int32, true), true),
7736            Field::new("other_col", DataType::Int32, true),
7737        ]);
7738        let plan = table_scan(Some("t"), &schema, None)?.build()?;
7739        let unnest_plan = LogicalPlanBuilder::from(plan)
7740            .unnest_column("list_col")?
7741            .build()?;
7742
7743        let exprs = unnest_plan.expressions();
7744        assert!(!exprs.is_empty(), "Unnest should expose exec_columns");
7745        assert_eq!(exprs.len(), 1);
7746        assert!(matches!(&exprs[0], Expr::Column(c) if c.name == "list_col"));
7747
7748        let inputs: Vec<LogicalPlan> =
7749            unnest_plan.inputs().into_iter().cloned().collect();
7750        let rebuilt = unnest_plan.with_new_exprs(exprs, inputs)?;
7751        assert_eq!(rebuilt.schema(), unnest_plan.schema());
7752
7753        Ok(())
7754    }
7755
7756    #[test]
7757    fn test_unnest_with_new_exprs_empty_preserves_columns() -> Result<()> {
7758        use crate::LogicalPlanBuilder;
7759        use arrow::datatypes::{DataType, Field, Schema};
7760
7761        let schema = Schema::new(vec![
7762            Field::new("list_col", DataType::new_list(DataType::Int32, true), true),
7763            Field::new("other_col", DataType::Int32, true),
7764        ]);
7765        let plan = table_scan(Some("t"), &schema, None)?.build()?;
7766        let unnest_plan = LogicalPlanBuilder::from(plan)
7767            .unnest_column("list_col")?
7768            .build()?;
7769
7770        let inputs: Vec<LogicalPlan> =
7771            unnest_plan.inputs().into_iter().cloned().collect();
7772        let rebuilt = unnest_plan.with_new_exprs(vec![], inputs)?;
7773        assert_eq!(rebuilt.schema(), unnest_plan.schema());
7774
7775        Ok(())
7776    }
7777
7778    #[test]
7779    fn union_infers_types_without_rewriting_inputs() -> Result<()> {
7780        let input = |data_type, nullable, source: &str| {
7781            table_scan(
7782                Some(source),
7783                &Schema::new(vec![
7784                    Field::new("x", data_type, nullable)
7785                        .with_metadata(Metadata::new().with("source", source)),
7786                ]),
7787                None,
7788            )?
7789            .build()
7790            .map(Arc::new)
7791        };
7792        let left = input(DataType::Int16, false, "left")?;
7793        let right = input(DataType::Int64, true, "right")?;
7794        let inputs = vec![Arc::clone(&left), Arc::clone(&right)];
7795        let union = Union::try_new_with_loose_types(inputs.clone())?;
7796        assert_eq!(union.inputs, inputs);
7797        assert_eq!(union.schema.field(0).name(), "x");
7798        assert_eq!(union.schema.field(0).data_type(), &DataType::Int64);
7799        assert!(union.schema.field(0).is_nullable());
7800        assert_eq!(
7801            union
7802                .schema
7803                .field(0)
7804                .metadata()
7805                .get("source")
7806                .map(String::as_str),
7807            Some("right")
7808        );
7809        assert!(Union::try_new(inputs.clone()).is_err());
7810        assert!(Union::try_new_with_loose_types(vec![Arc::clone(&left)]).is_err());
7811
7812        // Keep the original type when a later input prevents builtin inference.
7813        // A custom analyzer can still resolve the raw inputs without earlier casts.
7814        let incompatible = input(DataType::Boolean, false, "third")?;
7815        let inputs = vec![left, right, incompatible];
7816        for union in [
7817            Union::try_new_with_loose_types(inputs.clone())?,
7818            Union::try_new_by_name(inputs)?,
7819        ] {
7820            assert_eq!(union.schema.field(0).data_type(), &DataType::Int16);
7821        }
7822        Ok(())
7823    }
7824}