Skip to main content

datafusion_expr/logical_plan/
builder.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//! This module provides a builder for creating LogicalPlans
6
7use std::borrow::Cow;
8use std::cmp::Ordering;
9use std::collections::{HashMap, HashSet};
10use std::iter::once;
11use std::sync::Arc;
12
13use crate::dml::CopyTo;
14use crate::expr::{Alias, PlannedReplaceSelectItem, Sort as SortExpr};
15use crate::expr_rewriter::{
16    ColumnNormalizer, coerce_plan_expr_for_schema, normalize_col,
17    normalize_col_with_schemas_and_ambiguity_check, normalize_cols, normalize_sorts,
18    rewrite_sort_cols_by_aggs,
19};
20use crate::logical_plan::{
21    Aggregate, Analyze, AsOfJoin, AsOfMatch, Distinct, DistinctOn, EmptyRelation,
22    Explain, Filter, Join, JoinConstraint, JoinType, Limit, LogicalPlan, Partitioning,
23    PlanType, Prepare, Projection, Repartition, Show, ShowKind, Sort, SubqueryAlias,
24    TableScanBuilder, Union, Unnest, Values, Window,
25};
26use crate::select_expr::SelectExpr;
27use crate::utils::{
28    Columnizer, can_hash, check_all_columns_from_schema, compare_sort_expr,
29    expand_qualified_wildcard, expand_wildcard, expr_to_columns,
30    find_valid_equijoin_key_pair, group_window_expr_by_sort_keys,
31    passthrough_field_index, split_conjunction_owned,
32};
33use crate::{
34    BinaryExpr, DmlStatement, ExplainOption, Expr, ExprSchemable, Operator,
35    RecursiveQuery, Statement, TableProviderFilterPushDown, TableScan, TableSource,
36    WriteOp, and, binary_expr, lit,
37};
38
39use super::dml::InsertOp;
40use crate::logical_plan::information_schema::ColumnsDetail;
41use arrow::compute::can_cast_types;
42use arrow::datatypes::{DataType, Field, FieldRef, Fields, Schema, SchemaRef};
43use datafusion_common::display::ToStringifiedPlan;
44use datafusion_common::file_options::file_type::FileType;
45use datafusion_common::metadata::FieldMetadata;
46use datafusion_common::{
47    Column, Constraints, DFSchema, DFSchemaRef, FunctionalDependencies, NullEquality,
48    Result, ScalarValue, TableReference, ToDFSchema, UnnestOptions, exec_err,
49    get_target_functional_dependencies, internal_datafusion_err, plan_datafusion_err,
50    plan_err,
51};
52use datafusion_expr_common::type_coercion::binary::{
53    type_union_coercion, type_union_resolution,
54};
55
56use indexmap::IndexSet;
57
58/// Default table name for unnamed table
59pub const UNNAMED_TABLE: &str = "?table?";
60
61/// Options for [`LogicalPlanBuilder`]
62#[derive(Default, Debug, Clone)]
63pub struct LogicalPlanBuilderOptions {
64    /// Flag indicating whether the plan builder should add
65    /// functionally dependent expressions as additional aggregation groupings.
66    add_implicit_group_by_exprs: bool,
67}
68
69impl LogicalPlanBuilderOptions {
70    pub fn new() -> Self {
71        Default::default()
72    }
73
74    /// Should the builder add functionally dependent expressions as additional aggregation groupings.
75    pub fn with_add_implicit_group_by_exprs(mut self, add: bool) -> Self {
76        self.add_implicit_group_by_exprs = add;
77        self
78    }
79}
80
81fn recursive_type_can_be_coerced(from: &DataType, into: &DataType) -> bool {
82    if from == into || *from == DataType::Null {
83        return true;
84    }
85    // Preserve the integer coercion supported by recursive queries since #9794.
86    if from.is_integer() && into.is_integer() {
87        return true;
88    }
89    if matches!(
90        (from, into),
91        (DataType::Date32, DataType::Date64)
92            | (DataType::Utf8, DataType::LargeUtf8 | DataType::Utf8View)
93            | (DataType::LargeUtf8, DataType::Utf8View)
94            | (
95                DataType::Binary,
96                DataType::LargeBinary | DataType::BinaryView
97            )
98            | (DataType::LargeBinary, DataType::BinaryView)
99            | (
100                DataType::FixedSizeBinary(_),
101                DataType::Binary | DataType::BinaryView
102            )
103    ) {
104        return true;
105    }
106    // Compound types and changes of type category need an explicit seed type.
107    // UNION's common-type rules can hide lossy casts within nested fields.
108    if !from.is_numeric() || !into.is_numeric() {
109        return false;
110    }
111    // The decimal range/scale checks below are more precise than UNION coercion,
112    // which reserves 20 digits for Int64 even though its values fit in 19.
113    if !into.is_decimal() && type_union_coercion(into, from).as_ref() != Some(into) {
114        return false;
115    }
116
117    match (from, into) {
118        (
119            DataType::Int16
120            | DataType::UInt16
121            | DataType::Int32
122            | DataType::UInt32
123            | DataType::Int64
124            | DataType::UInt64,
125            DataType::Float16,
126        )
127        | (
128            DataType::Int32 | DataType::UInt32 | DataType::Int64 | DataType::UInt64,
129            DataType::Float32,
130        )
131        | (DataType::Int64 | DataType::UInt64, DataType::Float64) => false,
132        (from, into) if from.is_decimal() && into.is_floating() => false,
133        (from, into) if into.is_decimal() => {
134            if from.is_floating() {
135                return false;
136            }
137            let Some((into_precision, into_scale)) = decimal_precision_scale(into) else {
138                return false;
139            };
140            let from_precision_scale = match from {
141                DataType::Int8 | DataType::UInt8 => Some((3, 0)),
142                DataType::Int16 | DataType::UInt16 => Some((5, 0)),
143                DataType::Int32 | DataType::UInt32 => Some((10, 0)),
144                DataType::Int64 => Some((19, 0)),
145                DataType::UInt64 => Some((20, 0)),
146                _ => decimal_precision_scale(from),
147            };
148            let Some((from_precision, from_scale)) = from_precision_scale else {
149                return false;
150            };
151            into_scale >= from_scale
152                && into_precision - into_scale >= from_precision - from_scale
153        }
154        _ => true,
155    }
156}
157
158fn decimal_precision_scale(data_type: &DataType) -> Option<(i16, i16)> {
159    match data_type {
160        DataType::Decimal32(precision, scale)
161        | DataType::Decimal64(precision, scale)
162        | DataType::Decimal128(precision, scale)
163        | DataType::Decimal256(precision, scale) => {
164            Some((*precision as i16, *scale as i16))
165        }
166        _ => None,
167    }
168}
169
170/// Builder for logical plans
171///
172/// # Example building a simple plan
173/// ```
174/// # use datafusion_expr::{lit, col, LogicalPlanBuilder, logical_plan::table_scan};
175/// # use datafusion_common::Result;
176/// # use arrow::datatypes::{Schema, DataType, Field};
177/// #
178/// # fn main() -> Result<()> {
179/// #
180/// # fn employee_schema() -> Schema {
181/// #    Schema::new(vec![
182/// #           Field::new("id", DataType::Int32, false),
183/// #           Field::new("first_name", DataType::Utf8, false),
184/// #           Field::new("last_name", DataType::Utf8, false),
185/// #           Field::new("state", DataType::Utf8, false),
186/// #           Field::new("salary", DataType::Int32, false),
187/// #       ])
188/// #   }
189/// #
190/// // Create a plan similar to
191/// // SELECT last_name
192/// // FROM employees
193/// // WHERE salary < 1000
194/// let plan = table_scan(Some("employee"), &employee_schema(), None)?
195///  // Keep only rows where salary < 1000
196///  .filter(col("salary").lt(lit(1000)))?
197///  // only show "last_name" in the final results
198///  .project(vec![col("last_name")])?
199///  .build()?;
200///
201/// // Convert from plan back to builder
202/// let builder = LogicalPlanBuilder::from(plan);
203///
204/// # Ok(())
205/// # }
206/// ```
207#[derive(Debug, Clone)]
208pub struct LogicalPlanBuilder {
209    plan: Arc<LogicalPlan>,
210    options: LogicalPlanBuilderOptions,
211}
212
213impl LogicalPlanBuilder {
214    /// Create a builder from an existing plan
215    pub fn new(plan: LogicalPlan) -> Self {
216        Self {
217            plan: Arc::new(plan),
218            options: LogicalPlanBuilderOptions::default(),
219        }
220    }
221
222    /// Create a builder from an existing plan
223    pub fn new_from_arc(plan: Arc<LogicalPlan>) -> Self {
224        Self {
225            plan,
226            options: LogicalPlanBuilderOptions::default(),
227        }
228    }
229
230    pub fn with_options(mut self, options: LogicalPlanBuilderOptions) -> Self {
231        self.options = options;
232        self
233    }
234
235    /// Return the output schema of the plan build so far
236    pub fn schema(&self) -> &DFSchemaRef {
237        self.plan.schema()
238    }
239
240    /// Return the LogicalPlan of the plan build so far
241    pub fn plan(&self) -> &LogicalPlan {
242        &self.plan
243    }
244
245    /// Create an empty relation.
246    ///
247    /// `produce_one_row` set to true means this empty node needs to produce a placeholder row.
248    pub fn empty(produce_one_row: bool) -> Self {
249        Self::new(LogicalPlan::EmptyRelation(EmptyRelation {
250            produce_one_row,
251            schema: DFSchemaRef::new(DFSchema::empty()),
252        }))
253    }
254
255    /// Create a `DESCRIBE <query>` plan, where `schema` is the output schema of the query.
256    pub fn describe(schema: Arc<Schema>) -> Result<Self> {
257        Self::show(
258            ShowKind::Describe { schema },
259            crate::information_schema::columns_schema(ColumnsDetail::Describe),
260        )
261    }
262
263    /// Create a `SHOW TABLES` plan.
264    pub fn show_tables() -> Result<Self> {
265        Self::show(ShowKind::Tables, crate::information_schema::tables_schema())
266    }
267
268    /// Create a `DESCRIBE <table>` or `SHOW [FULL|EXTENDED] COLUMNS FROM <table>` plan.
269    pub fn show_columns(
270        table_ref: TableReference,
271        detail: ColumnsDetail,
272    ) -> Result<Self> {
273        Self::show(
274            ShowKind::Columns { table_ref, detail },
275            crate::information_schema::columns_schema(detail),
276        )
277    }
278
279    /// Create a `SHOW CREATE TABLE <table>` plan.
280    pub fn show_create_table(table_ref: TableReference) -> Result<Self> {
281        Self::show(
282            ShowKind::CreateTable { table_ref },
283            crate::information_schema::views_schema(),
284        )
285    }
286
287    /// Create a `SHOW <variable>` / `SHOW ALL` plan. `name` is `None` for
288    /// `SHOW ALL`.
289    pub fn show_variables(name: Option<String>, verbose: bool) -> Result<Self> {
290        Self::show(
291            ShowKind::Variables { name, verbose },
292            crate::information_schema::df_settings_schema(verbose),
293        )
294    }
295
296    /// Create a `SHOW FUNCTIONS [LIKE <pattern>]` plan.
297    pub fn show_functions(filter: Option<String>) -> Result<Self> {
298        Self::show(
299            ShowKind::Functions { filter },
300            crate::information_schema::show_functions_schema(),
301        )
302    }
303
304    /// Shared helper for the `SHOW`-class factory methods above.
305    fn show(kind: ShowKind, output_schema: Schema) -> Result<Self> {
306        Ok(Self::new(LogicalPlan::Show(Show {
307            kind,
308            output_schema: Arc::new(DFSchema::try_from(output_schema)?),
309        })))
310    }
311
312    /// Convert a regular plan into a recursive query.
313    /// `is_distinct` indicates whether the recursive term should be de-duplicated (`UNION`) after each iteration or not (`UNION ALL`).
314    pub fn to_recursive_query(
315        self,
316        name: String,
317        recursive_term: LogicalPlan,
318        is_distinct: bool,
319    ) -> Result<Self> {
320        // Ensure that the static term and the recursive term have the same number of fields
321        let static_fields_len = self.plan.schema().fields().len();
322        let recursive_fields_len = recursive_term.schema().fields().len();
323        if static_fields_len != recursive_fields_len {
324            return plan_err!(
325                "Non-recursive term and recursive term must have the same number of columns ({} != {})",
326                static_fields_len,
327                recursive_fields_len
328            );
329        }
330        for (index, (static_field, recursive_field)) in self
331            .plan
332            .schema()
333            .fields()
334            .iter()
335            .zip(recursive_term.schema().fields())
336            .enumerate()
337        {
338            let static_type = static_field.data_type();
339            let recursive_type = recursive_field.data_type();
340            if !recursive_type_can_be_coerced(recursive_type, static_type) {
341                return plan_err!(
342                    "Recursive CTE '{name}' column {} has type {static_type} in the non-recursive term but {recursive_type} in the recursive term; cast the non-recursive term to the intended type",
343                    index + 1
344                );
345            }
346        }
347        // Ensure that the recursive term has the same field types as the static term
348        let coerced_recursive_term =
349            coerce_plan_expr_for_schema(recursive_term, self.plan.schema())?;
350        let recursive_query = RecursiveQuery::try_new(
351            name,
352            self.plan,
353            Arc::new(coerced_recursive_term),
354            is_distinct,
355        )?;
356        Ok(Self::from(LogicalPlan::RecursiveQuery(recursive_query)))
357    }
358
359    /// Create a values list based relation, and the schema is inferred from data, consuming
360    /// `value`. See the [Postgres VALUES](https://www.postgresql.org/docs/current/queries-values.html)
361    /// documentation for more details.
362    ///
363    /// so it's usually better to override the default names with a table alias list.
364    ///
365    /// If the values include params/binders such as $1, $2, $3, etc, then the `param_data_types` should be provided.
366    pub fn values(values: Vec<Vec<Expr>>) -> Result<Self> {
367        if values.is_empty() {
368            return plan_err!("Values list cannot be empty");
369        }
370        let n_cols = values[0].len();
371        if n_cols == 0 {
372            return plan_err!("Values list cannot be zero length");
373        }
374        for (i, row) in values.iter().enumerate() {
375            if row.len() != n_cols {
376                return plan_err!(
377                    "Inconsistent data length across values list: got {} values in row {} but expected {}",
378                    row.len(),
379                    i,
380                    n_cols
381                );
382            }
383        }
384
385        // Infer from data itself
386        Self::infer_data(values)
387    }
388
389    /// Create a values list based relation, and the schema is inferred from data itself or table schema if provided, consuming
390    /// `value`. See the [Postgres VALUES](https://www.postgresql.org/docs/current/queries-values.html)
391    /// documentation for more details.
392    ///
393    /// By default, it assigns the names column1, column2, etc. to the columns of a VALUES table.
394    /// The column names are not specified by the SQL standard and different database systems do it differently,
395    /// so it's usually better to override the default names with a table alias list.
396    ///
397    /// If the values include params/binders such as $1, $2, $3, etc, then the `param_data_types` should be provided.
398    pub fn values_with_schema(
399        values: Vec<Vec<Expr>>,
400        schema: &DFSchemaRef,
401    ) -> Result<Self> {
402        if values.is_empty() {
403            return plan_err!("Values list cannot be empty");
404        }
405        let n_cols = schema.fields().len();
406        if n_cols == 0 {
407            return plan_err!("Values list cannot be zero length");
408        }
409        for (i, row) in values.iter().enumerate() {
410            if row.len() != n_cols {
411                return plan_err!(
412                    "Inconsistent data length across values list: got {} values in row {} but expected {}",
413                    row.len(),
414                    i,
415                    n_cols
416                );
417            }
418        }
419
420        // Check the type of value against the schema
421        Self::infer_values_from_schema(values, schema)
422    }
423
424    fn infer_values_from_schema(
425        values: Vec<Vec<Expr>>,
426        schema: &DFSchema,
427    ) -> Result<Self> {
428        let n_cols = values[0].len();
429        let mut fields = ValuesFields::new();
430        for j in 0..n_cols {
431            let field_type = schema.field(j).data_type();
432            for row in values.iter() {
433                let value = &row[j];
434                let data_type = value.get_type(schema)?;
435
436                if !data_type.equals_datatype(field_type)
437                    && !can_cast_types(&data_type, field_type)
438                {
439                    return exec_err!(
440                        "Types don't match and no valid cast exists, received data of type {} for field of type {}",
441                        data_type,
442                        field_type
443                    );
444                }
445            }
446            let field = schema.field(j);
447
448            fields.push_with_metadata(
449                field_type.clone(),
450                field.is_nullable(),
451                Some(FieldMetadata::new_from_field(field)),
452            );
453        }
454
455        Self::infer_inner(values, fields, schema)
456    }
457
458    fn infer_data(values: Vec<Vec<Expr>>) -> Result<Self> {
459        let n_cols = values[0].len();
460        let schema = DFSchema::empty();
461        let mut fields = ValuesFields::new();
462
463        for j in 0..n_cols {
464            let mut common_type: Option<DataType> = None;
465            let mut common_metadata: Option<FieldMetadata> = None;
466            let mut nullable = false;
467            for (i, row) in values.iter().enumerate() {
468                let value = &row[j];
469                let metadata = value.metadata(&schema)?;
470                if let Some(ref cm) = common_metadata {
471                    if &metadata != cm {
472                        return plan_err!(
473                            "Inconsistent metadata across values list at row {i} column {j}. Was {:?} but found {:?}",
474                            cm,
475                            metadata
476                        );
477                    }
478                } else {
479                    common_metadata = Some(metadata.clone());
480                }
481                if !nullable && value.nullable(&schema)? {
482                    nullable = true;
483                }
484                let data_type = value.get_type(&schema)?;
485                if data_type == DataType::Null {
486                    continue;
487                }
488
489                if let Some(prev_type) = common_type {
490                    // Widen the running type so that it can hold both the
491                    // previously seen rows and this row's value.
492                    let data_types = [prev_type.clone(), data_type.clone()];
493                    let Some(new_type) = type_union_resolution(&data_types) else {
494                        return plan_err!(
495                            "Inconsistent data type across values list at row {i} column {j}. Was {prev_type} but found {data_type}"
496                        );
497                    };
498                    common_type = Some(new_type);
499                } else {
500                    common_type = Some(data_type);
501                }
502            }
503            // If common_type is not set, every value in this column had type
504            // NULL. A DataType::Null field is always nullable.
505            let (data_type, nullable) = match common_type {
506                Some(t) => (t, nullable),
507                None => (DataType::Null, true),
508            };
509            fields.push_with_metadata(data_type, nullable, common_metadata);
510        }
511
512        Self::infer_inner(values, fields, &schema)
513    }
514
515    fn infer_inner(
516        mut values: Vec<Vec<Expr>>,
517        fields: ValuesFields,
518        schema: &DFSchema,
519    ) -> Result<Self> {
520        let fields = fields.into_fields();
521        // wrap cast if data type is not same as common type.
522        for row in &mut values {
523            for (j, field_type) in fields.iter().map(|f| f.data_type()).enumerate() {
524                if let Expr::Literal(ScalarValue::Null, metadata) = &row[j] {
525                    row[j] = Expr::Literal(
526                        ScalarValue::try_from(field_type)?,
527                        metadata.clone(),
528                    );
529                } else {
530                    row[j] = std::mem::take(&mut row[j]).cast_to(field_type, schema)?;
531                }
532            }
533        }
534
535        let dfschema = DFSchema::from_unqualified_fields(fields, HashMap::new())?;
536        let schema = DFSchemaRef::new(dfschema);
537
538        Ok(Self::new(LogicalPlan::Values(Values { schema, values })))
539    }
540
541    /// Convert a table provider into a builder with a TableScan
542    ///
543    /// Note that if you pass a string as `table_name`, it is treated
544    /// as a SQL identifier, as described on [`TableReference`] and
545    /// thus is normalized
546    ///
547    /// # Example:
548    /// ```
549    /// # use datafusion_expr::{lit, col, LogicalPlanBuilder,
550    /// #  logical_plan::builder::LogicalTableSource, logical_plan::table_scan
551    /// # };
552    /// # use std::sync::Arc;
553    /// # use arrow::datatypes::{Schema, DataType, Field};
554    /// # use datafusion_common::TableReference;
555    /// #
556    /// # let employee_schema = Arc::new(Schema::new(vec![
557    /// #           Field::new("id", DataType::Int32, false),
558    /// # ])) as _;
559    /// # let table_source = Arc::new(LogicalTableSource::new(employee_schema));
560    /// // Scan table_source with the name "mytable" (after normalization)
561    /// # let table = table_source.clone();
562    /// let scan = LogicalPlanBuilder::scan("MyTable", table, None);
563    ///
564    /// // Scan table_source with the name "MyTable" by enclosing in quotes
565    /// # let table = table_source.clone();
566    /// let scan = LogicalPlanBuilder::scan(r#""MyTable""#, table, None);
567    ///
568    /// // Scan table_source with the name "MyTable" by forming the table reference
569    /// # let table = table_source.clone();
570    /// let table_reference = TableReference::bare("MyTable");
571    /// let scan = LogicalPlanBuilder::scan(table_reference, table, None);
572    /// ```
573    pub fn scan(
574        table_name: impl Into<TableReference>,
575        table_source: Arc<dyn TableSource>,
576        projection: Option<Vec<usize>>,
577    ) -> Result<Self> {
578        let table_scan = TableScanBuilder::new(table_name, table_source)
579            .with_projection(projection)
580            .build()?;
581        Self::table_scan(table_scan)
582    }
583
584    /// Create a [CopyTo] for copying the contents of this builder to the specified file(s)
585    pub fn copy_to(
586        input: LogicalPlan,
587        output_url: String,
588        file_type: Arc<dyn FileType>,
589        options: HashMap<String, String>,
590        partition_by: Vec<String>,
591    ) -> Result<Self> {
592        Ok(Self::new(LogicalPlan::Copy(CopyTo::new(
593            Arc::new(input),
594            output_url,
595            partition_by,
596            file_type,
597            options,
598        ))))
599    }
600
601    /// Create a [`DmlStatement`] for inserting the contents of this builder into the named table.
602    ///
603    /// Note,  use a [`DefaultTableSource`] to insert into a [`TableProvider`]
604    ///
605    /// [`DefaultTableSource`]: https://docs.rs/datafusion/latest/datafusion/datasource/default_table_source/struct.DefaultTableSource.html
606    /// [`TableProvider`]: https://docs.rs/datafusion/latest/datafusion/catalog/trait.TableProvider.html
607    ///
608    /// # Example:
609    /// ```
610    /// # use datafusion_expr::{lit, LogicalPlanBuilder,
611    /// #  logical_plan::builder::LogicalTableSource,
612    /// # };
613    /// # use std::sync::Arc;
614    /// # use arrow::datatypes::{Schema, DataType, Field};
615    /// # use datafusion_expr::dml::InsertOp;
616    /// #
617    /// # fn test() -> datafusion_common::Result<()> {
618    /// # let employee_schema = Arc::new(Schema::new(vec![
619    /// #     Field::new("id", DataType::Int32, false),
620    /// # ])) as _;
621    /// # let table_source = Arc::new(LogicalTableSource::new(employee_schema));
622    /// // VALUES (1), (2)
623    /// let input = LogicalPlanBuilder::values(vec![vec![lit(1)], vec![lit(2)]])?.build()?;
624    /// // INSERT INTO MyTable VALUES (1), (2)
625    /// let insert_plan = LogicalPlanBuilder::insert_into(
626    ///     input,
627    ///     "MyTable",
628    ///     table_source,
629    ///     InsertOp::Append,
630    /// )?;
631    /// # Ok(())
632    /// # }
633    /// ```
634    pub fn insert_into(
635        input: LogicalPlan,
636        table_name: impl Into<TableReference>,
637        target: Arc<dyn TableSource>,
638        insert_op: InsertOp,
639    ) -> Result<Self> {
640        Ok(Self::new(LogicalPlan::Dml(DmlStatement::new(
641            table_name.into(),
642            target,
643            WriteOp::Insert(insert_op),
644            Arc::new(input),
645        ))))
646    }
647
648    /// Convert a table provider into a builder with a TableScan
649    #[deprecated(since = "56.0.0", note = "Use table_scan([`TableScan`]) instead")]
650    pub fn scan_with_filters(
651        table_name: impl Into<TableReference>,
652        table_source: Arc<dyn TableSource>,
653        projection: Option<Vec<usize>>,
654        filters: Vec<Expr>,
655    ) -> Result<Self> {
656        let table_scan = TableScanBuilder::new(table_name, table_source)
657            .with_projection(projection)
658            .with_filters(filters)
659            .build()?;
660        Self::table_scan(table_scan)
661    }
662
663    /// Convert a table provider into a builder with a TableScan with filter and fetch
664    #[deprecated(since = "56.0.0", note = "Use table_scan([`TableScan`]) instead")]
665    pub fn scan_with_filters_fetch(
666        table_name: impl Into<TableReference>,
667        table_source: Arc<dyn TableSource>,
668        projection: Option<Vec<usize>>,
669        filters: Vec<Expr>,
670        fetch: Option<usize>,
671    ) -> Result<Self> {
672        let table_scan = TableScanBuilder::new(table_name, table_source)
673            .with_projection(projection)
674            .with_filters(filters)
675            .with_fetch(fetch)
676            .build()?;
677        Self::table_scan(table_scan)
678    }
679
680    /// Convert a [`TableScan`] into a builder
681    pub fn table_scan(table_scan: TableScan) -> Result<Self> {
682        // Inline TableScan
683        if table_scan.filters.is_empty()
684            && let Some(p) = table_scan.source.get_logical_plan()
685        {
686            let sub_plan = p.into_owned();
687
688            if let Some(proj) = table_scan.projection {
689                let projection_exprs = proj
690                    .into_iter()
691                    .map(|i| {
692                        Expr::Column(Column::from(sub_plan.schema().qualified_field(i)))
693                    })
694                    .collect::<Vec<_>>();
695                return Self::new(sub_plan)
696                    .project(projection_exprs)?
697                    .alias(table_scan.table_name);
698            }
699
700            // Ensures that the reference to the inlined table remains the
701            // same, meaning we don't have to change any of the parent nodes
702            // that reference this table.
703            return Self::new(sub_plan).alias(table_scan.table_name);
704        }
705
706        Ok(Self::new(LogicalPlan::TableScan(table_scan)))
707    }
708
709    /// Wrap a plan in a window
710    pub fn window_plan(
711        input: LogicalPlan,
712        window_exprs: impl IntoIterator<Item = Expr>,
713    ) -> Result<LogicalPlan> {
714        let mut plan = input;
715        let mut groups = group_window_expr_by_sort_keys(window_exprs)?;
716        // To align with the behavior of PostgreSQL, we want the sort_keys sorted as same rule as PostgreSQL that first
717        // we compare the sort key themselves and if one window's sort keys are a prefix of another
718        // put the window with more sort keys first. so more deeply sorted plans gets nested further down as children.
719        // The sort_by() implementation here is a stable sort.
720        // Note that by this rule if there's an empty over, it'll be at the top level
721        groups.sort_by(|(key_a, _), (key_b, _)| {
722            for ((first, _), (second, _)) in key_a.iter().zip(key_b.iter()) {
723                let key_ordering = compare_sort_expr(first, second, plan.schema());
724                match key_ordering {
725                    Ordering::Less => {
726                        return Ordering::Less;
727                    }
728                    Ordering::Greater => {
729                        return Ordering::Greater;
730                    }
731                    Ordering::Equal => {}
732                }
733            }
734            key_b.len().cmp(&key_a.len())
735        });
736        for (_, exprs) in groups {
737            let window_exprs = exprs.into_iter().collect::<Vec<_>>();
738            // Partition and sorting is done at physical level, see the EnforceDistribution
739            // and EnforceSorting rules.
740            plan = LogicalPlanBuilder::from(plan)
741                .window(window_exprs)?
742                .build()?;
743        }
744        Ok(plan)
745    }
746
747    /// Apply a projection without alias.
748    pub fn project(
749        self,
750        expr: impl IntoIterator<Item = impl Into<SelectExpr>>,
751    ) -> Result<Self> {
752        project(Arc::unwrap_or_clone(self.plan), expr).map(Self::new)
753    }
754
755    /// Apply a projection without alias with optional validation
756    /// (true to validate, false to not validate)
757    pub fn project_with_validation(
758        self,
759        expr: Vec<(impl Into<SelectExpr>, bool)>,
760    ) -> Result<Self> {
761        project_with_validation(Arc::unwrap_or_clone(self.plan), expr, None)
762            .map(Self::new)
763    }
764
765    /// Apply a projection, aliasing non-Column/non-Alias expressions to
766    /// match the field names from the provided schema.
767    pub fn project_with_validation_and_schema(
768        self,
769        expr: impl IntoIterator<Item = impl Into<SelectExpr>>,
770        schema: &DFSchemaRef,
771    ) -> Result<Self> {
772        project_with_validation(
773            Arc::unwrap_or_clone(self.plan),
774            expr.into_iter().map(|e| (e, true)),
775            Some(schema),
776        )
777        .map(Self::new)
778    }
779
780    /// Select the given column indices
781    pub fn select(self, indices: impl IntoIterator<Item = usize>) -> Result<Self> {
782        let exprs: Vec<_> = indices
783            .into_iter()
784            .map(|x| Expr::Column(Column::from(self.plan.schema().qualified_field(x))))
785            .collect();
786        self.project(exprs)
787    }
788
789    /// Apply a filter
790    pub fn filter(self, expr: impl Into<Expr>) -> Result<Self> {
791        let expr = normalize_col(expr.into(), &self.plan)?;
792        Filter::try_new(expr, self.plan)
793            .map(LogicalPlan::Filter)
794            .map(Self::new)
795    }
796
797    /// Apply a filter which is used for a having clause
798    pub fn having(self, expr: impl Into<Expr>) -> Result<Self> {
799        let expr = normalize_col(expr.into(), &self.plan)?;
800        Filter::try_new(expr, self.plan)
801            .map(LogicalPlan::Filter)
802            .map(Self::from)
803    }
804
805    /// Make a builder for a prepare logical plan from the builder's plan
806    pub fn prepare(self, name: String, fields: Vec<FieldRef>) -> Result<Self> {
807        Ok(Self::new(LogicalPlan::Statement(Statement::Prepare(
808            Prepare {
809                name,
810                fields,
811                input: self.plan,
812            },
813        ))))
814    }
815
816    /// Limit the number of rows returned
817    ///
818    /// `skip` - Number of rows to skip before fetch any row.
819    ///
820    /// `fetch` - Maximum number of rows to fetch, after skipping `skip` rows,
821    ///          if specified.
822    pub fn limit(self, skip: usize, fetch: Option<usize>) -> Result<Self> {
823        let skip_expr = if skip == 0 {
824            None
825        } else {
826            Some(lit(skip as i64))
827        };
828        let fetch_expr = fetch.map(|f| lit(f as i64));
829        self.limit_by_expr(skip_expr, fetch_expr)
830    }
831
832    /// Limit the number of rows returned
833    ///
834    /// Similar to `limit` but uses expressions for `skip` and `fetch`
835    pub fn limit_by_expr(self, skip: Option<Expr>, fetch: Option<Expr>) -> Result<Self> {
836        Ok(Self::new(LogicalPlan::Limit(Limit {
837            skip: skip.map(Box::new),
838            fetch: fetch.map(Box::new),
839            input: self.plan,
840        })))
841    }
842
843    /// Apply an alias
844    pub fn alias(self, alias: impl Into<TableReference>) -> Result<Self> {
845        subquery_alias(Arc::unwrap_or_clone(self.plan), alias).map(Self::new)
846    }
847
848    /// Add missing sort columns to all downstream projection
849    ///
850    /// Thus, if you have a LogicalPlan that selects A and B and have
851    /// not requested a sort by C, this code will add C recursively to
852    /// all input projections.
853    ///
854    /// Adding a new column is not correct if there is a `Distinct`
855    /// node, which produces only distinct values of its
856    /// inputs. Adding a new column to its input will result in
857    /// potentially different results than with the original column.
858    ///
859    /// For example, if the input is like:
860    ///
861    /// Distinct(A, B)
862    ///
863    /// If the input looks like
864    ///
865    /// a | b | c
866    /// --+---+---
867    /// 1 | 2 | 3
868    /// 1 | 2 | 4
869    ///
870    /// Distinct (A, B) --> (1,2)
871    ///
872    /// But Distinct (A, B, C) --> (1, 2, 3), (1, 2, 4)
873    ///  (which will appear as a (1, 2), (1, 2) if a and b are projected
874    ///
875    /// See <https://github.com/apache/datafusion/issues/5065> for more details
876    fn add_missing_columns(
877        curr_plan: LogicalPlan,
878        missing_cols: &IndexSet<Column>,
879        is_distinct: bool,
880    ) -> Result<LogicalPlan> {
881        match curr_plan {
882            LogicalPlan::Projection(Projection {
883                input,
884                mut expr,
885                schema: _,
886            }) if missing_cols.iter().all(|c| input.schema().has_column(c)) => {
887                let mut missing_exprs = missing_cols
888                    .iter()
889                    .map(|c| normalize_col(Expr::Column(c.clone()), &input))
890                    .collect::<Result<Vec<_>>>()?;
891
892                // Do not let duplicate columns to be added, some of the
893                // missing_cols may be already present but without the new
894                // projected alias.
895                missing_exprs.retain(|e| !expr.contains(e));
896                if is_distinct {
897                    Self::ambiguous_distinct_check(&missing_exprs, missing_cols, &expr)?;
898                }
899                expr.extend(missing_exprs);
900                project(Arc::unwrap_or_clone(input), expr)
901            }
902            _ => {
903                let is_distinct =
904                    is_distinct || matches!(curr_plan, LogicalPlan::Distinct(_));
905                let new_inputs = curr_plan
906                    .inputs()
907                    .into_iter()
908                    .map(|input_plan| {
909                        Self::add_missing_columns(
910                            (*input_plan).clone(),
911                            missing_cols,
912                            is_distinct,
913                        )
914                    })
915                    .collect::<Result<Vec<_>>>()?;
916                curr_plan.with_new_exprs(curr_plan.expressions(), new_inputs)
917            }
918        }
919    }
920
921    fn ambiguous_distinct_check(
922        missing_exprs: &[Expr],
923        missing_cols: &IndexSet<Column>,
924        projection_exprs: &[Expr],
925    ) -> Result<()> {
926        if missing_exprs.is_empty() {
927            return Ok(());
928        }
929
930        // if the missing columns are all only aliases for things in
931        // the existing select list, it is ok
932        //
933        // This handles the special case for
934        // SELECT col as <alias> ORDER BY <alias>
935        //
936        // As described in https://github.com/apache/datafusion/issues/5293
937        let all_aliases = missing_exprs.iter().all(|e| {
938            projection_exprs.iter().any(|proj_expr| {
939                if let Expr::Alias(Alias { expr, .. }) = proj_expr {
940                    e == expr.as_ref()
941                } else {
942                    false
943                }
944            })
945        });
946        if all_aliases {
947            return Ok(());
948        }
949
950        let missing_col_names = missing_cols
951            .iter()
952            .map(|col| col.flat_name())
953            .collect::<String>();
954
955        plan_err!(
956            "For SELECT DISTINCT, ORDER BY expressions {missing_col_names} must appear in select list"
957        )
958    }
959
960    /// Apply a sort by provided expressions with default direction
961    pub fn sort_by(
962        self,
963        expr: impl IntoIterator<Item = impl Into<Expr>> + Clone,
964    ) -> Result<Self> {
965        self.sort(
966            expr.into_iter()
967                .map(|e| e.into().sort(true, false))
968                .collect::<Vec<SortExpr>>(),
969        )
970    }
971
972    pub fn sort(
973        self,
974        sorts: impl IntoIterator<Item = impl Into<SortExpr>> + Clone,
975    ) -> Result<Self> {
976        self.sort_with_limit(sorts, None)
977    }
978
979    /// Apply a sort
980    pub fn sort_with_limit(
981        self,
982        sorts: impl IntoIterator<Item = impl Into<SortExpr>> + Clone,
983        fetch: Option<usize>,
984    ) -> Result<Self> {
985        let sorts = rewrite_sort_cols_by_aggs(sorts, &self.plan)?;
986
987        let schema = self.plan.schema();
988
989        // Collect sort columns that are missing in the input plan's schema
990        let mut missing_cols: IndexSet<Column> = IndexSet::new();
991        sorts.iter().try_for_each::<_, Result<()>>(|sort| {
992            let columns = sort.expr.column_refs();
993
994            missing_cols.extend(
995                columns
996                    .into_iter()
997                    .filter(|c| !schema.has_column(c))
998                    .cloned(),
999            );
1000
1001            Ok(())
1002        })?;
1003
1004        if missing_cols.is_empty() {
1005            return Ok(Self::new(LogicalPlan::Sort(Sort {
1006                expr: normalize_sorts(sorts, &self.plan)?,
1007                input: self.plan,
1008                fetch,
1009            })));
1010        }
1011
1012        // remove pushed down sort columns
1013        let new_expr = schema.columns().into_iter().map(Expr::Column).collect();
1014
1015        let is_distinct = false;
1016        let plan = Self::add_missing_columns(
1017            Arc::unwrap_or_clone(self.plan),
1018            &missing_cols,
1019            is_distinct,
1020        )?;
1021
1022        let sort_plan = LogicalPlan::Sort(Sort {
1023            expr: normalize_sorts(sorts, &plan)?,
1024            input: Arc::new(plan),
1025            fetch,
1026        });
1027
1028        Projection::try_new(new_expr, Arc::new(sort_plan))
1029            .map(LogicalPlan::Projection)
1030            .map(Self::new)
1031    }
1032
1033    /// Apply a union, preserving duplicate rows
1034    pub fn union(self, plan: LogicalPlan) -> Result<Self> {
1035        union(Arc::unwrap_or_clone(self.plan), plan).map(Self::new)
1036    }
1037
1038    /// Apply a union by name, preserving duplicate rows
1039    pub fn union_by_name(self, plan: LogicalPlan) -> Result<Self> {
1040        union_by_name(Arc::unwrap_or_clone(self.plan), plan).map(Self::new)
1041    }
1042
1043    /// Apply a union by name, removing duplicate rows
1044    pub fn union_by_name_distinct(self, plan: LogicalPlan) -> Result<Self> {
1045        let left_plan: LogicalPlan = Arc::unwrap_or_clone(self.plan);
1046        let right_plan: LogicalPlan = plan;
1047
1048        Ok(Self::new(LogicalPlan::Distinct(Distinct::All(Arc::new(
1049            union_by_name(left_plan, right_plan)?,
1050        )))))
1051    }
1052
1053    /// Apply a union, removing duplicate rows
1054    pub fn union_distinct(self, plan: LogicalPlan) -> Result<Self> {
1055        let left_plan: LogicalPlan = Arc::unwrap_or_clone(self.plan);
1056        let right_plan: LogicalPlan = plan;
1057
1058        Ok(Self::new(LogicalPlan::Distinct(Distinct::All(Arc::new(
1059            union(left_plan, right_plan)?,
1060        )))))
1061    }
1062
1063    /// Apply deduplication: Only distinct (different) values are returned)
1064    pub fn distinct(self) -> Result<Self> {
1065        Ok(Self::new(LogicalPlan::Distinct(Distinct::All(self.plan))))
1066    }
1067
1068    /// Project first values of the specified expression list according to the provided
1069    /// sorting expressions grouped by the `DISTINCT ON` clause expressions.
1070    pub fn distinct_on(
1071        self,
1072        on_expr: Vec<Expr>,
1073        select_expr: Vec<Expr>,
1074        sort_expr: Option<Vec<SortExpr>>,
1075    ) -> Result<Self> {
1076        Ok(Self::new(LogicalPlan::Distinct(Distinct::On(
1077            DistinctOn::try_new(on_expr, select_expr, sort_expr, self.plan)?,
1078        ))))
1079    }
1080
1081    /// Apply a join to `right` using explicitly specified columns and an
1082    /// optional filter expression.
1083    ///
1084    /// See [`join_on`](Self::join_on) for a more concise way to specify the
1085    /// join condition. Since DataFusion will automatically identify and
1086    /// optimize equality predicates there is no performance difference between
1087    /// this function and `join_on`
1088    ///
1089    /// `left_cols` and `right_cols` are used to form "equijoin" predicates (see
1090    /// example below), which are then combined with the optional `filter`
1091    /// expression.
1092    ///
1093    /// Note that in case of outer join, the `filter` is applied to only matched rows.
1094    pub fn join(
1095        self,
1096        right: LogicalPlan,
1097        join_type: JoinType,
1098        join_keys: (Vec<impl Into<Column>>, Vec<impl Into<Column>>),
1099        filter: Option<Expr>,
1100    ) -> Result<Self> {
1101        self.join_detailed(
1102            right,
1103            join_type,
1104            join_keys,
1105            filter,
1106            NullEquality::NullEqualsNothing,
1107        )
1108    }
1109
1110    /// Apply a join using the specified expressions.
1111    ///
1112    /// Note that DataFusion automatically optimizes joins, including
1113    /// identifying and optimizing equality predicates.
1114    ///
1115    /// # Example
1116    ///
1117    /// ```
1118    /// # use datafusion_expr::{Expr, col, LogicalPlanBuilder,
1119    /// #  logical_plan::builder::LogicalTableSource, logical_plan::JoinType,};
1120    /// # use std::sync::Arc;
1121    /// # use arrow::datatypes::{Schema, DataType, Field};
1122    /// # use datafusion_common::Result;
1123    /// # fn main() -> Result<()> {
1124    /// let example_schema = Arc::new(Schema::new(vec![
1125    ///     Field::new("a", DataType::Int32, false),
1126    ///     Field::new("b", DataType::Int32, false),
1127    ///     Field::new("c", DataType::Int32, false),
1128    /// ]));
1129    /// let table_source = Arc::new(LogicalTableSource::new(example_schema));
1130    /// let left_table = table_source.clone();
1131    /// let right_table = table_source.clone();
1132    ///
1133    /// let right_plan = LogicalPlanBuilder::scan("right", right_table, None)?.build()?;
1134    ///
1135    /// // Form the expression `(left.a != right.a)` AND `(left.b != right.b)`
1136    /// let exprs = vec![
1137    ///     col("left.a").eq(col("right.a")),
1138    ///     col("left.b").not_eq(col("right.b")),
1139    /// ];
1140    ///
1141    /// // Perform the equivalent of `left INNER JOIN right ON (a != a2 AND b != b2)`
1142    /// // finding all pairs of rows from `left` and `right` where
1143    /// // where `a = a2` and `b != b2`.
1144    /// let plan = LogicalPlanBuilder::scan("left", left_table, None)?
1145    ///     .join_on(right_plan, JoinType::Inner, exprs)?
1146    ///     .build()?;
1147    /// # Ok(())
1148    /// # }
1149    /// ```
1150    pub fn join_on(
1151        self,
1152        right: LogicalPlan,
1153        join_type: JoinType,
1154        on_exprs: impl IntoIterator<Item = Expr>,
1155    ) -> Result<Self> {
1156        let filter = on_exprs.into_iter().reduce(Expr::and);
1157
1158        self.join_detailed(
1159            right,
1160            join_type,
1161            (Vec::<Column>::new(), Vec::<Column>::new()),
1162            filter,
1163            NullEquality::NullEqualsNothing,
1164        )
1165    }
1166
1167    /// Apply a left-preserving ASOF join using an optional equality condition
1168    /// and one ordered match condition.
1169    ///
1170    /// When present, `on_expr` must contain equality comparisons combined with
1171    /// `AND`. Each comparison must have one operand that references only the
1172    /// left input and one that references only `right`; their order does not
1173    /// matter. `match_condition` must be a single `<`, `<=`, `>`, or `>=`
1174    /// comparison whose left operand references only the left input and whose
1175    /// right operand references only `right`.
1176    pub fn asof_join_on(
1177        self,
1178        right: LogicalPlan,
1179        on_expr: Option<Expr>,
1180        match_condition: Expr,
1181    ) -> Result<Self> {
1182        let on = on_expr
1183            .into_iter()
1184            .flat_map(split_conjunction_owned)
1185            .map(|predicate| {
1186                let Expr::BinaryExpr(BinaryExpr {
1187                    left,
1188                    op: Operator::Eq,
1189                    right: right_expr,
1190                }) = predicate
1191                else {
1192                    return plan_err!(
1193                        "ASOF ON accepts only equality conditions combined with AND"
1194                    );
1195                };
1196                find_valid_equijoin_key_pair(
1197                    &left,
1198                    &right_expr,
1199                    self.plan.schema(),
1200                    right.schema(),
1201                )?
1202                .ok_or_else(|| {
1203                    plan_datafusion_err!(
1204                        "Each ASOF equality condition must compare one left expression with one right expression"
1205                    )
1206                })
1207            })
1208            .collect::<Result<_>>()?;
1209        self.asof_join_with_constraint(
1210            right,
1211            on,
1212            AsOfMatch::try_from(match_condition)?,
1213            JoinConstraint::On,
1214        )
1215    }
1216
1217    /// Apply a left-preserving ASOF join using `USING` equality keys and one
1218    /// ordered match condition.
1219    ///
1220    /// Every key in `using_keys` must resolve in both inputs.
1221    /// `match_condition` follows the same operand and operator requirements as
1222    /// [`asof_join_on`](Self::asof_join_on).
1223    pub fn asof_join_using(
1224        self,
1225        right: LogicalPlan,
1226        using_keys: Vec<Column>,
1227        match_condition: Expr,
1228    ) -> Result<Self> {
1229        let on = using_keys
1230            .into_iter()
1231            .map(|key| {
1232                let left = Self::normalize(&self.plan, key.clone())?;
1233                let right = Self::normalize(&right, key)?;
1234                Ok((Expr::Column(left), Expr::Column(right)))
1235            })
1236            .collect::<Result<_>>()?;
1237        self.asof_join_with_constraint(
1238            right,
1239            on,
1240            AsOfMatch::try_from(match_condition)?,
1241            JoinConstraint::Using,
1242        )
1243    }
1244
1245    fn asof_join_with_constraint(
1246        self,
1247        right: LogicalPlan,
1248        on: Vec<(Expr, Expr)>,
1249        match_condition: AsOfMatch,
1250        join_constraint: JoinConstraint,
1251    ) -> Result<Self> {
1252        let left_columns = match_condition.left.column_refs();
1253        let right_columns = match_condition.right.column_refs();
1254        if left_columns.is_empty()
1255            || right_columns.is_empty()
1256            || !check_all_columns_from_schema(&left_columns, self.plan.schema())?
1257            || !check_all_columns_from_schema(&right_columns, right.schema())?
1258        {
1259            return plan_err!(
1260                "ASOF MATCH_CONDITION left operand must reference only the left input and right operand only the right input"
1261            );
1262        }
1263        let normalize = |expr, schema: &DFSchema| {
1264            normalize_col_with_schemas_and_ambiguity_check(expr, &[&[schema]], &[])
1265        };
1266        let on = on
1267            .into_iter()
1268            .map(|(left, right_expr)| {
1269                Ok((
1270                    normalize(left, self.plan.schema())?,
1271                    normalize(right_expr, right.schema())?,
1272                ))
1273            })
1274            .collect::<Result<_>>()?;
1275        let match_condition = AsOfMatch {
1276            left: normalize(match_condition.left, self.plan.schema())?,
1277            op: match_condition.op,
1278            right: normalize(match_condition.right, right.schema())?,
1279        };
1280        Ok(Self::new(LogicalPlan::AsOfJoin(AsOfJoin::try_new(
1281            self.plan,
1282            Arc::new(right),
1283            on,
1284            match_condition,
1285            join_constraint,
1286        )?)))
1287    }
1288
1289    pub(crate) fn normalize(plan: &LogicalPlan, column: Column) -> Result<Column> {
1290        ColumnNormalizer::new(plan).normalize_column(column)
1291    }
1292
1293    /// Apply a join with on constraint and specified null equality.
1294    ///
1295    /// The behavior is the same as [`join`](Self::join) except that it allows
1296    /// specifying the null equality behavior.
1297    ///
1298    /// The `null_equality` dictates how `null` values are joined.
1299    pub fn join_detailed(
1300        self,
1301        right: LogicalPlan,
1302        join_type: JoinType,
1303        join_keys: (Vec<impl Into<Column>>, Vec<impl Into<Column>>),
1304        filter: Option<Expr>,
1305        null_equality: NullEquality,
1306    ) -> Result<Self> {
1307        self.join_detailed_with_options(
1308            right,
1309            join_type,
1310            join_keys,
1311            filter,
1312            null_equality,
1313            false,
1314        )
1315    }
1316
1317    pub fn join_detailed_with_options(
1318        self,
1319        right: LogicalPlan,
1320        join_type: JoinType,
1321        join_keys: (Vec<impl Into<Column>>, Vec<impl Into<Column>>),
1322        filter: Option<Expr>,
1323        null_equality: NullEquality,
1324        null_aware: bool,
1325    ) -> Result<Self> {
1326        if join_keys.0.len() != join_keys.1.len() {
1327            return plan_err!("left_keys and right_keys were not the same length");
1328        }
1329
1330        let filter = if let Some(expr) = filter {
1331            let filter = normalize_col_with_schemas_and_ambiguity_check(
1332                expr,
1333                &[&[self.schema(), right.schema()]],
1334                &[],
1335            )?;
1336            Some(filter)
1337        } else {
1338            None
1339        };
1340
1341        let (left_keys, right_keys): (Vec<Result<Column>>, Vec<Result<Column>>) =
1342            join_keys
1343                .0
1344                .into_iter()
1345                .zip(join_keys.1)
1346                .map(|(l, r)| {
1347                    let l = l.into();
1348                    let r = r.into();
1349
1350                    match (&l.relation, &r.relation) {
1351                        (Some(lr), Some(rr)) => {
1352                            let l_is_left =
1353                                self.plan.schema().field_with_qualified_name(lr, &l.name);
1354                            let l_is_right =
1355                                right.schema().field_with_qualified_name(lr, &l.name);
1356                            let r_is_left =
1357                                self.plan.schema().field_with_qualified_name(rr, &r.name);
1358                            let r_is_right =
1359                                right.schema().field_with_qualified_name(rr, &r.name);
1360
1361                            match (l_is_left, l_is_right, r_is_left, r_is_right) {
1362                                (_, Ok(_), Ok(_), _) => (Ok(r), Ok(l)),
1363                                (Ok(_), _, _, Ok(_)) => (Ok(l), Ok(r)),
1364                                _ => (
1365                                    Self::normalize(&self.plan, l),
1366                                    Self::normalize(&right, r),
1367                                ),
1368                            }
1369                        }
1370                        (Some(lr), None) => {
1371                            let l_is_left =
1372                                self.plan.schema().field_with_qualified_name(lr, &l.name);
1373                            let l_is_right =
1374                                right.schema().field_with_qualified_name(lr, &l.name);
1375
1376                            match (l_is_left, l_is_right) {
1377                                (Ok(_), _) => (Ok(l), Self::normalize(&right, r)),
1378                                (_, Ok(_)) => (Self::normalize(&self.plan, r), Ok(l)),
1379                                _ => (
1380                                    Self::normalize(&self.plan, l),
1381                                    Self::normalize(&right, r),
1382                                ),
1383                            }
1384                        }
1385                        (None, Some(rr)) => {
1386                            let r_is_left =
1387                                self.plan.schema().field_with_qualified_name(rr, &r.name);
1388                            let r_is_right =
1389                                right.schema().field_with_qualified_name(rr, &r.name);
1390
1391                            match (r_is_left, r_is_right) {
1392                                (Ok(_), _) => (Ok(r), Self::normalize(&right, l)),
1393                                (_, Ok(_)) => (Self::normalize(&self.plan, l), Ok(r)),
1394                                _ => (
1395                                    Self::normalize(&self.plan, l),
1396                                    Self::normalize(&right, r),
1397                                ),
1398                            }
1399                        }
1400                        (None, None) => {
1401                            let mut swap = false;
1402                            let left_key = Self::normalize(&self.plan, l.clone())
1403                                .or_else(|_| {
1404                                    swap = true;
1405                                    Self::normalize(&right, l)
1406                                });
1407                            if swap {
1408                                (Self::normalize(&self.plan, r), left_key)
1409                            } else {
1410                                (left_key, Self::normalize(&right, r))
1411                            }
1412                        }
1413                    }
1414                })
1415                .unzip();
1416
1417        let left_keys = left_keys.into_iter().collect::<Result<Vec<Column>>>()?;
1418        let right_keys = right_keys.into_iter().collect::<Result<Vec<Column>>>()?;
1419
1420        let on: Vec<_> = left_keys
1421            .into_iter()
1422            .zip(right_keys)
1423            .map(|(l, r)| (Expr::Column(l), Expr::Column(r)))
1424            .collect();
1425        let join_schema =
1426            build_join_schema(self.plan.schema(), right.schema(), &join_type)?;
1427
1428        // Inner type without join condition is cross join
1429        if join_type != JoinType::Inner && on.is_empty() && filter.is_none() {
1430            return plan_err!("join condition should not be empty");
1431        }
1432
1433        Ok(Self::new(LogicalPlan::Join(Join {
1434            left: self.plan,
1435            right: Arc::new(right),
1436            on,
1437            filter,
1438            join_type,
1439            join_constraint: JoinConstraint::On,
1440            schema: DFSchemaRef::new(join_schema),
1441            null_equality,
1442            null_aware,
1443            null_aware_value_keys: 0,
1444        })))
1445    }
1446
1447    /// Apply a join with using constraint, which duplicates all join columns in output schema.
1448    pub fn join_using(
1449        self,
1450        right: LogicalPlan,
1451        join_type: JoinType,
1452        using_keys: Vec<Column>,
1453    ) -> Result<Self> {
1454        let left_keys: Vec<Column> = using_keys
1455            .clone()
1456            .into_iter()
1457            .map(|c| Self::normalize(&self.plan, c))
1458            .collect::<Result<_>>()?;
1459        let right_keys: Vec<Column> = using_keys
1460            .into_iter()
1461            .map(|c| Self::normalize(&right, c))
1462            .collect::<Result<_>>()?;
1463
1464        let on: Vec<(_, _)> = left_keys.into_iter().zip(right_keys).collect();
1465        let mut join_on: Vec<(Expr, Expr)> = Vec::with_capacity(on.len());
1466        let mut filters: Option<Expr> = None;
1467        for (l, r) in &on {
1468            if self.plan.schema().has_column(l)
1469                && right.schema().has_column(r)
1470                && can_hash(
1471                    datafusion_common::ExprSchema::field_from_column(
1472                        self.plan.schema(),
1473                        l,
1474                    )?
1475                    .data_type(),
1476                )
1477            {
1478                join_on.push((Expr::Column(l.clone()), Expr::Column(r.clone())));
1479            } else if self.plan.schema().has_column(l)
1480                && right.schema().has_column(r)
1481                && can_hash(
1482                    datafusion_common::ExprSchema::field_from_column(
1483                        self.plan.schema(),
1484                        r,
1485                    )?
1486                    .data_type(),
1487                )
1488            {
1489                join_on.push((Expr::Column(r.clone()), Expr::Column(l.clone())));
1490            } else {
1491                let expr = binary_expr(
1492                    Expr::Column(l.clone()),
1493                    Operator::Eq,
1494                    Expr::Column(r.clone()),
1495                );
1496                match filters {
1497                    None => filters = Some(expr),
1498                    Some(filter_expr) => filters = Some(and(expr, filter_expr)),
1499                }
1500            }
1501        }
1502
1503        if join_on.is_empty() {
1504            let join = Self::from(self.plan).cross_join(right)?;
1505            join.filter(filters.ok_or_else(|| {
1506                internal_datafusion_err!("filters should not be None here")
1507            })?)
1508        } else {
1509            let join = Join::try_new(
1510                self.plan,
1511                Arc::new(right),
1512                join_on,
1513                filters,
1514                join_type,
1515                JoinConstraint::Using,
1516                NullEquality::NullEqualsNothing,
1517                false, // null_aware
1518            )?;
1519
1520            Ok(Self::new(LogicalPlan::Join(join)))
1521        }
1522    }
1523
1524    /// Apply a cross join
1525    pub fn cross_join(self, right: LogicalPlan) -> Result<Self> {
1526        let join = Join::try_new(
1527            self.plan,
1528            Arc::new(right),
1529            vec![],
1530            None,
1531            JoinType::Inner,
1532            JoinConstraint::On,
1533            NullEquality::NullEqualsNothing,
1534            false, // null_aware
1535        )?;
1536
1537        Ok(Self::new(LogicalPlan::Join(join)))
1538    }
1539
1540    /// Repartition
1541    pub fn repartition(self, partitioning_scheme: Partitioning) -> Result<Self> {
1542        Ok(Self::new(LogicalPlan::Repartition(Repartition {
1543            input: self.plan,
1544            partitioning_scheme,
1545        })))
1546    }
1547
1548    /// Apply a window functions to extend the schema
1549    pub fn window(
1550        self,
1551        window_expr: impl IntoIterator<Item = impl Into<Expr>>,
1552    ) -> Result<Self> {
1553        let window_expr = normalize_cols(window_expr, &self.plan)?;
1554        validate_unique_names("Windows", &window_expr)?;
1555        Ok(Self::new(LogicalPlan::Window(Window::try_new(
1556            window_expr,
1557            self.plan,
1558        )?)))
1559    }
1560
1561    /// Apply an aggregate: grouping on the `group_expr` expressions
1562    /// and calculating `aggr_expr` aggregates for each distinct
1563    /// value of the `group_expr`;
1564    pub fn aggregate(
1565        self,
1566        group_expr: impl IntoIterator<Item = impl Into<Expr>>,
1567        aggr_expr: impl IntoIterator<Item = impl Into<Expr>>,
1568    ) -> Result<Self> {
1569        let group_expr = normalize_cols(group_expr, &self.plan)?;
1570        let aggr_expr = normalize_cols(aggr_expr, &self.plan)?;
1571
1572        let group_expr = if self.options.add_implicit_group_by_exprs {
1573            add_group_by_exprs_from_dependencies(group_expr, self.plan.schema())?
1574        } else {
1575            group_expr
1576        };
1577
1578        Aggregate::try_new(self.plan, group_expr, aggr_expr)
1579            .map(LogicalPlan::Aggregate)
1580            .map(Self::new)
1581    }
1582
1583    /// Create an expression to represent the explanation of the plan
1584    ///
1585    /// if `analyze` is true, runs the actual plan and produces
1586    /// information about metrics during run.
1587    ///
1588    /// if `verbose` is true, prints out additional details.
1589    pub fn explain(self, verbose: bool, analyze: bool) -> Result<Self> {
1590        // Keep the format default to Indent
1591        self.explain_option_format(
1592            ExplainOption::default()
1593                .with_verbose(verbose)
1594                .with_analyze(analyze),
1595        )
1596    }
1597
1598    /// Create an expression to represent the explanation of the plan
1599    /// The`explain_option` is used to specify the format and verbosity of the explanation.
1600    /// Details see [`ExplainOption`].
1601    pub fn explain_option_format(self, explain_option: ExplainOption) -> Result<Self> {
1602        let schema = LogicalPlan::explain_schema();
1603        let schema = schema.to_dfschema_ref()?;
1604
1605        if explain_option.analyze {
1606            Ok(Self::new(LogicalPlan::Analyze(Analyze {
1607                verbose: explain_option.verbose,
1608                format: explain_option.format,
1609                input: self.plan,
1610                schema,
1611                analyze_level: explain_option.analyze_level,
1612                analyze_categories: explain_option.analyze_categories,
1613            })))
1614        } else {
1615            let stringified_plans =
1616                vec![self.plan.to_stringified(PlanType::InitialLogicalPlan)];
1617
1618            Ok(Self::new(LogicalPlan::Explain(Explain {
1619                verbose: explain_option.verbose,
1620                plan: self.plan,
1621                explain_format: explain_option.format,
1622                stringified_plans,
1623                schema,
1624                logical_optimization_succeeded: false,
1625                show_statistics: explain_option.show_statistics,
1626            })))
1627        }
1628    }
1629
1630    /// Process intersect set operator
1631    pub fn intersect(
1632        left_plan: LogicalPlan,
1633        right_plan: LogicalPlan,
1634        is_all: bool,
1635    ) -> Result<LogicalPlan> {
1636        LogicalPlanBuilder::intersect_or_except(
1637            left_plan,
1638            right_plan,
1639            JoinType::LeftSemi,
1640            is_all,
1641        )
1642    }
1643
1644    /// Process except set operator
1645    pub fn except(
1646        left_plan: LogicalPlan,
1647        right_plan: LogicalPlan,
1648        is_all: bool,
1649    ) -> Result<LogicalPlan> {
1650        LogicalPlanBuilder::intersect_or_except(
1651            left_plan,
1652            right_plan,
1653            JoinType::LeftAnti,
1654            is_all,
1655        )
1656    }
1657
1658    /// Process intersect or except
1659    fn intersect_or_except(
1660        left_plan: LogicalPlan,
1661        right_plan: LogicalPlan,
1662        join_type: JoinType,
1663        is_all: bool,
1664    ) -> Result<LogicalPlan> {
1665        let left_len = left_plan.schema().fields().len();
1666        let right_len = right_plan.schema().fields().len();
1667
1668        if left_len != right_len {
1669            return plan_err!(
1670                "INTERSECT/EXCEPT query must have the same number of columns. Left is {left_len} and right is {right_len}."
1671            );
1672        }
1673
1674        // Requalify sides if needed to avoid duplicate qualified field names
1675        // (e.g., when both sides reference the same table)
1676        let left_builder = LogicalPlanBuilder::from(left_plan);
1677        let right_builder = LogicalPlanBuilder::from(right_plan);
1678        let (left_builder, right_builder, _requalified) =
1679            requalify_sides_if_needed(left_builder, right_builder)?;
1680        let left_plan = left_builder.build()?;
1681        let right_plan = right_builder.build()?;
1682
1683        let join_keys = left_plan
1684            .schema()
1685            .fields()
1686            .iter()
1687            .zip(right_plan.schema().fields().iter())
1688            .map(|(left_field, right_field)| {
1689                (
1690                    (Column::from_name(left_field.name())),
1691                    (Column::from_name(right_field.name())),
1692                )
1693            })
1694            .unzip();
1695        let mut left_builder = LogicalPlanBuilder::from(left_plan);
1696        if !is_all {
1697            left_builder = left_builder.distinct()?;
1698        }
1699        left_builder
1700            .join_detailed(
1701                right_plan,
1702                join_type,
1703                join_keys,
1704                None,
1705                NullEquality::NullEqualsNull,
1706            )?
1707            .build()
1708    }
1709
1710    /// Build the plan
1711    pub fn build(self) -> Result<LogicalPlan> {
1712        Ok(Arc::unwrap_or_clone(self.plan))
1713    }
1714
1715    /// Apply a join with both explicit equijoin and non equijoin predicates.
1716    ///
1717    /// Note this is a low level API that requires identifying specific
1718    /// predicate types. Most users should use  [`join_on`](Self::join_on) that
1719    /// automatically identifies predicates appropriately.
1720    ///
1721    /// `equi_exprs` defines equijoin predicates, of the form `l = r)` for each
1722    /// `(l, r)` tuple. `l`, the first element of the tuple, must only refer
1723    /// to columns from the existing input. `r`, the second element of the tuple,
1724    /// must only refer to columns from the right input.
1725    ///
1726    /// `filter` contains any other filter expression to apply during the
1727    /// join. Note that `equi_exprs` predicates are evaluated more efficiently
1728    /// than the filter expressions, so they are preferred.
1729    pub fn join_with_expr_keys(
1730        self,
1731        right: LogicalPlan,
1732        join_type: JoinType,
1733        equi_exprs: (Vec<impl Into<Expr>>, Vec<impl Into<Expr>>),
1734        filter: Option<Expr>,
1735    ) -> Result<Self> {
1736        if equi_exprs.0.len() != equi_exprs.1.len() {
1737            return plan_err!("left_keys and right_keys were not the same length");
1738        }
1739
1740        let join_key_pairs = equi_exprs
1741            .0
1742            .into_iter()
1743            .zip(equi_exprs.1)
1744            .map(|(l, r)| {
1745                let left_key = l.into();
1746                let right_key = r.into();
1747                let mut left_using_columns  = HashSet::new();
1748                expr_to_columns(&left_key, &mut left_using_columns)?;
1749                let normalized_left_key = normalize_col_with_schemas_and_ambiguity_check(
1750                    left_key,
1751                    &[&[self.plan.schema()]],
1752                    &[],
1753                )?;
1754
1755                let mut right_using_columns = HashSet::new();
1756                expr_to_columns(&right_key, &mut right_using_columns)?;
1757                let normalized_right_key = normalize_col_with_schemas_and_ambiguity_check(
1758                    right_key,
1759                    &[&[right.schema()]],
1760                    &[],
1761                )?;
1762
1763                // find valid equijoin
1764                find_valid_equijoin_key_pair(
1765                        &normalized_left_key,
1766                        &normalized_right_key,
1767                        self.plan.schema(),
1768                        right.schema(),
1769                    )?.ok_or_else(||
1770                        plan_datafusion_err!(
1771                            "can't create join plan, join key should belong to one input, error key: ({normalized_left_key},{normalized_right_key})"
1772                        ))
1773            })
1774            .collect::<Result<Vec<_>>>()?;
1775
1776        let join = Join::try_new(
1777            self.plan,
1778            Arc::new(right),
1779            join_key_pairs,
1780            filter,
1781            join_type,
1782            JoinConstraint::On,
1783            NullEquality::NullEqualsNothing,
1784            false, // null_aware
1785        )?;
1786
1787        Ok(Self::new(LogicalPlan::Join(join)))
1788    }
1789
1790    /// Unnest the given column.
1791    pub fn unnest_column(self, column: impl Into<Column>) -> Result<Self> {
1792        unnest(Arc::unwrap_or_clone(self.plan), vec![column.into()]).map(Self::new)
1793    }
1794
1795    /// Unnest the given column given [`UnnestOptions`]
1796    pub fn unnest_column_with_options(
1797        self,
1798        column: impl Into<Column>,
1799        options: UnnestOptions,
1800    ) -> Result<Self> {
1801        unnest_with_options(
1802            Arc::unwrap_or_clone(self.plan),
1803            vec![column.into()],
1804            options,
1805        )
1806        .map(Self::new)
1807    }
1808
1809    /// Unnest the given columns with the given [`UnnestOptions`]
1810    pub fn unnest_columns_with_options(
1811        self,
1812        columns: Vec<Column>,
1813        options: UnnestOptions,
1814    ) -> Result<Self> {
1815        unnest_with_options(Arc::unwrap_or_clone(self.plan), columns, options)
1816            .map(Self::new)
1817    }
1818}
1819
1820impl From<LogicalPlan> for LogicalPlanBuilder {
1821    fn from(plan: LogicalPlan) -> Self {
1822        LogicalPlanBuilder::new(plan)
1823    }
1824}
1825
1826impl From<Arc<LogicalPlan>> for LogicalPlanBuilder {
1827    fn from(plan: Arc<LogicalPlan>) -> Self {
1828        LogicalPlanBuilder::new_from_arc(plan)
1829    }
1830}
1831
1832/// Container used when building fields for a `VALUES` node.
1833#[derive(Default)]
1834struct ValuesFields {
1835    inner: Vec<Field>,
1836}
1837
1838impl ValuesFields {
1839    pub fn new() -> Self {
1840        Self::default()
1841    }
1842
1843    pub fn push_with_metadata(
1844        &mut self,
1845        data_type: DataType,
1846        nullable: bool,
1847        metadata: Option<FieldMetadata>,
1848    ) {
1849        // Naming follows the convention described here:
1850        // https://www.postgresql.org/docs/current/queries-values.html
1851        let name = format!("column{}", self.inner.len() + 1);
1852        let mut field = Field::new(name, data_type, nullable);
1853        if let Some(metadata) = metadata {
1854            field.set_metadata(metadata.into_inner());
1855        }
1856        self.inner.push(field);
1857    }
1858
1859    pub fn into_fields(self) -> Fields {
1860        self.inner.into()
1861    }
1862}
1863
1864/// Returns aliases to make field names unique.
1865///
1866/// Returns a vector of optional aliases, one per input field. `None` means keep the original name,
1867/// `Some(alias)` means rename to the alias to ensure uniqueness.
1868///
1869/// Used when creating [`SubqueryAlias`] or similar operations that strip table qualifiers but need
1870/// to maintain unique column names.
1871///
1872/// # Example
1873/// Input fields: `[a, a, b, b, a, a:1]` ([`DFSchema`] valid when duplicate fields have different qualifiers)
1874/// Returns: `[None, Some("a:1"), None, Some("b:1"), Some("a:2"), Some("a:1:1")]`
1875pub fn unique_field_aliases(fields: &Fields) -> Vec<Option<String>> {
1876    // Some field names might already come to this function with the count (number of times it appeared)
1877    // as a suffix e.g. id:1, so there's still a chance of name collisions, for example,
1878    // if these three fields passed to this function: "col:1", "col" and "col", the function
1879    // would rename them to -> col:1, col, col:1 causing a posterior error when building the DFSchema.
1880    // That's why we need the `seen` set, so the fields are always unique.
1881
1882    // Tracks a mapping between a field name and the number of appearances of that field.
1883    let mut name_map = HashMap::<&str, usize>::with_capacity(fields.len());
1884    // Tracks all the fields and aliases that were previously seen.
1885    let mut seen = HashSet::<Cow<String>>::with_capacity(fields.len());
1886
1887    fields
1888        .iter()
1889        .map(|field| {
1890            let original_name = field.name();
1891            let mut name = Cow::Borrowed(original_name);
1892
1893            let count = name_map.entry(original_name).or_insert(0);
1894
1895            // Loop until we find a name that hasn't been used.
1896            while seen.contains(&name) {
1897                *count += 1;
1898                name = Cow::Owned(format!("{original_name}:{count}"));
1899            }
1900
1901            seen.insert(name.clone());
1902
1903            match name {
1904                Cow::Borrowed(_) => None,
1905                Cow::Owned(alias) => Some(alias),
1906            }
1907        })
1908        .collect()
1909}
1910
1911fn mark_field(schema: &DFSchema) -> (Option<TableReference>, Arc<Field>) {
1912    let mut table_references = schema
1913        .iter()
1914        .filter_map(|(qualifier, _)| qualifier)
1915        .collect::<Vec<_>>();
1916    table_references.dedup();
1917    let table_reference = if table_references.len() == 1 {
1918        table_references.pop().cloned()
1919    } else {
1920        None
1921    };
1922
1923    (
1924        table_reference,
1925        // Nullable: null-aware `LeftMark` joins use NULL to represent SQL
1926        // UNKNOWN for `NOT IN`. Other mark joins simply never produce a NULL.
1927        Arc::new(Field::new("mark", DataType::Boolean, true)),
1928    )
1929}
1930
1931/// Creates a schema for a join operation.
1932/// The fields from the left side are first
1933pub fn build_join_schema(
1934    left: &DFSchema,
1935    right: &DFSchema,
1936    join_type: &JoinType,
1937) -> Result<DFSchema> {
1938    fn nullify_fields<'a>(
1939        fields: impl Iterator<Item = (Option<&'a TableReference>, &'a Arc<Field>)>,
1940    ) -> Vec<(Option<TableReference>, Arc<Field>)> {
1941        fields
1942            .map(|(q, f)| {
1943                // TODO: find a good way to do that
1944                let field = f.as_ref().clone().with_nullable(true);
1945                (q.cloned(), Arc::new(field))
1946            })
1947            .collect()
1948    }
1949
1950    let right_fields = right.iter();
1951    let left_fields = left.iter();
1952
1953    let qualified_fields: Vec<(Option<TableReference>, Arc<Field>)> = match join_type {
1954        JoinType::Inner => {
1955            // left then right
1956            let left_fields = left_fields
1957                .map(|(q, f)| (q.cloned(), Arc::clone(f)))
1958                .collect::<Vec<_>>();
1959            let right_fields = right_fields
1960                .map(|(q, f)| (q.cloned(), Arc::clone(f)))
1961                .collect::<Vec<_>>();
1962            left_fields.into_iter().chain(right_fields).collect()
1963        }
1964        JoinType::Left => {
1965            // left then right, right set to nullable in case of not matched scenario
1966            let left_fields = left_fields
1967                .map(|(q, f)| (q.cloned(), Arc::clone(f)))
1968                .collect::<Vec<_>>();
1969            left_fields
1970                .into_iter()
1971                .chain(nullify_fields(right_fields))
1972                .collect()
1973        }
1974        JoinType::Right => {
1975            // left then right, left set to nullable in case of not matched scenario
1976            let right_fields = right_fields
1977                .map(|(q, f)| (q.cloned(), Arc::clone(f)))
1978                .collect::<Vec<_>>();
1979            nullify_fields(left_fields)
1980                .into_iter()
1981                .chain(right_fields)
1982                .collect()
1983        }
1984        JoinType::Full => {
1985            // left then right, all set to nullable in case of not matched scenario
1986            nullify_fields(left_fields)
1987                .into_iter()
1988                .chain(nullify_fields(right_fields))
1989                .collect()
1990        }
1991        JoinType::LeftSemi | JoinType::LeftAnti => {
1992            // Only use the left side for the schema
1993            left_fields
1994                .map(|(q, f)| (q.cloned(), Arc::clone(f)))
1995                .collect()
1996        }
1997        JoinType::LeftMark => left_fields
1998            .map(|(q, f)| (q.cloned(), Arc::clone(f)))
1999            .chain(once(mark_field(right)))
2000            .collect(),
2001        JoinType::RightSemi | JoinType::RightAnti => {
2002            // Only use the right side for the schema
2003            right_fields
2004                .map(|(q, f)| (q.cloned(), Arc::clone(f)))
2005                .collect()
2006        }
2007        JoinType::RightMark => right_fields
2008            .map(|(q, f)| (q.cloned(), Arc::clone(f)))
2009            .chain(once(mark_field(left)))
2010            .collect(),
2011    };
2012    let func_dependencies = left.functional_dependencies().join(
2013        right.functional_dependencies(),
2014        join_type,
2015        left.fields().len(),
2016    );
2017
2018    let (schema1, schema2) = match join_type {
2019        JoinType::Right
2020        | JoinType::RightSemi
2021        | JoinType::RightAnti
2022        | JoinType::RightMark => (left, right),
2023        _ => (right, left),
2024    };
2025
2026    let mut metadata = schema1.metadata().clone();
2027    metadata.extend(schema2.metadata().clone());
2028
2029    let dfschema = DFSchema::new_with_metadata(qualified_fields, metadata)?;
2030    dfschema.with_functional_dependencies(func_dependencies)
2031}
2032
2033/// Creates the schema for a left-preserving ASOF join.
2034///
2035/// Both `ON` and `USING` preserve all qualified input fields. SQL wildcard
2036/// expansion handles the unqualified `USING` key as a single column.
2037pub fn build_asof_join_schema(left: &DFSchema, right: &DFSchema) -> Result<DFSchema> {
2038    // ASOF emits exactly one output row for each left row. Unlike a general
2039    // left join, it cannot duplicate left rows, so left dependencies retain
2040    // their modes. Right dependencies remain valid but not unique because one
2041    // right row may match multiple left rows.
2042    let schema = build_join_schema(left, right, &JoinType::Left)?;
2043    // `build_join_schema` places the downgraded left dependencies before the
2044    // nullable, non-unique right dependencies. Replace only the left prefix.
2045    let left_dependencies_len = left.functional_dependencies().len();
2046    let right_dependencies =
2047        schema.functional_dependencies()[left_dependencies_len..].to_vec();
2048    let mut dependencies = left.functional_dependencies().clone();
2049    dependencies.extend_target_indices(schema.fields().len());
2050    dependencies.extend(FunctionalDependencies::new(right_dependencies));
2051    schema.with_functional_dependencies(dependencies)
2052}
2053
2054/// (Re)qualify the sides of a join if needed, i.e. if the columns from one side would otherwise
2055/// conflict with the columns from the other.
2056/// This is especially useful for queries that come as Substrait, since Substrait doesn't currently allow specifying
2057/// aliases, neither for columns nor for tables.  DataFusion requires columns to be uniquely identifiable, in some
2058/// places (see e.g. DFSchema::check_names).
2059/// The function returns:
2060/// - The requalified or original left logical plan
2061/// - The requalified or original right logical plan
2062/// - If a requalification was needed or not
2063pub fn requalify_sides_if_needed(
2064    left: LogicalPlanBuilder,
2065    right: LogicalPlanBuilder,
2066) -> Result<(LogicalPlanBuilder, LogicalPlanBuilder, bool)> {
2067    let left_cols = left.schema().columns();
2068    let right_cols = right.schema().columns();
2069
2070    // Requalify if merging the schemas would cause an error during join.
2071    // This can happen in several cases:
2072    // 1. Duplicate qualified fields: both sides have same relation.name
2073    // 2. Duplicate unqualified fields: both sides have same unqualified name
2074    // 3. Ambiguous reference: one side qualified, other unqualified, same name
2075    //
2076    // Implementation note: This uses a simple O(n*m) nested loop rather than
2077    // a HashMap-based O(n+m) approach. The nested loop is preferred because:
2078    // - Schemas are typically small (in TPCH benchmark, max is 16 columns),
2079    //   so n*m is negligible
2080    // - Early return on first conflict makes common case very fast
2081    // - Code is simpler and easier to reason about
2082    // - Called only during plan construction, not in execution hot path
2083    for l in &left_cols {
2084        for r in &right_cols {
2085            if l.name != r.name {
2086                continue;
2087            }
2088
2089            // Same name - check if this would cause a conflict
2090            match (&l.relation, &r.relation) {
2091                // Both qualified with same relation - duplicate qualified field
2092                (Some(l_rel), Some(r_rel)) if l_rel == r_rel => {
2093                    return Ok((
2094                        left.alias(TableReference::bare("left"))?,
2095                        right.alias(TableReference::bare("right"))?,
2096                        true,
2097                    ));
2098                }
2099                // Both unqualified - duplicate unqualified field
2100                (None, None) => {
2101                    return Ok((
2102                        left.alias(TableReference::bare("left"))?,
2103                        right.alias(TableReference::bare("right"))?,
2104                        true,
2105                    ));
2106                }
2107                // One qualified, one not - ambiguous reference
2108                (Some(_), None) | (None, Some(_)) => {
2109                    return Ok((
2110                        left.alias(TableReference::bare("left"))?,
2111                        right.alias(TableReference::bare("right"))?,
2112                        true,
2113                    ));
2114                }
2115                // Different qualifiers - OK, no conflict
2116                _ => {}
2117            }
2118        }
2119    }
2120
2121    // No conflicts found
2122    Ok((left, right, false))
2123}
2124/// Add additional "synthetic" group by expressions based on functional
2125/// dependencies.
2126///
2127/// For example, if we are grouping on `[c1]`, and we know from
2128/// functional dependencies that column `c1` determines `c2`, this function
2129/// adds `c2` to the group by list.
2130///
2131/// This allows MySQL style selects like
2132/// `SELECT col FROM t WHERE pk = 5` if col is unique
2133pub fn add_group_by_exprs_from_dependencies(
2134    mut group_expr: Vec<Expr>,
2135    schema: &DFSchemaRef,
2136) -> Result<Vec<Expr>> {
2137    // With no functional dependencies on the input schema,
2138    // `get_target_functional_dependencies` below can never resolve any
2139    // target indices, so skip formatting the GROUP BY expression names and
2140    // return the GROUP BY list unchanged.
2141    if schema.functional_dependencies().is_empty() {
2142        return Ok(group_expr);
2143    }
2144
2145    // The input field that each GROUP BY expression passes through, or `None`
2146    // for a computed expression such as `c1 + 1`
2147    let mut group_by_input_indices = group_expr
2148        .iter()
2149        .map(|e| passthrough_field_index(e, schema))
2150        .collect::<Vec<_>>();
2151
2152    if let Some(target_indices) =
2153        get_target_functional_dependencies(schema, &group_by_input_indices)
2154    {
2155        for idx in target_indices {
2156            if !group_by_input_indices.contains(&Some(idx)) {
2157                group_by_input_indices.push(Some(idx));
2158                group_expr.push(Expr::Column(Column::from(schema.qualified_field(idx))));
2159            }
2160        }
2161    }
2162    Ok(group_expr)
2163}
2164
2165/// Errors if one or more expressions have equal names.
2166pub fn validate_unique_names<'a>(
2167    node_name: &str,
2168    expressions: impl IntoIterator<Item = &'a Expr>,
2169) -> Result<()> {
2170    let expressions = expressions.into_iter();
2171    let mut unique_names = HashMap::with_capacity(expressions.size_hint().0);
2172
2173    expressions.enumerate().try_for_each(|(position, expr)| {
2174        let name = expr.schema_name().to_string();
2175        match unique_names.get(&name) {
2176            None => {
2177                unique_names.insert(name, (position, expr));
2178                Ok(())
2179            },
2180            Some((existing_position, existing_expr)) => {
2181                plan_err!("{node_name} require unique expression names \
2182                             but the expression \"{existing_expr}\" at position {existing_position} and \"{expr}\" \
2183                             at position {position} have the same name. Consider aliasing (\"AS\") one of them."
2184                            )
2185            }
2186        }
2187    })
2188}
2189
2190/// Union two [`LogicalPlan`]s.
2191///
2192/// Infers common output types, but does not insert casts into the inputs.
2193/// The analyzer must still resolve input expressions and insert any required casts.
2194///
2195/// If a properly typed UNION plan is needed, refer to [`TypeCoercionRewriter::coerce_union`]
2196/// or alternatively, merge the union input schema using [`coerce_union_schema`] and
2197/// apply the expression rewrite with [`coerce_plan_expr_for_schema`].
2198///
2199/// [`TypeCoercionRewriter::coerce_union`]: https://docs.rs/datafusion-optimizer/latest/datafusion_optimizer/analyzer/type_coercion/struct.TypeCoercionRewriter.html#method.coerce_union
2200/// [`coerce_union_schema`]: https://docs.rs/datafusion-optimizer/latest/datafusion_optimizer/analyzer/type_coercion/fn.coerce_union_schema.html
2201pub fn union(left_plan: LogicalPlan, right_plan: LogicalPlan) -> Result<LogicalPlan> {
2202    Ok(LogicalPlan::Union(Union::try_new_with_loose_types(vec![
2203        Arc::new(left_plan),
2204        Arc::new(right_plan),
2205    ])?))
2206}
2207
2208/// Like [`union`], but combine rows from different tables by name, rather than
2209/// by position.
2210pub fn union_by_name(
2211    left_plan: LogicalPlan,
2212    right_plan: LogicalPlan,
2213) -> Result<LogicalPlan> {
2214    Ok(LogicalPlan::Union(Union::try_new_by_name(vec![
2215        Arc::new(left_plan),
2216        Arc::new(right_plan),
2217    ])?))
2218}
2219
2220/// Create Projection
2221/// # Errors
2222/// This function errors under any of the following conditions:
2223/// * Two or more expressions have the same name
2224/// * An invalid expression is used (e.g. a `sort` expression)
2225pub fn project(
2226    plan: LogicalPlan,
2227    expr: impl IntoIterator<Item = impl Into<SelectExpr>>,
2228) -> Result<LogicalPlan> {
2229    project_with_validation(plan, expr.into_iter().map(|e| (e, true)), None)
2230}
2231
2232/// Create Projection. Similar to project except that the expressions
2233/// passed in have a flag to indicate if that expression requires
2234/// validation (normalize & columnize) (true) or not (false)
2235/// # Errors
2236/// This function errors under any of the following conditions:
2237/// * Two or more expressions have the same name
2238/// * An invalid expression is used (e.g. a `sort` expression)
2239fn project_with_validation(
2240    plan: LogicalPlan,
2241    expr: impl IntoIterator<Item = (impl Into<SelectExpr>, bool)>,
2242    schema: Option<&DFSchemaRef>,
2243) -> Result<LogicalPlan> {
2244    let mut projected_expr = vec![];
2245    let mut has_wildcard = false;
2246    let mut normalizer = ColumnNormalizer::new(&plan);
2247    let columnizer = Columnizer::new(&plan);
2248    for (e, validate) in expr {
2249        let mut push_validated = |e: Expr| -> Result<()> {
2250            if validate {
2251                projected_expr.push(columnizer.columnize(normalizer.normalize(e)?)?)
2252            } else {
2253                projected_expr.push(e)
2254            }
2255            Ok(())
2256        };
2257        match e.into() {
2258            SelectExpr::Wildcard(opt) => {
2259                has_wildcard = true;
2260                let expanded = expand_wildcard(plan.schema(), &plan, Some(&opt))?;
2261                apply_replace(expanded, opt.replace.as_ref())?
2262                    .into_iter()
2263                    .try_for_each(push_validated)?;
2264            }
2265            SelectExpr::QualifiedWildcard(table_ref, opt) => {
2266                has_wildcard = true;
2267                let expanded =
2268                    expand_qualified_wildcard(&table_ref, plan.schema(), Some(&opt))?;
2269                apply_replace(expanded, opt.replace.as_ref())?
2270                    .into_iter()
2271                    .try_for_each(push_validated)?;
2272            }
2273            SelectExpr::Expression(e) => push_validated(e)?,
2274        }
2275    }
2276
2277    if has_wildcard && projected_expr.is_empty() && !plan.schema().fields().is_empty() {
2278        return plan_err!(
2279            "SELECT list is empty after resolving * expressions, \
2280             the wildcard expanded to zero columns"
2281        );
2282    }
2283
2284    // When inside a set expression, alias non-Column/non-Alias expressions
2285    // to match the left side's field names, avoiding duplicate name errors.
2286    if let Some(schema) = &schema {
2287        for (expr, field) in projected_expr.iter_mut().zip(schema.fields()) {
2288            if !matches!(expr, Expr::Column(_) | Expr::Alias(_)) {
2289                *expr = std::mem::take(expr).alias(field.name());
2290            }
2291        }
2292    }
2293
2294    validate_unique_names("Projections", projected_expr.iter())?;
2295
2296    // `columnizer` borrows `plan`, which moves into the projection below.
2297    drop(columnizer);
2298    Projection::try_new(projected_expr, Arc::new(plan)).map(LogicalPlan::Projection)
2299}
2300
2301/// Applies a wildcard's REPLACE statement, if it has one, to the columns the
2302/// wildcard expanded to.
2303fn apply_replace(
2304    expanded: Vec<Expr>,
2305    replace: Option<&PlannedReplaceSelectItem>,
2306) -> Result<Vec<Expr>> {
2307    match replace {
2308        Some(replace) => replace_columns(expanded, replace),
2309        None => Ok(expanded),
2310    }
2311}
2312
2313/// If there is a REPLACE statement in the projected expression in the form of
2314/// "REPLACE (some_column_within_an_expr AS some_column)", this function replaces
2315/// that column with the given replace expression. Column name remains the same.
2316/// Multiple REPLACEs are also possible with comma separations.
2317fn replace_columns(
2318    mut exprs: Vec<Expr>,
2319    replace: &PlannedReplaceSelectItem,
2320) -> Result<Vec<Expr>> {
2321    for expr in exprs.iter_mut() {
2322        if let Expr::Column(Column { name, .. }) = expr
2323            && let Some((_, new_expr)) = replace
2324                .items()
2325                .iter()
2326                .zip(replace.expressions().iter())
2327                .find(|(item, _)| item.column_name.value == *name)
2328        {
2329            *expr = new_expr.clone().alias(name.clone())
2330        }
2331    }
2332    Ok(exprs)
2333}
2334
2335/// Create a SubqueryAlias to wrap a LogicalPlan.
2336pub fn subquery_alias(
2337    plan: LogicalPlan,
2338    alias: impl Into<TableReference>,
2339) -> Result<LogicalPlan> {
2340    SubqueryAlias::try_new(Arc::new(plan), alias).map(LogicalPlan::SubqueryAlias)
2341}
2342
2343/// Create a LogicalPlanBuilder representing a scan of a table with the provided name and schema.
2344/// This is mostly used for testing and documentation.
2345pub fn table_scan(
2346    name: Option<impl Into<TableReference>>,
2347    table_schema: &Schema,
2348    projection: Option<Vec<usize>>,
2349) -> Result<LogicalPlanBuilder> {
2350    table_scan_with_filters(name, table_schema, projection, vec![])
2351}
2352
2353/// Create a LogicalPlanBuilder representing a scan of a table with the provided name and schema,
2354/// and inlined filters.
2355/// This is mostly used for testing and documentation.
2356pub fn table_scan_with_filters(
2357    name: Option<impl Into<TableReference>>,
2358    table_schema: &Schema,
2359    projection: Option<Vec<usize>>,
2360    filters: Vec<Expr>,
2361) -> Result<LogicalPlanBuilder> {
2362    table_scan_with_filter_and_fetch(name, table_schema, projection, filters, None)
2363}
2364
2365/// Create a LogicalPlanBuilder representing a scan of a table with the provided name and schema,
2366/// filters, and inlined fetch.
2367/// This is mostly used for testing and documentation.
2368pub fn table_scan_with_filter_and_fetch(
2369    name: Option<impl Into<TableReference>>,
2370    table_schema: &Schema,
2371    projection: Option<Vec<usize>>,
2372    filters: Vec<Expr>,
2373    fetch: Option<usize>,
2374) -> Result<LogicalPlanBuilder> {
2375    table_scan_with_filter_and_fetch_and_skip(
2376        name,
2377        table_schema,
2378        projection,
2379        filters,
2380        fetch,
2381        None,
2382    )
2383}
2384
2385/// Create a LogicalPlanBuilder representing a scan of a table with the provided name and schema,
2386/// filters, inlined fetch and offset.
2387/// This is mostly used for testing and documentation.
2388pub fn table_scan_with_filter_and_fetch_and_skip(
2389    name: Option<impl Into<TableReference>>,
2390    table_schema: &Schema,
2391    projection: Option<Vec<usize>>,
2392    filters: Vec<Expr>,
2393    fetch: Option<usize>,
2394    skip: Option<usize>,
2395) -> Result<LogicalPlanBuilder> {
2396    let table_source = table_source(table_schema);
2397    let name = name
2398        .map(|n| n.into())
2399        .unwrap_or_else(|| TableReference::bare(UNNAMED_TABLE));
2400    let table_scan = TableScanBuilder::new(name, table_source)
2401        .with_projection(projection)
2402        .with_filters(filters)
2403        .with_fetch(fetch)
2404        .with_skip(skip)
2405        .build()?;
2406    LogicalPlanBuilder::table_scan(table_scan)
2407}
2408
2409pub fn table_source(table_schema: &Schema) -> Arc<dyn TableSource> {
2410    // TODO should we take SchemaRef and avoid cloning?
2411    let table_schema = Arc::new(table_schema.clone());
2412    Arc::new(LogicalTableSource {
2413        table_schema,
2414        constraints: Default::default(),
2415    })
2416}
2417
2418pub fn table_source_with_constraints(
2419    table_schema: &Schema,
2420    constraints: Constraints,
2421) -> Arc<dyn TableSource> {
2422    // TODO should we take SchemaRef and avoid cloning?
2423    let table_schema = Arc::new(table_schema.clone());
2424    Arc::new(LogicalTableSource {
2425        table_schema,
2426        constraints,
2427    })
2428}
2429
2430/// Wrap projection for a plan, if the join keys contains normal expression.
2431pub fn wrap_projection_for_join_if_necessary(
2432    join_keys: &[Expr],
2433    input: LogicalPlan,
2434) -> Result<(LogicalPlan, Vec<Column>, bool)> {
2435    let input_schema = input.schema();
2436    let alias_join_keys: Vec<Expr> = join_keys
2437        .iter()
2438        .map(|key| {
2439            // The display_name() of cast expression will ignore the cast info, and show the inner expression name.
2440            // If we do not add alias, it will throw same field name error in the schema when adding projection.
2441            // For example:
2442            //    input scan : [a, b, c],
2443            //    join keys: [cast(a as int)]
2444            //
2445            //  then a and cast(a as int) will use the same field name - `a` in projection schema.
2446            //  https://github.com/apache/datafusion/issues/4478
2447            if matches!(key, Expr::Cast(_)) || matches!(key, Expr::TryCast(_)) {
2448                let alias = format!("{key}");
2449                key.clone().alias(alias)
2450            } else {
2451                key.clone()
2452            }
2453        })
2454        .collect::<Vec<_>>();
2455
2456    let need_project = join_keys.iter().any(|key| !matches!(key, Expr::Column(_)));
2457    let plan = if need_project {
2458        // Include all columns from the input and extend them with the join keys
2459        let mut projection = input_schema
2460            .columns()
2461            .into_iter()
2462            .map(Expr::Column)
2463            .collect::<Vec<_>>();
2464        #[allow(clippy::allow_attributes, clippy::mutable_key_type)]
2465        // Expr contains Arc with interior mutability but is intentionally used as hash key
2466        let join_key_items = alias_join_keys
2467            .iter()
2468            .filter(|expr| expr.try_as_col().is_none())
2469            .cloned()
2470            .collect::<HashSet<Expr>>();
2471        projection.extend(join_key_items);
2472
2473        LogicalPlanBuilder::from(input)
2474            .project(projection.into_iter().map(SelectExpr::from))?
2475            .build()?
2476    } else {
2477        input
2478    };
2479
2480    let join_on = alias_join_keys
2481        .into_iter()
2482        .map(|key| {
2483            if let Some(col) = key.try_as_col() {
2484                Ok(col.clone())
2485            } else {
2486                let name = key.schema_name().to_string();
2487                Ok(Column::from_name(name))
2488            }
2489        })
2490        .collect::<Result<Vec<_>>>()?;
2491
2492    Ok((plan, join_on, need_project))
2493}
2494
2495/// Basic TableSource implementation intended for use in tests and documentation. It is expected
2496/// that users will provide their own TableSource implementations or use DataFusion's
2497/// DefaultTableSource.
2498pub struct LogicalTableSource {
2499    table_schema: SchemaRef,
2500    constraints: Constraints,
2501}
2502
2503impl LogicalTableSource {
2504    /// Create a new LogicalTableSource
2505    pub fn new(table_schema: SchemaRef) -> Self {
2506        Self {
2507            table_schema,
2508            constraints: Constraints::default(),
2509        }
2510    }
2511
2512    pub fn with_constraints(mut self, constraints: Constraints) -> Self {
2513        self.constraints = constraints;
2514        self
2515    }
2516}
2517
2518impl TableSource for LogicalTableSource {
2519    fn schema(&self) -> SchemaRef {
2520        Arc::clone(&self.table_schema)
2521    }
2522
2523    fn constraints(&self) -> Option<&Constraints> {
2524        Some(&self.constraints)
2525    }
2526
2527    fn supports_filters_pushdown(
2528        &self,
2529        filters: &[&Expr],
2530    ) -> Result<Vec<TableProviderFilterPushDown>> {
2531        Ok(vec![TableProviderFilterPushDown::Exact; filters.len()])
2532    }
2533}
2534
2535/// Create a [`LogicalPlan::Unnest`] plan
2536pub fn unnest(input: LogicalPlan, columns: Vec<Column>) -> Result<LogicalPlan> {
2537    unnest_with_options(input, columns, UnnestOptions::default())
2538}
2539
2540pub fn get_struct_unnested_columns(
2541    col_name: &String,
2542    inner_fields: &Fields,
2543) -> Vec<Column> {
2544    inner_fields
2545        .iter()
2546        .map(|f| Column::from_name(format!("{}.{}", col_name, f.name())))
2547        .collect()
2548}
2549
2550/// Create a [`LogicalPlan::Unnest`] plan with options
2551/// This function receive a list of columns to be unnested
2552/// because multiple unnest can be performed on the same column (e.g unnest with different depth)
2553/// The new schema will contains post-unnest fields replacing the original field
2554///
2555/// For example:
2556/// Input schema as
2557/// ```text
2558/// +---------------------+-------------------+
2559/// | col1                | col2              |
2560/// +---------------------+-------------------+
2561/// | Struct(INT64,INT32) | List(List(Int64)) |
2562/// +---------------------+-------------------+
2563/// ```
2564///
2565///
2566///
2567/// Then unnesting columns with:
2568/// - (col1,Struct)
2569/// - (col2,List(\[depth=1,depth=2\]))
2570///
2571/// will generate a new schema as
2572/// ```text
2573/// +---------+---------+---------------------+---------------------+
2574/// | col1.c0 | col1.c1 | unnest_col2_depth_1 | unnest_col2_depth_2 |
2575/// +---------+---------+---------------------+---------------------+
2576/// | Int64   | Int32   | List(Int64)         |  Int64              |
2577/// +---------+---------+---------------------+---------------------+
2578/// ```
2579pub fn unnest_with_options(
2580    input: LogicalPlan,
2581    columns_to_unnest: Vec<Column>,
2582    options: UnnestOptions,
2583) -> Result<LogicalPlan> {
2584    Ok(LogicalPlan::Unnest(Unnest::try_new(
2585        Arc::new(input),
2586        columns_to_unnest,
2587        options,
2588    )?))
2589}
2590
2591#[cfg(test)]
2592mod tests {
2593    use std::vec;
2594
2595    use super::*;
2596    use crate::lit_with_metadata;
2597    use crate::logical_plan::StringifiedPlan;
2598    use crate::{col, expr, expr_fn::exists, in_subquery, scalar_subquery};
2599
2600    use crate::test::function_stub::sum;
2601    use datafusion_common::{
2602        Constraint, DataFusionError, Dependency, FunctionalDependence,
2603        FunctionalDependencies, RecursionUnnestOption, SchemaError,
2604    };
2605    use insta::assert_snapshot;
2606
2607    #[test]
2608    fn plan_builder_simple() -> Result<()> {
2609        let plan =
2610            table_scan(Some("employee_csv"), &employee_schema(), Some(vec![0, 3]))?
2611                .filter(col("state").eq(lit("CO")))?
2612                .project(vec![col("id")])?
2613                .build()?;
2614
2615        assert_snapshot!(plan, @r#"
2616        Projection: employee_csv.id
2617          Filter: employee_csv.state = Utf8("CO")
2618            TableScan: employee_csv projection=[id, state]
2619        "#);
2620
2621        Ok(())
2622    }
2623
2624    #[test]
2625    fn plan_builder_schema() {
2626        let schema = employee_schema();
2627        let projection = None;
2628        let plan =
2629            LogicalPlanBuilder::scan("employee_csv", table_source(&schema), projection)
2630                .unwrap();
2631        assert_snapshot!(plan.schema().as_ref(), @"fields:[employee_csv.id, employee_csv.first_name, employee_csv.last_name, employee_csv.state, employee_csv.salary], metadata:{}");
2632
2633        // Note scan of "EMPLOYEE_CSV" is treated as a SQL identifier
2634        // (and thus normalized to "employee"csv") as well
2635        let projection = None;
2636        let plan =
2637            LogicalPlanBuilder::scan("EMPLOYEE_CSV", table_source(&schema), projection)
2638                .unwrap();
2639        assert_snapshot!(plan.schema().as_ref(), @"fields:[employee_csv.id, employee_csv.first_name, employee_csv.last_name, employee_csv.state, employee_csv.salary], metadata:{}");
2640    }
2641
2642    #[test]
2643    fn plan_builder_empty_name() {
2644        let schema = employee_schema();
2645        let projection = None;
2646        let err =
2647            LogicalPlanBuilder::scan("", table_source(&schema), projection).unwrap_err();
2648        assert_snapshot!(
2649            err.strip_backtrace(),
2650            @"Error during planning: table_name cannot be empty"
2651        );
2652    }
2653
2654    #[test]
2655    fn plan_builder_sort() -> Result<()> {
2656        let plan =
2657            table_scan(Some("employee_csv"), &employee_schema(), Some(vec![3, 4]))?
2658                .sort(vec![
2659                    expr::Sort::new(col("state"), true, true),
2660                    expr::Sort::new(col("salary"), false, false),
2661                ])?
2662                .build()?;
2663
2664        assert_snapshot!(plan, @r"
2665        Sort: employee_csv.state ASC NULLS FIRST, employee_csv.salary DESC NULLS LAST
2666          TableScan: employee_csv projection=[state, salary]
2667        ");
2668
2669        Ok(())
2670    }
2671
2672    #[test]
2673    fn plan_builder_union() -> Result<()> {
2674        let plan =
2675            table_scan(Some("employee_csv"), &employee_schema(), Some(vec![3, 4]))?;
2676
2677        let plan = plan
2678            .clone()
2679            .union(plan.clone().build()?)?
2680            .union(plan.clone().build()?)?
2681            .union(plan.build()?)?
2682            .build()?;
2683
2684        assert_snapshot!(plan, @r"
2685        Union
2686          Union
2687            Union
2688              TableScan: employee_csv projection=[state, salary]
2689              TableScan: employee_csv projection=[state, salary]
2690            TableScan: employee_csv projection=[state, salary]
2691          TableScan: employee_csv projection=[state, salary]
2692        ");
2693
2694        Ok(())
2695    }
2696
2697    #[test]
2698    fn plan_builder_union_distinct() -> Result<()> {
2699        let plan =
2700            table_scan(Some("employee_csv"), &employee_schema(), Some(vec![3, 4]))?;
2701
2702        let plan = plan
2703            .clone()
2704            .union_distinct(plan.clone().build()?)?
2705            .union_distinct(plan.clone().build()?)?
2706            .union_distinct(plan.build()?)?
2707            .build()?;
2708
2709        assert_snapshot!(plan, @r"
2710        Distinct:
2711          Union
2712            Distinct:
2713              Union
2714                Distinct:
2715                  Union
2716                    TableScan: employee_csv projection=[state, salary]
2717                    TableScan: employee_csv projection=[state, salary]
2718                TableScan: employee_csv projection=[state, salary]
2719            TableScan: employee_csv projection=[state, salary]
2720        ");
2721
2722        Ok(())
2723    }
2724
2725    #[test]
2726    fn plan_builder_simple_distinct() -> Result<()> {
2727        let plan =
2728            table_scan(Some("employee_csv"), &employee_schema(), Some(vec![0, 3]))?
2729                .filter(col("state").eq(lit("CO")))?
2730                .project(vec![col("id")])?
2731                .distinct()?
2732                .build()?;
2733
2734        assert_snapshot!(plan, @r#"
2735        Distinct:
2736          Projection: employee_csv.id
2737            Filter: employee_csv.state = Utf8("CO")
2738              TableScan: employee_csv projection=[id, state]
2739        "#);
2740
2741        Ok(())
2742    }
2743
2744    #[test]
2745    fn exists_subquery() -> Result<()> {
2746        let foo = test_table_scan_with_name("foo")?;
2747        let bar = test_table_scan_with_name("bar")?;
2748
2749        let subquery = LogicalPlanBuilder::from(foo)
2750            .project(vec![col("a")])?
2751            .filter(col("a").eq(col("bar.a")))?
2752            .build()?;
2753
2754        let outer_query = LogicalPlanBuilder::from(bar)
2755            .project(vec![col("a")])?
2756            .filter(exists(Arc::new(subquery)))?
2757            .build()?;
2758
2759        assert_snapshot!(outer_query, @r"
2760        Filter: EXISTS (<subquery>)
2761          Subquery:
2762            Filter: foo.a = bar.a
2763              Projection: foo.a
2764                TableScan: foo
2765          Projection: bar.a
2766            TableScan: bar
2767        ");
2768
2769        Ok(())
2770    }
2771
2772    #[test]
2773    fn filter_in_subquery() -> Result<()> {
2774        let foo = test_table_scan_with_name("foo")?;
2775        let bar = test_table_scan_with_name("bar")?;
2776
2777        let subquery = LogicalPlanBuilder::from(foo)
2778            .project(vec![col("a")])?
2779            .filter(col("a").eq(col("bar.a")))?
2780            .build()?;
2781
2782        // SELECT a FROM bar WHERE a IN (SELECT a FROM foo WHERE a = bar.a)
2783        let outer_query = LogicalPlanBuilder::from(bar)
2784            .project(vec![col("a")])?
2785            .filter(in_subquery(col("a"), Arc::new(subquery)))?
2786            .build()?;
2787
2788        assert_snapshot!(outer_query, @r"
2789        Filter: bar.a IN (<subquery>)
2790          Subquery:
2791            Filter: foo.a = bar.a
2792              Projection: foo.a
2793                TableScan: foo
2794          Projection: bar.a
2795            TableScan: bar
2796        ");
2797
2798        Ok(())
2799    }
2800
2801    #[test]
2802    fn select_scalar_subquery() -> Result<()> {
2803        let foo = test_table_scan_with_name("foo")?;
2804        let bar = test_table_scan_with_name("bar")?;
2805
2806        let subquery = LogicalPlanBuilder::from(foo)
2807            .project(vec![col("b")])?
2808            .filter(col("a").eq(col("bar.a")))?
2809            .build()?;
2810
2811        // SELECT (SELECT a FROM foo WHERE a = bar.a) FROM bar
2812        let outer_query = LogicalPlanBuilder::from(bar)
2813            .project(vec![scalar_subquery(Arc::new(subquery))])?
2814            .build()?;
2815
2816        assert_snapshot!(outer_query, @r"
2817        Projection: (<subquery>)
2818          Subquery:
2819            Filter: foo.a = bar.a
2820              Projection: foo.b
2821                TableScan: foo
2822          TableScan: bar
2823        ");
2824
2825        Ok(())
2826    }
2827
2828    #[test]
2829    fn projection_non_unique_names() -> Result<()> {
2830        let plan = table_scan(
2831            Some("employee_csv"),
2832            &employee_schema(),
2833            // project id and first_name by column index
2834            Some(vec![0, 1]),
2835        )?
2836        // two columns with the same name => error
2837        .project(vec![col("id"), col("first_name").alias("id")]);
2838
2839        match plan {
2840            Err(DataFusionError::SchemaError(err, _)) => {
2841                if let SchemaError::AmbiguousReference { field } = *err {
2842                    let Column {
2843                        relation,
2844                        name,
2845                        spans: _,
2846                    } = *field;
2847                    let Some(TableReference::Bare { table }) = relation else {
2848                        return plan_err!(
2849                            "wrong relation: {relation:?}, expected table name"
2850                        );
2851                    };
2852                    assert_eq!(*"employee_csv", *table);
2853                    assert_eq!("id", &name);
2854                    Ok(())
2855                } else {
2856                    plan_err!("Plan should have returned an DataFusionError::SchemaError")
2857                }
2858            }
2859            _ => plan_err!("Plan should have returned an DataFusionError::SchemaError"),
2860        }
2861    }
2862
2863    fn employee_schema() -> Schema {
2864        Schema::new(vec![
2865            Field::new("id", DataType::Int32, false),
2866            Field::new("first_name", DataType::Utf8, false),
2867            Field::new("last_name", DataType::Utf8, false),
2868            Field::new("state", DataType::Utf8, false),
2869            Field::new("salary", DataType::Int32, false),
2870        ])
2871    }
2872
2873    #[test]
2874    fn stringified_plan() {
2875        let stringified_plan =
2876            StringifiedPlan::new(PlanType::InitialLogicalPlan, "...the plan...");
2877        assert!(stringified_plan.should_display(true));
2878        assert!(!stringified_plan.should_display(false)); // not in non verbose mode
2879
2880        let stringified_plan =
2881            StringifiedPlan::new(PlanType::FinalLogicalPlan, "...the plan...");
2882        assert!(stringified_plan.should_display(true));
2883        assert!(stringified_plan.should_display(false)); // display in non verbose mode too
2884
2885        let stringified_plan =
2886            StringifiedPlan::new(PlanType::InitialPhysicalPlan, "...the plan...");
2887        assert!(stringified_plan.should_display(true));
2888        assert!(!stringified_plan.should_display(false)); // not in non verbose mode
2889
2890        let stringified_plan =
2891            StringifiedPlan::new(PlanType::FinalPhysicalPlan, "...the plan...");
2892        assert!(stringified_plan.should_display(true));
2893        assert!(stringified_plan.should_display(false)); // display in non verbose mode
2894
2895        let stringified_plan = StringifiedPlan::new(
2896            PlanType::OptimizedLogicalPlan {
2897                optimizer_name: "random opt pass".into(),
2898            },
2899            "...the plan...",
2900        );
2901        assert!(stringified_plan.should_display(true));
2902        assert!(!stringified_plan.should_display(false));
2903    }
2904
2905    fn test_table_scan_with_name(name: &str) -> Result<LogicalPlan> {
2906        let schema = Schema::new(vec![
2907            Field::new("a", DataType::UInt32, false),
2908            Field::new("b", DataType::UInt32, false),
2909            Field::new("c", DataType::UInt32, false),
2910        ]);
2911        table_scan(Some(name), &schema, None)?.build()
2912    }
2913
2914    #[test]
2915    fn plan_builder_intersect_different_num_columns_error() -> Result<()> {
2916        let plan1 =
2917            table_scan(TableReference::none(), &employee_schema(), Some(vec![3]))?;
2918        let plan2 =
2919            table_scan(TableReference::none(), &employee_schema(), Some(vec![3, 4]))?;
2920
2921        let err_msg1 =
2922            LogicalPlanBuilder::intersect(plan1.build()?, plan2.build()?, true)
2923                .unwrap_err();
2924
2925        assert_snapshot!(err_msg1.strip_backtrace(), @"Error during planning: INTERSECT/EXCEPT query must have the same number of columns. Left is 1 and right is 2.");
2926
2927        Ok(())
2928    }
2929
2930    #[test]
2931    fn plan_builder_unnest() -> Result<()> {
2932        // Cannot unnest on a scalar column
2933        let err = nested_table_scan("test_table")?
2934            .unnest_column("scalar")
2935            .unwrap_err();
2936
2937        let DataFusionError::Internal(desc) = err else {
2938            return plan_err!("Plan should have returned an DataFusionError::Internal");
2939        };
2940
2941        let desc = (*desc
2942            .split(DataFusionError::BACK_TRACE_SEP)
2943            .collect::<Vec<&str>>()
2944            .first()
2945            .unwrap_or(&""))
2946        .to_string();
2947
2948        assert_snapshot!(desc, @"trying to unnest on invalid data type UInt32");
2949
2950        // Unnesting the strings list.
2951        let plan = nested_table_scan("test_table")?
2952            .unnest_column("strings")?
2953            .build()?;
2954
2955        assert_snapshot!(plan, @r"
2956        Unnest: lists[test_table.strings|depth=1] structs[]
2957          TableScan: test_table
2958        ");
2959
2960        // Check unnested field is a scalar
2961        let field = plan.schema().field_with_name(None, "strings").unwrap();
2962        assert_eq!(&DataType::Utf8, field.data_type());
2963
2964        // Unnesting the singular struct column result into 2 new columns for each subfield
2965        let plan = nested_table_scan("test_table")?
2966            .unnest_column("struct_singular")?
2967            .build()?;
2968
2969        assert_snapshot!(plan, @r"
2970        Unnest: lists[] structs[test_table.struct_singular]
2971          TableScan: test_table
2972        ");
2973
2974        for field_name in &["a", "b"] {
2975            // Check unnested struct field is a scalar
2976            let field = plan
2977                .schema()
2978                .field_with_name(None, &format!("struct_singular.{field_name}"))
2979                .unwrap();
2980            assert_eq!(&DataType::UInt32, field.data_type());
2981        }
2982
2983        // Unnesting multiple fields in separate plans
2984        let plan = nested_table_scan("test_table")?
2985            .unnest_column("strings")?
2986            .unnest_column("structs")?
2987            .unnest_column("struct_singular")?
2988            .build()?;
2989
2990        assert_snapshot!(plan, @r"
2991        Unnest: lists[] structs[test_table.struct_singular]
2992          Unnest: lists[test_table.structs|depth=1] structs[]
2993            Unnest: lists[test_table.strings|depth=1] structs[]
2994              TableScan: test_table
2995        ");
2996
2997        // Check unnested struct list field should be a struct.
2998        let field = plan.schema().field_with_name(None, "structs").unwrap();
2999        assert!(matches!(field.data_type(), DataType::Struct(_)));
3000
3001        // Unnesting multiple fields at the same time, using infer syntax
3002        let cols = vec!["strings", "structs", "struct_singular"]
3003            .into_iter()
3004            .map(|c| c.into())
3005            .collect();
3006
3007        let plan = nested_table_scan("test_table")?
3008            .unnest_columns_with_options(cols, UnnestOptions::default())?
3009            .build()?;
3010
3011        assert_snapshot!(plan, @r"
3012        Unnest: lists[test_table.strings|depth=1, test_table.structs|depth=1] structs[test_table.struct_singular]
3013          TableScan: test_table
3014        ");
3015
3016        // Unnesting missing column should fail.
3017        let plan = nested_table_scan("test_table")?.unnest_column("missing");
3018        assert!(plan.is_err());
3019
3020        // Simultaneously unnesting a list (with different depth) and a struct column
3021        let plan = nested_table_scan("test_table")?
3022            .unnest_columns_with_options(
3023                vec!["stringss".into(), "struct_singular".into()],
3024                UnnestOptions::default()
3025                    .with_recursions(RecursionUnnestOption {
3026                        input_column: "stringss".into(),
3027                        output_column: "stringss_depth_1".into(),
3028                        depth: 1,
3029                    })
3030                    .with_recursions(RecursionUnnestOption {
3031                        input_column: "stringss".into(),
3032                        output_column: "stringss_depth_2".into(),
3033                        depth: 2,
3034                    }),
3035            )?
3036            .build()?;
3037
3038        assert_snapshot!(plan, @r"
3039        Unnest: lists[test_table.stringss|depth=1, test_table.stringss|depth=2] structs[test_table.struct_singular]
3040          TableScan: test_table
3041        ");
3042
3043        // Check output columns has correct type
3044        let field = plan
3045            .schema()
3046            .field_with_name(None, "stringss_depth_1")
3047            .unwrap();
3048        assert_eq!(
3049            &DataType::new_list(DataType::Utf8, false),
3050            field.data_type()
3051        );
3052        let field = plan
3053            .schema()
3054            .field_with_name(None, "stringss_depth_2")
3055            .unwrap();
3056        assert_eq!(&DataType::Utf8, field.data_type());
3057        // unnesting struct is still correct
3058        for field_name in &["a", "b"] {
3059            let field = plan
3060                .schema()
3061                .field_with_name(None, &format!("struct_singular.{field_name}"))
3062                .unwrap();
3063            assert_eq!(&DataType::UInt32, field.data_type());
3064        }
3065
3066        Ok(())
3067    }
3068
3069    fn nested_table_scan(table_name: &str) -> Result<LogicalPlanBuilder> {
3070        // Create a schema with a scalar field, a list of strings, a list of structs
3071        // and a singular struct
3072        let struct_field_in_list = Field::new_struct(
3073            "item",
3074            vec![
3075                Field::new("a", DataType::UInt32, false),
3076                Field::new("b", DataType::UInt32, false),
3077            ],
3078            false,
3079        );
3080        let string_field = Field::new_list_field(DataType::Utf8, false);
3081        let strings_field = Field::new_list("item", string_field.clone(), false);
3082        let schema = Schema::new(vec![
3083            Field::new("scalar", DataType::UInt32, false),
3084            Field::new_list("strings", string_field, false),
3085            Field::new_list("structs", struct_field_in_list, false),
3086            Field::new(
3087                "struct_singular",
3088                DataType::Struct(Fields::from(vec![
3089                    Field::new("a", DataType::UInt32, false),
3090                    Field::new("b", DataType::UInt32, false),
3091                ])),
3092                false,
3093            ),
3094            Field::new_list("stringss", strings_field, false),
3095        ]);
3096
3097        table_scan(Some(table_name), &schema, None)
3098    }
3099
3100    #[test]
3101    fn test_union_after_join() -> Result<()> {
3102        let values = vec![vec![lit(1)]];
3103
3104        let left = LogicalPlanBuilder::values(values.clone())?
3105            .alias("left")?
3106            .build()?;
3107        let right = LogicalPlanBuilder::values(values)?
3108            .alias("right")?
3109            .build()?;
3110
3111        let join = LogicalPlanBuilder::from(left).cross_join(right)?.build()?;
3112
3113        let plan = LogicalPlanBuilder::from(join.clone())
3114            .union(join)?
3115            .build()?;
3116
3117        assert_snapshot!(plan, @r"
3118        Union
3119          Cross Join:
3120            SubqueryAlias: left
3121              Values: (Int32(1))
3122            SubqueryAlias: right
3123              Values: (Int32(1))
3124          Cross Join:
3125            SubqueryAlias: left
3126              Values: (Int32(1))
3127            SubqueryAlias: right
3128              Values: (Int32(1))
3129        ");
3130
3131        Ok(())
3132    }
3133
3134    #[test]
3135    fn asof_join_on_extracts_and_validates_conditions() -> Result<()> {
3136        let values = vec![vec![lit(1), lit(2)]];
3137        let left = LogicalPlanBuilder::values(values.clone())?
3138            .alias("l")?
3139            .build()?;
3140        let right = LogicalPlanBuilder::values(values)?.alias("r")?.build()?;
3141
3142        let plan = LogicalPlanBuilder::from(left.clone())
3143            .asof_join_on(
3144                right.clone(),
3145                Some(
3146                    col("r.column1")
3147                        .eq(col("l.column1"))
3148                        .and(col("l.column2").eq(col("r.column2"))),
3149                ),
3150                col("l.column2").gt_eq(col("r.column2")),
3151            )?
3152            .build()?;
3153        let LogicalPlan::AsOfJoin(join) = plan else {
3154            panic!("expected ASOF join")
3155        };
3156        assert_eq!(
3157            join.on,
3158            vec![
3159                (col("l.column1"), col("r.column1")),
3160                (col("l.column2"), col("r.column2")),
3161            ]
3162        );
3163        assert_eq!(
3164            join.match_condition.as_ref(),
3165            &AsOfMatch::new(col("l.column2"), Operator::GtEq, col("r.column2"))
3166        );
3167
3168        let invalid_on = LogicalPlanBuilder::from(left.clone())
3169            .asof_join_on(
3170                right.clone(),
3171                Some(col("l.column1").gt(col("r.column1"))),
3172                col("l.column2").gt_eq(col("r.column2")),
3173            )
3174            .expect_err("non-equality ASOF ON should fail");
3175        assert_snapshot!(invalid_on.strip_backtrace(), @r#"Error during planning: ASOF ON accepts only equality conditions combined with AND"#);
3176
3177        let invalid_match = LogicalPlanBuilder::from(left.clone())
3178            .asof_join_on(
3179                right.clone(),
3180                Some(col("l.column1").eq(col("r.column1"))),
3181                col("l.column2").eq(col("r.column2")),
3182            )
3183            .expect_err("equality ASOF MATCH_CONDITION should fail");
3184        assert_snapshot!(invalid_match.strip_backtrace(), @r#"Error during planning: ASOF MATCH_CONDITION requires <, <=, >, or >=, found ="#);
3185
3186        let reversed_match = LogicalPlanBuilder::from(left)
3187            .asof_join_on(
3188                right,
3189                Some(col("l.column1").eq(col("r.column1"))),
3190                col("r.column2").gt_eq(col("l.column2")),
3191            )
3192            .expect_err("reversed ASOF MATCH_CONDITION should fail");
3193        assert_snapshot!(reversed_match.strip_backtrace(), @r#"Error during planning: ASOF MATCH_CONDITION left operand must reference only the left input and right operand only the right input"#);
3194
3195        Ok(())
3196    }
3197
3198    #[test]
3199    fn plan_builder_from_logical_plan() -> Result<()> {
3200        let plan =
3201            table_scan(Some("employee_csv"), &employee_schema(), Some(vec![3, 4]))?
3202                .sort(vec![
3203                    expr::Sort::new(col("state"), true, true),
3204                    expr::Sort::new(col("salary"), false, false),
3205                ])?
3206                .build()?;
3207
3208        let plan_expected = format!("{plan}");
3209        let plan_builder: LogicalPlanBuilder = Arc::new(plan).into();
3210        assert_eq!(plan_expected, format!("{}", plan_builder.plan));
3211
3212        Ok(())
3213    }
3214
3215    #[test]
3216    fn plan_builder_aggregate_without_implicit_group_by_exprs() -> Result<()> {
3217        let constraints =
3218            Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
3219        let table_source = table_source_with_constraints(&employee_schema(), constraints);
3220
3221        let plan =
3222            LogicalPlanBuilder::scan("employee_csv", table_source, Some(vec![0, 3, 4]))?
3223                .aggregate(vec![col("id")], vec![sum(col("salary"))])?
3224                .build()?;
3225
3226        assert_snapshot!(plan, @r"
3227        Aggregate: groupBy=[[employee_csv.id]], aggr=[[sum(employee_csv.salary)]]
3228          TableScan: employee_csv projection=[id, state, salary]
3229        ");
3230
3231        Ok(())
3232    }
3233
3234    #[test]
3235    fn plan_builder_aggregate_with_implicit_group_by_exprs() -> Result<()> {
3236        let constraints =
3237            Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
3238        let table_source = table_source_with_constraints(&employee_schema(), constraints);
3239
3240        let options =
3241            LogicalPlanBuilderOptions::new().with_add_implicit_group_by_exprs(true);
3242        let plan =
3243            LogicalPlanBuilder::scan("employee_csv", table_source, Some(vec![0, 3, 4]))?
3244                .with_options(options)
3245                .aggregate(vec![col("id")], vec![sum(col("salary"))])?
3246                .build()?;
3247
3248        assert_snapshot!(plan, @r"
3249        Aggregate: groupBy=[[employee_csv.id, employee_csv.state, employee_csv.salary]], aggr=[[sum(employee_csv.salary)]]
3250          TableScan: employee_csv projection=[id, state, salary]
3251        ");
3252
3253        Ok(())
3254    }
3255
3256    #[test]
3257    fn plan_builder_aggregate_with_implicit_group_by_exprs_no_constraints() -> Result<()>
3258    {
3259        // With no PRIMARY KEY / UNIQUE constraint on the input, there are no
3260        // functional dependencies to expand the GROUP BY with, so the GROUP
3261        // BY list must be left exactly as given.
3262        let table_source = table_source(&employee_schema());
3263
3264        let options =
3265            LogicalPlanBuilderOptions::new().with_add_implicit_group_by_exprs(true);
3266        let plan =
3267            LogicalPlanBuilder::scan("employee_csv", table_source, Some(vec![0, 3, 4]))?
3268                .with_options(options)
3269                .aggregate(vec![col("id")], vec![sum(col("salary"))])?
3270                .build()?;
3271
3272        assert_snapshot!(plan, @r"
3273        Aggregate: groupBy=[[employee_csv.id]], aggr=[[sum(employee_csv.salary)]]
3274          TableScan: employee_csv projection=[id, state, salary]
3275        ");
3276
3277        Ok(())
3278    }
3279
3280    #[test]
3281    fn plan_builder_aggregate_nullable_unique_adds_no_implicit_group_by_exprs()
3282    -> Result<()> {
3283        // A nullable UNIQUE column permits multiple NULL rows that may differ
3284        // in the other columns, so it does not determine them across the
3285        // single NULL group and they must not be added to the GROUP BY.
3286        let schema = Schema::new(vec![
3287            Field::new("id", DataType::Int32, true),
3288            Field::new("state", DataType::Utf8, true),
3289            Field::new("salary", DataType::Int32, true),
3290        ]);
3291        let constraints = Constraints::new_unverified(vec![Constraint::Unique(vec![0])]);
3292        let table_source = table_source_with_constraints(&schema, constraints);
3293
3294        let options =
3295            LogicalPlanBuilderOptions::new().with_add_implicit_group_by_exprs(true);
3296        let plan = LogicalPlanBuilder::scan("employee_csv", table_source, None)?
3297            .with_options(options)
3298            .aggregate(vec![col("id")], vec![sum(col("salary"))])?
3299            .build()?;
3300
3301        assert_snapshot!(plan, @r"
3302        Aggregate: groupBy=[[employee_csv.id]], aggr=[[sum(employee_csv.salary)]]
3303          TableScan: employee_csv
3304        ");
3305
3306        Ok(())
3307    }
3308
3309    #[test]
3310    fn plan_builder_aggregate_not_null_unique_implicit_group_by_exprs() -> Result<()> {
3311        // A UNIQUE column declared NOT NULL has no NULL rows, so it determines
3312        // the other columns like a PRIMARY KEY and they are added to the
3313        // GROUP BY.
3314        let schema = Schema::new(vec![
3315            Field::new("id", DataType::Int32, false),
3316            Field::new("state", DataType::Utf8, true),
3317            Field::new("salary", DataType::Int32, true),
3318        ]);
3319        let constraints = Constraints::new_unverified(vec![Constraint::Unique(vec![0])]);
3320        let table_source = table_source_with_constraints(&schema, constraints);
3321
3322        let options =
3323            LogicalPlanBuilderOptions::new().with_add_implicit_group_by_exprs(true);
3324        let plan = LogicalPlanBuilder::scan("employee_csv", table_source, None)?
3325            .with_options(options)
3326            .aggregate(vec![col("id")], vec![sum(col("salary"))])?
3327            .build()?;
3328
3329        assert_snapshot!(plan, @r"
3330        Aggregate: groupBy=[[employee_csv.id, employee_csv.state, employee_csv.salary]], aggr=[[sum(employee_csv.salary)]]
3331          TableScan: employee_csv
3332        ");
3333
3334        Ok(())
3335    }
3336
3337    #[test]
3338    fn plan_builder_aggregate_rejects_nested_aggregates() -> Result<()> {
3339        // https://github.com/apache/datafusion/issues/23812
3340        let err = table_scan(
3341            Some("employee_csv"),
3342            &employee_schema(),
3343            Some(vec![0, 3, 4]),
3344        )?
3345        .aggregate(vec![col("id")], vec![sum(sum(col("salary")))])
3346        .expect_err("nested aggregates should be rejected");
3347
3348        assert_snapshot!(
3349            err.strip_backtrace(),
3350            @"Error during planning: Aggregate function calls cannot be nested: 'sum(employee_csv.salary)' is nested inside 'sum(sum(employee_csv.salary))'"
3351        );
3352
3353        Ok(())
3354    }
3355
3356    #[test]
3357    fn plan_builder_window_rejects_nested_window_functions() -> Result<()> {
3358        // https://github.com/apache/datafusion/issues/23812
3359        let sum_over = |arg| {
3360            Expr::from(expr::WindowFunction::new(
3361                crate::WindowFunctionDefinition::AggregateUDF(
3362                    crate::test::function_stub::sum_udaf(),
3363                ),
3364                vec![arg],
3365            ))
3366        };
3367        let err = table_scan(Some("employee_csv"), &employee_schema(), Some(vec![4]))?
3368            .window(vec![sum_over(sum_over(col("salary")))])
3369            .expect_err("nested window functions should be rejected");
3370
3371        assert_snapshot!(
3372            err.strip_backtrace(),
3373            @"Error during planning: Window function calls cannot be nested: 'sum(employee_csv.salary) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING' is nested inside 'sum(sum(employee_csv.salary) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING'"
3374        );
3375
3376        Ok(())
3377    }
3378
3379    #[test]
3380    fn plan_builder_filter_rejects_window_functions() -> Result<()> {
3381        // https://github.com/apache/datafusion/issues/4610
3382        let sum_over = |arg| {
3383            Expr::from(expr::WindowFunction::new(
3384                crate::WindowFunctionDefinition::AggregateUDF(
3385                    crate::test::function_stub::sum_udaf(),
3386                ),
3387                vec![arg],
3388            ))
3389        };
3390        let scan = || table_scan(Some("employee_csv"), &employee_schema(), Some(vec![4]));
3391
3392        let err = scan()?
3393            .filter(sum_over(col("salary")).gt(lit(10)))
3394            .expect_err("window functions in a filter should be rejected");
3395        assert_snapshot!(
3396            err.strip_backtrace(),
3397            @"Error during planning: Window function calls are not allowed in filter predicates: 'sum(employee_csv.salary) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING'"
3398        );
3399
3400        let err = scan()?
3401            .having(sum_over(col("salary")).gt(lit(10)))
3402            .expect_err("window functions in a having should be rejected");
3403        assert_snapshot!(
3404            err.strip_backtrace(),
3405            @"Error during planning: Window function calls are not allowed in filter predicates: 'sum(employee_csv.salary) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING'"
3406        );
3407
3408        // computing the window function first and filtering on its result is
3409        // the supported form
3410        let plan = scan()?
3411            .window(vec![sum_over(col("salary")).alias("total")])?
3412            .filter(col("total").gt(lit(10)))?
3413            .build()?;
3414        assert_snapshot!(plan, @r"
3415        Filter: total > Int32(10)
3416          WindowAggr: windowExpr=[[sum(employee_csv.salary) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING AS total]]
3417            TableScan: employee_csv projection=[salary]
3418        ");
3419
3420        Ok(())
3421    }
3422
3423    #[test]
3424    fn test_join_metadata() -> Result<()> {
3425        let left_schema = DFSchema::new_with_metadata(
3426            vec![(None, Arc::new(Field::new("a", DataType::Int32, false)))],
3427            HashMap::from([("key".to_string(), "left".to_string())]),
3428        )?;
3429        let right_schema = DFSchema::new_with_metadata(
3430            vec![(None, Arc::new(Field::new("b", DataType::Int32, false)))],
3431            HashMap::from([("key".to_string(), "right".to_string())]),
3432        )?;
3433
3434        let join_schema =
3435            build_join_schema(&left_schema, &right_schema, &JoinType::Left)?;
3436        assert_eq!(
3437            join_schema.metadata(),
3438            &HashMap::from([("key".to_string(), "left".to_string())])
3439        );
3440        let join_schema =
3441            build_join_schema(&left_schema, &right_schema, &JoinType::Right)?;
3442        assert_eq!(
3443            join_schema.metadata(),
3444            &HashMap::from([("key".to_string(), "right".to_string())])
3445        );
3446
3447        Ok(())
3448    }
3449
3450    #[test]
3451    fn asof_join_schema_preserves_dependencies() -> Result<()> {
3452        let left = DFSchema::try_from_qualified_schema(
3453            "left",
3454            &Schema::new(vec![
3455                Field::new("id", DataType::Int32, false),
3456                Field::new("value", DataType::Utf8, false),
3457            ]),
3458        )?
3459        .with_functional_dependencies(FunctionalDependencies::new(vec![
3460            FunctionalDependence::new(vec![0], vec![0, 1], false)
3461                .with_mode(Dependency::Single),
3462        ]))?;
3463        let right = DFSchema::try_from_qualified_schema(
3464            "right",
3465            &Schema::new(vec![
3466                Field::new("id", DataType::Int32, false),
3467                Field::new("value", DataType::Utf8, false),
3468            ]),
3469        )?
3470        .with_functional_dependencies(FunctionalDependencies::new(vec![
3471            FunctionalDependence::new(vec![0], vec![0, 1], false)
3472                .with_mode(Dependency::Single),
3473        ]))?;
3474
3475        let schema = build_asof_join_schema(&left, &right)?;
3476
3477        assert_eq!(
3478            schema.functional_dependencies(),
3479            &FunctionalDependencies::new(vec![
3480                FunctionalDependence::new(vec![0], vec![0, 1, 2, 3], false)
3481                    .with_mode(Dependency::Single),
3482                FunctionalDependence::new(vec![2], vec![2, 3], true)
3483                    .with_mode(Dependency::Multi)
3484                    .with_null_equality(NullEquality::NullEqualsNull),
3485            ])
3486        );
3487        Ok(())
3488    }
3489
3490    #[test]
3491    fn test_values_metadata() -> Result<()> {
3492        let metadata: HashMap<String, String> =
3493            once(("ARROW:extension:metadata".to_string(), "test".to_string())).collect();
3494        let metadata = FieldMetadata::from(metadata);
3495        let values = LogicalPlanBuilder::values(vec![
3496            vec![lit_with_metadata(1, Some(metadata.clone()))],
3497            vec![lit_with_metadata(2, Some(metadata.clone()))],
3498        ])?
3499        .build()?;
3500        assert_eq!(*values.schema().field(0).metadata(), metadata.to_hashmap());
3501
3502        // Do not allow VALUES with different metadata mixed together
3503        let metadata2: HashMap<String, String> =
3504            once(("ARROW:extension:metadata".to_string(), "test2".to_string())).collect();
3505        let metadata2 = FieldMetadata::from(metadata2);
3506        assert!(
3507            LogicalPlanBuilder::values(vec![
3508                vec![lit_with_metadata(1, Some(metadata.clone()))],
3509                vec![lit_with_metadata(2, Some(metadata2.clone()))],
3510            ])
3511            .is_err()
3512        );
3513
3514        Ok(())
3515    }
3516
3517    #[test]
3518    fn test_unique_field_aliases() {
3519        let t1_field_1 = Field::new("a", DataType::Int32, false);
3520        let t2_field_1 = Field::new("a", DataType::Int32, false);
3521        let t2_field_3 = Field::new("a", DataType::Int32, false);
3522        let t2_field_4 = Field::new("a:1", DataType::Int32, false);
3523        let t1_field_2 = Field::new("b", DataType::Int32, false);
3524        let t2_field_2 = Field::new("b", DataType::Int32, false);
3525
3526        let fields = vec![
3527            t1_field_1, t2_field_1, t1_field_2, t2_field_2, t2_field_3, t2_field_4,
3528        ];
3529        let fields = Fields::from(fields);
3530
3531        let remove_redundant = unique_field_aliases(&fields);
3532
3533        // Input [a, a, b, b, a, a:1] becomes [None, a:1, None, b:1, a:2, a:1:1]
3534        // First occurrence of each field name keeps original name (None), duplicates get
3535        // incremental suffixes (:1, :2, etc.).
3536        // Crucially in this case the 2nd occurrence of `a` gets rewritten to `a:1` which later
3537        // conflicts with the last column which is _actually_ called `a:1` so we need to rename it
3538        // as well to `a:1:1`.
3539        assert_eq!(
3540            remove_redundant,
3541            vec![
3542                None,
3543                Some("a:1".to_string()),
3544                None,
3545                Some("b:1".to_string()),
3546                Some("a:2".to_string()),
3547                Some("a:1:1".to_string()),
3548            ]
3549        );
3550    }
3551
3552    #[test]
3553    fn test_values_with_schema_type_mismatch_error_message() {
3554        // Date32 field, but the value is a Boolean, which cannot be cast to Date32.
3555        let schema = Arc::new(
3556            DFSchema::from_unqualified_fields(
3557                vec![Field::new("a", DataType::Date32, false)].into(),
3558                HashMap::new(),
3559            )
3560            .unwrap(),
3561        );
3562
3563        let err = LogicalPlanBuilder::values_with_schema(vec![vec![lit(true)]], &schema)
3564            .unwrap_err();
3565
3566        assert_eq!(
3567            err.strip_backtrace(),
3568            "Execution error: Types don't match and no valid cast exists, \
3569         received data of type Boolean for field of type Date32"
3570        );
3571    }
3572}