Skip to main content

datafusion_expr/
expr.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Logical Expressions: [`Expr`]
6
7use std::borrow::Cow;
8use std::cmp::Ordering;
9use std::collections::HashSet;
10use std::fmt::{self, Display, Formatter, Write};
11use std::hash::{Hash, Hasher};
12use std::mem;
13use std::sync::Arc;
14
15use crate::expr_fn::binary_expr;
16use crate::function::WindowFunctionSimplification;
17use crate::higher_order_function::{HigherOrderUDF, resolve_lambda_variables};
18use crate::logical_plan::Subquery;
19use crate::type_coercion::functions::value_fields_with_higher_order_udf;
20use crate::{AggregateUDF, LambdaParametersProgress, ValueOrLambda, Volatility};
21use crate::{ExprSchemable, Operator, Signature, WindowFrame, WindowUDF};
22
23use arrow::datatypes::{DataType, Field, FieldRef, Metadata};
24use datafusion_common::cse::{HashNode, NormalizeEq, Normalizeable};
25use datafusion_common::datatype::DataTypeExt;
26use datafusion_common::metadata::format_type_and_metadata;
27use datafusion_common::tree_node::{
28    Transformed, TransformedResult, TreeNode, TreeNodeContainer, TreeNodeRecursion,
29};
30use datafusion_common::{
31    Column, DFSchema, ExprSchema, HashMap, Result, ScalarValue, Spans, TableReference,
32    plan_err,
33};
34use datafusion_expr_common::placement::ExpressionPlacement;
35use datafusion_functions_window_common::field::WindowUDFFieldArgs;
36#[cfg(feature = "sql")]
37pub use sqlparser::ast::{
38    ExceptSelectItem, ExcludeSelectItem, IlikeSelectItem, RenameSelectItem,
39    ReplaceSelectElement,
40};
41// Use shims for sqlparser types when the sql feature is disabled.
42#[cfg(not(feature = "sql"))]
43pub use crate::sql::{
44    ExceptSelectItem, ExcludeSelectItem, IlikeSelectItem, RenameSelectItem,
45    ReplaceSelectElement,
46};
47
48// Moved in 51.0.0 to datafusion_common
49pub use datafusion_common::metadata::FieldMetadata;
50use datafusion_common::metadata::ScalarAndMetadata;
51
52// This mirrors sqlparser::ast::NullTreatment but we need our own variant
53// for when the sql feature is disabled.
54#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
55pub enum NullTreatment {
56    IgnoreNulls,
57    RespectNulls,
58}
59
60impl Display for NullTreatment {
61    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
62        f.write_str(match self {
63            NullTreatment::IgnoreNulls => "IGNORE NULLS",
64            NullTreatment::RespectNulls => "RESPECT NULLS",
65        })
66    }
67}
68
69#[cfg(feature = "sql")]
70impl From<sqlparser::ast::NullTreatment> for NullTreatment {
71    fn from(value: sqlparser::ast::NullTreatment) -> Self {
72        match value {
73            sqlparser::ast::NullTreatment::IgnoreNulls => Self::IgnoreNulls,
74            sqlparser::ast::NullTreatment::RespectNulls => Self::RespectNulls,
75        }
76    }
77}
78
79/// Represents logical expressions such as `A + 1`, or `CAST(c1 AS int)`.
80///
81/// For example the expression `A + 1` will be represented as
82///
83/// ```text
84///  BinaryExpr {
85///    left: Expr::Column("A"),
86///    op: Operator::Plus,
87///    right: Expr::Literal(ScalarValue::Int32(Some(1)), None)
88/// }
89/// ```
90///
91/// # Creating Expressions
92///
93/// `Expr`s can be created directly, but it is often easier and less verbose to
94/// use the fluent APIs in [`crate::expr_fn`] such as [`col`] and [`lit`], or
95/// methods such as [`Expr::alias`], [`Expr::cast_to`], and [`Expr::Like`]).
96///
97/// See also [`ExprFunctionExt`] for creating aggregate and window functions.
98///
99/// [`ExprFunctionExt`]: crate::expr_fn::ExprFunctionExt
100///
101/// # Printing Expressions
102///
103/// You can print `Expr`s using the `Debug` trait, `Display` trait, or
104/// [`Self::human_display`]. See the [examples](#examples-displaying-exprs) below.
105///
106/// If you need  SQL to pass to other systems, consider using [`Unparser`].
107///
108/// [`Unparser`]: https://docs.rs/datafusion/latest/datafusion/sql/unparser/struct.Unparser.html
109///
110/// # Schema Access
111///
112/// See [`ExprSchemable::get_type`] to access the [`DataType`] and nullability
113/// of an `Expr`.
114///
115/// # Visiting and Rewriting `Expr`s
116///
117/// The `Expr` struct implements the [`TreeNode`] trait for walking and
118/// rewriting expressions. For example [`TreeNode::apply`] recursively visits an
119/// `Expr` and [`TreeNode::transform`] can be used to rewrite an expression. See
120/// the examples below and [`TreeNode`] for more information.
121///
122/// # Examples: Creating and Using `Expr`s
123///
124/// ## Column References and Literals
125///
126/// [`Expr::Column`] refer to the values of columns and are often created with
127/// the [`col`] function. For example to create an expression `c1` referring to
128/// column named "c1":
129///
130/// [`col`]: crate::expr_fn::col
131///
132/// ```
133/// # use datafusion_common::Column;
134/// # use datafusion_expr::{lit, col, Expr};
135/// let expr = col("c1");
136/// assert_eq!(expr, Expr::Column(Column::from_name("c1")));
137/// ```
138///
139/// [`Expr::Literal`] refer to literal, or constant, values. These are created
140/// with the [`lit`] function. For example to create an expression `42`:
141///
142/// [`lit`]: crate::lit
143///
144/// ```
145/// # use datafusion_common::{Column, ScalarValue};
146/// # use datafusion_expr::{lit, col, Expr};
147/// // All literals are strongly typed in DataFusion. To make an `i64` 42:
148/// let expr = lit(42i64);
149/// assert_eq!(expr, Expr::Literal(ScalarValue::Int64(Some(42)), None));
150/// assert_eq!(expr, Expr::Literal(ScalarValue::Int64(Some(42)), None));
151/// // To make a (typed) NULL:
152/// let expr = Expr::Literal(ScalarValue::Int64(None), None);
153/// // to make an (untyped) NULL (the optimizer will coerce this to the correct type):
154/// let expr = lit(ScalarValue::Null);
155/// ```
156///
157/// ## Binary Expressions
158///
159/// Exprs implement traits that allow easy to understand construction of more
160/// complex expressions. For example, to create `c1 + c2` to add columns "c1" and
161/// "c2" together
162///
163/// ```
164/// # use datafusion_expr::{lit, col, Operator, Expr};
165/// // Use the `+` operator to add two columns together
166/// let expr = col("c1") + col("c2");
167/// assert!(matches!(expr, Expr::BinaryExpr { .. }));
168/// if let Expr::BinaryExpr(binary_expr) = expr {
169///     assert_eq!(*binary_expr.left, col("c1"));
170///     assert_eq!(*binary_expr.right, col("c2"));
171///     assert_eq!(binary_expr.op, Operator::Plus);
172/// }
173/// ```
174///
175/// The expression `c1 = 42` to compares the value in column "c1" to the
176/// literal value `42`:
177///
178/// ```
179/// # use datafusion_common::ScalarValue;
180/// # use datafusion_expr::{lit, col, Operator, Expr};
181/// let expr = col("c1").eq(lit(42_i32));
182/// assert!(matches!(expr, Expr::BinaryExpr { .. }));
183/// if let Expr::BinaryExpr(binary_expr) = expr {
184///     assert_eq!(*binary_expr.left, col("c1"));
185///     let scalar = ScalarValue::Int32(Some(42));
186///     assert_eq!(*binary_expr.right, Expr::Literal(scalar, None));
187///     assert_eq!(binary_expr.op, Operator::Eq);
188/// }
189/// ```
190///
191/// Here is how to implement the equivalent of `SELECT *` to select all
192/// [`Expr::Column`] from a [`DFSchema`]'s columns:
193///
194/// ```
195/// # use arrow::datatypes::{DataType, Field, Schema};
196/// # use datafusion_common::{DFSchema, Column};
197/// # use datafusion_expr::Expr;
198/// // Create a schema c1(int, c2 float)
199/// let arrow_schema = Schema::new(vec![
200///     Field::new("c1", DataType::Int32, false),
201///     Field::new("c2", DataType::Float64, false),
202/// ]);
203/// // DFSchema is a an Arrow schema with optional relation name
204/// let df_schema = DFSchema::try_from_qualified_schema("t1", &arrow_schema).unwrap();
205///
206/// // Form Vec<Expr> with an expression for each column in the schema
207/// let exprs: Vec<_> = df_schema.iter().map(Expr::from).collect();
208///
209/// assert_eq!(
210///     exprs,
211///     vec![
212///         Expr::from(Column::from_qualified_name("t1.c1")),
213///         Expr::from(Column::from_qualified_name("t1.c2")),
214///     ]
215/// );
216/// ```
217///
218/// # Examples: Displaying `Exprs`
219///
220/// There are three ways to print an `Expr` depending on the usecase.
221///
222/// ## Use `Debug` trait
223///
224/// Following Rust conventions, the `Debug` implementation prints out the
225/// internal structure of the expression, which is useful for debugging.
226///
227/// ```
228/// # use datafusion_expr::{lit, col};
229/// let expr = col("c1") + lit(42);
230/// assert_eq!(format!("{expr:?}"), "BinaryExpr(BinaryExpr { left: Column(Column { relation: None, name: \"c1\" }), op: Plus, right: Literal(Int32(42), None) })");
231/// ```
232///
233/// ## Use the `Display` trait  (detailed expression)
234///
235/// The `Display` implementation prints out the expression in a SQL-like form,
236/// but has additional details such as the data type of literals. This is useful
237/// for understanding the expression in more detail and is used for the low level
238/// [`ExplainFormat::Indent`] explain plan format.
239///
240/// [`ExplainFormat::Indent`]: crate::logical_plan::ExplainFormat::Indent
241///
242/// ```
243/// # use datafusion_expr::{lit, col};
244/// let expr = col("c1") + lit(42);
245/// assert_eq!(format!("{expr}"), "c1 + Int32(42)");
246/// ```
247///
248/// ## Use [`Self::human_display`] (human readable)
249///
250/// [`Self::human_display`]  prints out the expression in a SQL-like form, optimized
251/// for human consumption by end users. It is used for the
252/// [`ExplainFormat::Tree`] explain plan format.
253///
254/// [`ExplainFormat::Tree`]: crate::logical_plan::ExplainFormat::Tree
255///
256/// ```
257/// # use datafusion_expr::{lit, col};
258/// let expr = col("c1") + lit(42);
259/// assert_eq!(format!("{}", expr.human_display()), "c1 + 42");
260/// ```
261///
262/// # Examples: Visiting and Rewriting `Expr`s
263///
264/// Here is an example that finds all literals in an `Expr` tree:
265/// ```
266/// # use std::collections::{HashSet};
267/// use datafusion_common::ScalarValue;
268/// # use datafusion_expr::{col, Expr, lit};
269/// use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
270/// // Expression a = 5 AND b = 6
271/// let expr = col("a").eq(lit(5)) & col("b").eq(lit(6));
272/// // find all literals in a HashMap
273/// let mut scalars = HashSet::new();
274/// // apply recursively visits all nodes in the expression tree
275/// expr.apply(|e| {
276///     if let Expr::Literal(scalar, _) = e {
277///         scalars.insert(scalar);
278///     }
279///     // The return value controls whether to continue visiting the tree
280///     Ok(TreeNodeRecursion::Continue)
281/// })
282/// .unwrap();
283/// // All subtrees have been visited and literals found
284/// assert_eq!(scalars.len(), 2);
285/// assert!(scalars.contains(&ScalarValue::Int32(Some(5))));
286/// assert!(scalars.contains(&ScalarValue::Int32(Some(6))));
287/// ```
288///
289/// Rewrite an expression, replacing references to column "a" in an
290/// to the literal `42`:
291///
292/// ```
293/// # use datafusion_common::tree_node::{Transformed, TreeNode};
294/// # use datafusion_expr::{col, Expr, lit};
295/// // expression a = 5 AND b = 6
296/// let expr = col("a").eq(lit(5)).and(col("b").eq(lit(6)));
297/// // rewrite all references to column "a" to the literal 42
298/// let rewritten = expr.transform(|e| {
299///   if let Expr::Column(c) = &e {
300///     if &c.name == "a" {
301///       // return Transformed::yes to indicate the node was changed
302///       return Ok(Transformed::yes(lit(42)))
303///     }
304///   }
305///   // return Transformed::no to indicate the node was not changed
306///   Ok(Transformed::no(e))
307/// }).unwrap();
308/// // The expression has been rewritten
309/// assert!(rewritten.transformed);
310/// // to 42 = 5 AND b = 6
311/// assert_eq!(rewritten.data, lit(42).eq(lit(5)).and(col("b").eq(lit(6))));
312/// ```
313#[derive(Clone, PartialEq, PartialOrd, Eq, Debug, Hash)]
314pub enum Expr {
315    /// An expression with a specific name.
316    Alias(Alias),
317    /// A named reference to a qualified field in a schema.
318    Column(Column),
319    /// A named reference to a variable in a registry.
320    ScalarVariable(FieldRef, Vec<String>),
321    /// A constant value along with associated [`FieldMetadata`].
322    Literal(ScalarValue, Option<FieldMetadata>),
323    /// A binary expression such as "age > 21"
324    BinaryExpr(BinaryExpr),
325    /// LIKE expression
326    Like(Like),
327    /// LIKE expression that uses regular expressions
328    SimilarTo(Like),
329    /// Negation of an expression. The expression's type must be a boolean to make sense.
330    Not(Box<Expr>),
331    /// True if argument is not NULL, false otherwise. This expression itself is never NULL.
332    IsNotNull(Box<Expr>),
333    /// True if argument is NULL, false otherwise. This expression itself is never NULL.
334    IsNull(Box<Expr>),
335    /// True if argument is true, false otherwise. This expression itself is never NULL.
336    IsTrue(Box<Expr>),
337    /// True if argument is  false, false otherwise. This expression itself is never NULL.
338    IsFalse(Box<Expr>),
339    /// True if argument is NULL, false otherwise. This expression itself is never NULL.
340    IsUnknown(Box<Expr>),
341    /// True if argument is FALSE or NULL, false otherwise. This expression itself is never NULL.
342    IsNotTrue(Box<Expr>),
343    /// True if argument is TRUE OR NULL, false otherwise. This expression itself is never NULL.
344    IsNotFalse(Box<Expr>),
345    /// True if argument is TRUE or FALSE, false otherwise. This expression itself is never NULL.
346    IsNotUnknown(Box<Expr>),
347    /// arithmetic negation of an expression, the operand must be of a signed numeric data type
348    Negative(Box<Expr>),
349    /// Whether an expression is between a given range.
350    Between(Between),
351    /// A CASE expression (see docs on [`Case`])
352    Case(Case),
353    /// Casts the expression to a given type and will return a runtime error if the expression cannot be cast.
354    /// This expression is guaranteed to have a fixed type.
355    Cast(Cast),
356    /// Casts the expression to a given type and will return a null value if the expression cannot be cast.
357    /// This expression is guaranteed to have a fixed type.
358    TryCast(TryCast),
359    /// Call a scalar function with a set of arguments.
360    ScalarFunction(ScalarFunction),
361    /// Calls an aggregate function with arguments, and optional
362    /// `ORDER BY`, `FILTER`, `DISTINCT` and `NULL TREATMENT`.
363    ///
364    /// See also [`ExprFunctionExt`] to set these fields.
365    ///
366    /// [`ExprFunctionExt`]: crate::expr_fn::ExprFunctionExt
367    AggregateFunction(AggregateFunction),
368    /// Call a window function with a set of arguments.
369    WindowFunction(Box<WindowFunction>),
370    /// Returns whether the list contains the expr value.
371    InList(InList),
372    /// EXISTS subquery
373    Exists(Exists),
374    /// IN subquery
375    InSubquery(InSubquery),
376    /// Set comparison subquery (e.g. `= ANY`, `> ALL`)
377    SetComparison(SetComparison),
378    /// Scalar subquery
379    ScalarSubquery(Subquery),
380    /// Represents a reference to all available fields in a specific schema,
381    /// with an optional (schema) qualifier.
382    ///
383    /// This expr has to be resolved to a list of columns before translating logical
384    /// plan into physical plan.
385    #[deprecated(
386        since = "46.0.0",
387        note = "A wildcard needs to be resolved to concrete expressions when constructing the logical plan. See https://github.com/apache/datafusion/issues/7765"
388    )]
389    Wildcard {
390        qualifier: Option<TableReference>,
391        options: Box<WildcardOptions>,
392    },
393    /// List of grouping set expressions. Only valid in the context of an aggregate
394    /// GROUP BY expression list
395    GroupingSet(GroupingSet),
396    /// A place holder for parameters in a prepared statement
397    /// (e.g. `$foo` or `$1`)
398    Placeholder(Placeholder),
399    /// A placeholder which holds a reference to a qualified field
400    /// in the outer query, used for correlated sub queries.
401    OuterReferenceColumn(FieldRef, Column),
402    /// Unnest expression
403    Unnest(Unnest),
404    /// Call a higher order function with a set of arguments.
405    ///
406    /// For example, `array_transform([1,2,3], v -> v+1)` would be equivalent to:
407    ///
408    /// ```text
409    /// HigherOrderFunction(array_transform)
410    /// ├── args[0]: Literal([1,2,3])
411    /// └── args[1]: Lambda
412    ///     ├── params: ["v"]
413    ///     └── body: BinaryExpr(+)
414    ///         ├── LambdaVariable("v")
415    ///         └── Literal(1)
416    /// ```
417    HigherOrderFunction(HigherOrderFunction),
418    /// A Lambda expression with a set of parameters names and a body
419    Lambda(Lambda),
420    /// A named reference to a lambda parameter
421    LambdaVariable(LambdaVariable),
422}
423
424/// Invoke a [`HigherOrderUDF`] with a set of arguments
425#[derive(Clone, Eq, PartialOrd, Debug)]
426pub struct HigherOrderFunction {
427    /// The function
428    pub func: Arc<HigherOrderUDF>,
429    /// List of expressions to feed to the functions as arguments
430    pub args: Vec<Expr>,
431}
432
433impl HigherOrderFunction {
434    /// Create a new `HigherOrderFunction` from a [`HigherOrderUDF`]
435    pub fn new(func: Arc<HigherOrderUDF>, args: Vec<Expr>) -> Self {
436        Self { func, args }
437    }
438
439    pub fn name(&self) -> &str {
440        self.func.name()
441    }
442
443    /// Invokes the inner function [`crate::HigherOrderUDFImpl::lambda_parameters`]
444    /// using the arguments of this invocation. This expression lambda
445    /// variables must be already resolved either by coming from the
446    /// default sql planner or by calling [Expr::resolve_lambda_variables]
447    /// or [LogicalPlan::resolve_lambda_variables]
448    ///
449    /// [LogicalPlan::resolve_lambda_variables]: crate::LogicalPlan::resolve_lambda_variables
450    pub fn lambda_parameters(
451        &self,
452        schema: &dyn ExprSchema,
453    ) -> Result<Vec<Vec<FieldRef>>> {
454        let args = self
455            .args
456            .iter()
457            .map(|e| match e {
458                Expr::Lambda(lambda) => {
459                    Ok(ValueOrLambda::Lambda(Some(lambda.body.to_field(schema)?.1)))
460                }
461                _ => Ok(ValueOrLambda::Value(e.to_field(schema)?.1)),
462            })
463            .collect::<Result<Vec<_>>>()?;
464
465        let coerced_fields =
466            value_fields_with_higher_order_udf(&args, self.func.as_ref())?;
467
468        match self.func.lambda_parameters(0, &coerced_fields)? {
469            LambdaParametersProgress::Partial(_) => plan_err!(
470                "{} lambda_parameters returned a partial result when the return type of all it's lambdas were provided",
471                self.name()
472            ),
473            LambdaParametersProgress::Complete(items) => Ok(items),
474        }
475    }
476}
477
478impl Hash for HigherOrderFunction {
479    fn hash<H: Hasher>(&self, state: &mut H) {
480        self.func.hash(state);
481        self.args.hash(state);
482    }
483}
484
485impl PartialEq for HigherOrderFunction {
486    fn eq(&self, other: &Self) -> bool {
487        self.func.as_ref() == other.func.as_ref() && self.args == other.args
488    }
489}
490
491/// A named reference to a lambda parameter which includes it's own [`FieldRef`],
492/// which is used to implement [`ExprSchemable`], for example. It is an option only to make
493/// easier for `expr_api` users to construct lambda variables, but any expression
494/// tree or [`LogicalPlan`] containing unresolved variables must be resolved before
495/// usage with either [`Expr::resolve_lambda_variables`] or
496/// [`LogicalPlan::resolve_lambda_variables`]. The default SQL planner produces
497/// already resolved variables and no further resolving is required.
498///
499/// After resolving, if any argument from the lambda function which this
500/// variables originates from have it's field changed (type, nullability,
501/// metadata, etc), the resolved variable may became outdated and must be
502/// resolved again.
503///
504/// [`LogicalPlan`]: crate::LogicalPlan
505/// [`LogicalPlan::resolve_lambda_variables`]: crate::LogicalPlan::resolve_lambda_variables
506#[derive(Clone, PartialEq, PartialOrd, Eq, Debug, Hash)]
507pub struct LambdaVariable {
508    pub name: String,
509    pub field: Option<FieldRef>,
510    pub spans: Spans,
511}
512
513impl LambdaVariable {
514    /// Create a lambda variable from a name and an optional field.
515    /// If the field is none, the expression tree or LogicalPlan which
516    /// owns this variable must be resolved before usage with either
517    /// [`Expr::resolve_lambda_variables`] or [`LogicalPlan::resolve_lambda_variables`].
518    ///
519    /// [`LogicalPlan::resolve_lambda_variables`]: crate::LogicalPlan::resolve_lambda_variables
520    pub fn new(name: String, field: Option<FieldRef>) -> Self {
521        Self {
522            name,
523            field,
524            spans: Spans::new(),
525        }
526    }
527
528    pub fn spans_mut(&mut self) -> &mut Spans {
529        &mut self.spans
530    }
531}
532
533impl Default for Expr {
534    fn default() -> Self {
535        Expr::Literal(ScalarValue::Null, None)
536    }
537}
538
539impl AsRef<Expr> for Expr {
540    fn as_ref(&self) -> &Expr {
541        self
542    }
543}
544
545/// Create an [`Expr`] from a [`Column`]
546impl From<Column> for Expr {
547    fn from(value: Column) -> Self {
548        Expr::Column(value)
549    }
550}
551
552/// Create an [`Expr`] from a [`WindowFunction`]
553impl From<WindowFunction> for Expr {
554    fn from(value: WindowFunction) -> Self {
555        Expr::WindowFunction(Box::new(value))
556    }
557}
558
559/// Create an [`Expr`] from an [`ScalarAndMetadata`]
560impl From<ScalarAndMetadata> for Expr {
561    fn from(value: ScalarAndMetadata) -> Self {
562        let (value, metadata) = value.into_inner();
563        Expr::Literal(value, metadata)
564    }
565}
566
567/// Create an [`Expr`] from an optional qualifier and a [`FieldRef`]. This is
568/// useful for creating [`Expr`] from a [`DFSchema`].
569///
570/// See example on [`Expr`]
571impl<'a> From<(Option<&'a TableReference>, &'a FieldRef)> for Expr {
572    fn from(value: (Option<&'a TableReference>, &'a FieldRef)) -> Self {
573        Expr::from(Column::from(value))
574    }
575}
576
577impl<'a> TreeNodeContainer<'a, Self> for Expr {
578    fn apply_elements<F: FnMut(&'a Self) -> Result<TreeNodeRecursion>>(
579        &'a self,
580        mut f: F,
581    ) -> Result<TreeNodeRecursion> {
582        f(self)
583    }
584
585    fn map_elements<F: FnMut(Self) -> Result<Transformed<Self>>>(
586        self,
587        mut f: F,
588    ) -> Result<Transformed<Self>> {
589        f(self)
590    }
591}
592
593/// The metadata used in [`Field::metadata`].
594///
595/// This represents the metadata associated with an Arrow [`Field`]. The metadata consists of key-value pairs.
596///
597/// # Common Use Cases
598///
599/// Field metadata is commonly used to store:
600/// - Default values for columns when data is missing
601/// - Column descriptions or documentation
602/// - Data lineage information
603/// - Custom application-specific annotations
604/// - Encoding hints or display formatting preferences
605///
606/// # Example: Storing Default Values
607///
608/// A practical example of using field metadata is storing default values for columns
609/// that may be missing in the physical data but present in the logical schema.
610/// See the [default_column_values.rs] example implementation.
611///
612/// [default_column_values.rs]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/custom_data_source/default_column_values.rs
613pub type SchemaFieldMetadata = Metadata;
614
615/// Intersects multiple metadata instances for UNION operations.
616///
617/// This function implements the intersection strategy used by UNION operations,
618/// where only metadata keys that exist in ALL inputs with identical values
619/// are preserved in the result.
620///
621/// # Union Metadata Behavior
622///
623/// Union operations require consistent metadata across all branches:
624/// - Only metadata keys present in ALL union branches are kept
625/// - For each kept key, the value must be identical across all branches
626/// - If a key has different values across branches, it is excluded from the result
627/// - If any input has no metadata, the result will be empty
628///
629/// # Arguments
630///
631/// * `metadatas` - An iterator of `SchemaFieldMetadata` instances to intersect
632///
633/// # Returns
634///
635/// A new `SchemaFieldMetadata` containing only the intersected metadata
636#[deprecated(
637    since = "56.0.0",
638    note = "UNION now merges metadata with `datafusion_common::metadata::merge_metadata_for_union`"
639)]
640pub fn intersect_metadata_for_union<'a>(
641    metadatas: impl IntoIterator<Item = &'a SchemaFieldMetadata>,
642) -> SchemaFieldMetadata {
643    let mut intersected: Option<SchemaFieldMetadata> = None;
644
645    for metadata in metadatas {
646        // Skip empty metadata (e.g. from NULL literals or computed expressions)
647        // to avoid dropping metadata from branches that have it.
648        if metadata.is_empty() {
649            continue;
650        }
651        match &mut intersected {
652            None => {
653                intersected = Some(metadata.clone());
654            }
655            Some(current) => {
656                // Only keep keys that exist in both with the same value
657                current.retain(|k, v| metadata.get(k) == Some(&*v));
658            }
659        }
660    }
661
662    intersected.unwrap_or_default()
663}
664
665/// UNNEST expression.
666///
667/// When `outer` is `true`, the unnest should preserve `NULL` and empty input
668/// lists by emitting a single `NULL` output row for each. When `false` (the
669/// historical default), the behavior is identical to the plain `UNNEST(col)`
670/// SQL form: `NULL` and empty input lists are dropped from the output.
671#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
672pub struct Unnest {
673    pub expr: Box<Expr>,
674    /// Outer-unnest behavior: also expand empty input lists into a single
675    /// `NULL` output row (in addition to preserving `NULL` input rows).
676    pub outer: bool,
677}
678
679impl Unnest {
680    /// Create a new Unnest expression with default (non-outer) semantics.
681    pub fn new(expr: Expr) -> Self {
682        Self {
683            expr: Box::new(expr),
684            outer: false,
685        }
686    }
687
688    /// Create a new Unnest expression with default (non-outer) semantics.
689    pub fn new_boxed(boxed: Box<Expr>) -> Self {
690        Self {
691            expr: boxed,
692            outer: false,
693        }
694    }
695
696    /// Create a new Unnest expression with outer-unnest semantics: `NULL`
697    /// and empty input lists each produce a single `NULL` output row.
698    pub fn new_outer(expr: Expr) -> Self {
699        Self {
700            expr: Box::new(expr),
701            outer: true,
702        }
703    }
704}
705
706/// Alias expression
707#[derive(Clone, PartialEq, Eq, Debug)]
708pub struct Alias {
709    pub expr: Box<Expr>,
710    pub relation: Option<TableReference>,
711    pub name: String,
712    pub metadata: Option<FieldMetadata>,
713}
714
715impl Hash for Alias {
716    fn hash<H: Hasher>(&self, state: &mut H) {
717        self.expr.hash(state);
718        self.relation.hash(state);
719        self.name.hash(state);
720    }
721}
722
723impl PartialOrd for Alias {
724    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
725        let cmp = self.expr.partial_cmp(&other.expr);
726        let Some(Ordering::Equal) = cmp else {
727            return cmp;
728        };
729        let cmp = self.relation.partial_cmp(&other.relation);
730        let Some(Ordering::Equal) = cmp else {
731            return cmp;
732        };
733        self.name
734            .partial_cmp(&other.name)
735            // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
736            .filter(|cmp| *cmp != Ordering::Equal || self == other)
737    }
738}
739
740impl Alias {
741    /// Create an alias with an optional schema/field qualifier.
742    pub fn new(
743        expr: Expr,
744        relation: Option<impl Into<TableReference>>,
745        name: impl Into<String>,
746    ) -> Self {
747        Self {
748            expr: Box::new(expr),
749            relation: relation.map(|r| r.into()),
750            name: name.into(),
751            metadata: None,
752        }
753    }
754
755    pub fn with_metadata(mut self, metadata: Option<FieldMetadata>) -> Self {
756        self.metadata = metadata;
757        self
758    }
759
760    #[doc(hidden)]
761    pub fn with_expr(mut self, expr: Expr) -> Self {
762        self.expr = Box::new(expr);
763        self
764    }
765
766    #[doc(hidden)]
767    pub fn try_map_expr(self, f: impl FnOnce(Expr) -> Result<Expr>) -> Result<Expr> {
768        let Alias {
769            expr,
770            relation,
771            name,
772            metadata,
773        } = self;
774        Ok(Expr::Alias(Alias {
775            expr: Box::new(f(*expr)?),
776            relation,
777            name,
778            metadata,
779        }))
780    }
781}
782
783/// Binary expression for [`Expr::BinaryExpr`]
784#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
785pub struct BinaryExpr {
786    /// Left-hand side of the expression
787    pub left: Box<Expr>,
788    /// The comparison operator
789    pub op: Operator,
790    /// Right-hand side of the expression
791    pub right: Box<Expr>,
792}
793
794impl BinaryExpr {
795    /// Create a new binary expression
796    pub fn new(left: Box<Expr>, op: Operator, right: Box<Expr>) -> Self {
797        Self { left, op, right }
798    }
799}
800
801impl Display for BinaryExpr {
802    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
803        // Put parentheses around child binary expressions so that we can see the difference
804        // between `(a OR b) AND c` and `a OR (b AND c)`. We only insert parentheses when needed,
805        // based on operator precedence. For example, `(a AND b) OR c` and `a AND b OR c` are
806        // equivalent and the parentheses are not necessary.
807
808        fn write_child(
809            f: &mut Formatter<'_>,
810            expr: &Expr,
811            precedence: u8,
812        ) -> fmt::Result {
813            match expr {
814                Expr::BinaryExpr(child) => {
815                    let p = child.op.precedence();
816                    if p == 0 || p < precedence {
817                        write!(f, "({child})")?;
818                    } else {
819                        write!(f, "{child}")?;
820                    }
821                }
822                _ => write!(f, "{expr}")?,
823            }
824            Ok(())
825        }
826
827        let precedence = self.op.precedence();
828        write_child(f, self.left.as_ref(), precedence)?;
829        write!(f, " {} ", self.op)?;
830        write_child(f, self.right.as_ref(), precedence)
831    }
832}
833
834/// CASE expression
835///
836/// The CASE expression is similar to a series of nested if/else and there are two forms that
837/// can be used. The first form consists of a series of boolean "when" expressions with
838/// corresponding "then" expressions, and an optional "else" expression.
839///
840/// ```text
841/// CASE WHEN condition THEN result
842///      [WHEN ...]
843///      [ELSE result]
844/// END
845/// ```
846///
847/// The second form uses a base expression and then a series of "when" clauses that match on a
848/// literal value.
849///
850/// ```text
851/// CASE expression
852///     WHEN value THEN result
853///     [WHEN ...]
854///     [ELSE result]
855/// END
856/// ```
857#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Hash)]
858pub struct Case {
859    /// Optional base expression that can be compared to literal values in the "when" expressions
860    pub expr: Option<Box<Expr>>,
861    /// One or more when/then expressions
862    pub when_then_expr: Vec<(Box<Expr>, Box<Expr>)>,
863    /// Optional "else" expression
864    pub else_expr: Option<Box<Expr>>,
865}
866
867impl Case {
868    /// Create a new Case expression
869    pub fn new(
870        expr: Option<Box<Expr>>,
871        when_then_expr: Vec<(Box<Expr>, Box<Expr>)>,
872        else_expr: Option<Box<Expr>>,
873    ) -> Self {
874        Self {
875            expr,
876            when_then_expr,
877            else_expr,
878        }
879    }
880}
881
882/// LIKE expression
883#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
884pub struct Like {
885    pub negated: bool,
886    pub expr: Box<Expr>,
887    pub pattern: Box<Expr>,
888    pub escape_char: Option<char>,
889    /// Whether to ignore case on comparing
890    pub case_insensitive: bool,
891}
892
893impl Like {
894    /// Create a new Like expression
895    pub fn new(
896        negated: bool,
897        expr: Box<Expr>,
898        pattern: Box<Expr>,
899        escape_char: Option<char>,
900        case_insensitive: bool,
901    ) -> Self {
902        Self {
903            negated,
904            expr,
905            pattern,
906            escape_char,
907            case_insensitive,
908        }
909    }
910}
911
912/// BETWEEN expression
913#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
914pub struct Between {
915    /// The value to compare
916    pub expr: Box<Expr>,
917    /// Whether the expression is negated
918    pub negated: bool,
919    /// The low end of the range
920    pub low: Box<Expr>,
921    /// The high end of the range
922    pub high: Box<Expr>,
923}
924
925impl Between {
926    /// Create a new Between expression
927    pub fn new(expr: Box<Expr>, negated: bool, low: Box<Expr>, high: Box<Expr>) -> Self {
928        Self {
929            expr,
930            negated,
931            low,
932            high,
933        }
934    }
935}
936
937/// Invoke a [`ScalarUDF`] with a set of arguments
938///
939/// [`ScalarUDF`]: crate::ScalarUDF
940#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
941pub struct ScalarFunction {
942    /// The function
943    pub func: Arc<crate::ScalarUDF>,
944    /// List of expressions to feed to the functions as arguments
945    pub args: Vec<Expr>,
946}
947
948impl ScalarFunction {
949    // return the Function's name
950    pub fn name(&self) -> &str {
951        self.func.name()
952    }
953}
954
955impl ScalarFunction {
956    /// Create a new `ScalarFunction` from a [`ScalarUDF`]
957    ///
958    /// [`ScalarUDF`]: crate::ScalarUDF
959    pub fn new_udf(udf: Arc<crate::ScalarUDF>, args: Vec<Expr>) -> Self {
960        Self { func: udf, args }
961    }
962}
963
964/// Access a sub field of a nested type, such as `Field` or `List`
965#[derive(Clone, PartialEq, Eq, Hash, Debug)]
966pub enum GetFieldAccess {
967    /// Named field, for example `struct["name"]`
968    NamedStructField { name: ScalarValue },
969    /// Single list index, for example: `list[i]`
970    ListIndex { key: Box<Expr> },
971    /// List stride, for example `list[i:j:k]`
972    ListRange {
973        start: Box<Expr>,
974        stop: Box<Expr>,
975        stride: Box<Expr>,
976    },
977}
978
979/// Cast expression
980#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
981pub struct Cast {
982    /// The expression being cast
983    pub expr: Box<Expr>,
984    /// The `DataType` the expression will yield
985    pub field: FieldRef,
986}
987
988impl Cast {
989    /// Create a new Cast expression
990    pub fn new(expr: Box<Expr>, data_type: DataType) -> Self {
991        Self {
992            expr,
993            field: data_type.into_nullable_field_ref(),
994        }
995    }
996
997    pub fn new_from_field(expr: Box<Expr>, field: FieldRef) -> Self {
998        Self { expr, field }
999    }
1000}
1001
1002/// TryCast Expression
1003#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1004pub struct TryCast {
1005    /// The expression being cast
1006    pub expr: Box<Expr>,
1007    /// The `DataType` the expression will yield
1008    pub field: FieldRef,
1009}
1010
1011impl TryCast {
1012    /// Create a new TryCast expression
1013    pub fn new(expr: Box<Expr>, data_type: DataType) -> Self {
1014        Self {
1015            expr,
1016            field: data_type.into_nullable_field_ref(),
1017        }
1018    }
1019
1020    pub fn new_from_field(expr: Box<Expr>, field: FieldRef) -> Self {
1021        Self { expr, field }
1022    }
1023}
1024
1025/// SORT expression
1026#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1027pub struct Sort {
1028    /// The expression to sort on
1029    pub expr: Expr,
1030    /// The direction of the sort
1031    pub asc: bool,
1032    /// Whether to put Nulls before all other data values
1033    pub nulls_first: bool,
1034}
1035
1036impl Sort {
1037    /// Create a new Sort expression
1038    pub fn new(expr: Expr, asc: bool, nulls_first: bool) -> Self {
1039        Self {
1040            expr,
1041            asc,
1042            nulls_first,
1043        }
1044    }
1045
1046    /// Create a new Sort expression with the opposite sort direction
1047    pub fn reverse(&self) -> Self {
1048        Self {
1049            expr: self.expr.clone(),
1050            asc: !self.asc,
1051            nulls_first: !self.nulls_first,
1052        }
1053    }
1054
1055    /// Replaces the Sort expressions with `expr`
1056    pub fn with_expr(&self, expr: Expr) -> Self {
1057        Self {
1058            expr,
1059            asc: self.asc,
1060            nulls_first: self.nulls_first,
1061        }
1062    }
1063}
1064
1065impl Display for Sort {
1066    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1067        write!(f, "{}", self.expr)?;
1068        if self.asc {
1069            write!(f, " ASC")?;
1070        } else {
1071            write!(f, " DESC")?;
1072        }
1073        if self.nulls_first {
1074            write!(f, " NULLS FIRST")?;
1075        } else {
1076            write!(f, " NULLS LAST")?;
1077        }
1078        Ok(())
1079    }
1080}
1081
1082impl<'a> TreeNodeContainer<'a, Expr> for Sort {
1083    fn apply_elements<F: FnMut(&'a Expr) -> Result<TreeNodeRecursion>>(
1084        &'a self,
1085        f: F,
1086    ) -> Result<TreeNodeRecursion> {
1087        self.expr.apply_elements(f)
1088    }
1089
1090    fn map_elements<F: FnMut(Expr) -> Result<Transformed<Expr>>>(
1091        self,
1092        f: F,
1093    ) -> Result<Transformed<Self>> {
1094        self.expr
1095            .map_elements(f)?
1096            .map_data(|expr| Ok(Self { expr, ..self }))
1097    }
1098}
1099
1100/// Aggregate function
1101///
1102/// See also  [`ExprFunctionExt`] to set these fields on `Expr`
1103///
1104/// [`ExprFunctionExt`]: crate::expr_fn::ExprFunctionExt
1105#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1106pub struct AggregateFunction {
1107    /// Name of the function
1108    pub func: Arc<AggregateUDF>,
1109    pub params: AggregateFunctionParams,
1110}
1111
1112#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1113pub struct AggregateFunctionParams {
1114    pub args: Vec<Expr>,
1115    /// Whether this is a DISTINCT aggregation or not
1116    pub distinct: bool,
1117    /// Optional filter
1118    pub filter: Option<Box<Expr>>,
1119    /// Optional ordering
1120    pub order_by: Vec<Sort>,
1121    pub null_treatment: Option<NullTreatment>,
1122}
1123
1124impl AggregateFunction {
1125    /// Create a new AggregateFunction expression with a user-defined function (UDF)
1126    pub fn new_udf(
1127        func: Arc<AggregateUDF>,
1128        args: Vec<Expr>,
1129        distinct: bool,
1130        filter: Option<Box<Expr>>,
1131        order_by: Vec<Sort>,
1132        null_treatment: Option<NullTreatment>,
1133    ) -> Self {
1134        Self {
1135            func,
1136            params: AggregateFunctionParams {
1137                args,
1138                distinct,
1139                filter,
1140                order_by,
1141                null_treatment,
1142            },
1143        }
1144    }
1145}
1146
1147/// A function used as a SQL window function
1148///
1149/// In SQL, you can use:
1150/// - Actual window functions ([`WindowUDF`])
1151/// - Normal aggregate functions ([`AggregateUDF`])
1152#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
1153pub enum WindowFunctionDefinition {
1154    /// A user defined aggregate function
1155    AggregateUDF(Arc<AggregateUDF>),
1156    /// A user defined window function
1157    WindowUDF(Arc<WindowUDF>),
1158}
1159
1160impl WindowFunctionDefinition {
1161    /// Returns the datatype of the window function
1162    pub fn return_field(
1163        &self,
1164        input_expr_fields: &[FieldRef],
1165        display_name: &str,
1166    ) -> Result<FieldRef> {
1167        match self {
1168            WindowFunctionDefinition::AggregateUDF(fun) => {
1169                fun.return_field(input_expr_fields)
1170            }
1171            WindowFunctionDefinition::WindowUDF(fun) => {
1172                fun.field(WindowUDFFieldArgs::new(input_expr_fields, display_name))
1173            }
1174        }
1175    }
1176
1177    /// The signatures supported by the function `fun`.
1178    pub fn signature(&self) -> Signature {
1179        match self {
1180            WindowFunctionDefinition::AggregateUDF(fun) => fun.signature().clone(),
1181            WindowFunctionDefinition::WindowUDF(fun) => fun.signature().clone(),
1182        }
1183    }
1184
1185    /// Function's name for display
1186    pub fn name(&self) -> &str {
1187        match self {
1188            WindowFunctionDefinition::WindowUDF(fun) => fun.name(),
1189            WindowFunctionDefinition::AggregateUDF(fun) => fun.name(),
1190        }
1191    }
1192
1193    /// Returns this window function's simplification hook, if any.
1194    ///
1195    /// See [`WindowFunctionSimplification`] for more information
1196    pub fn simplify(&self) -> Option<WindowFunctionSimplification> {
1197        match self {
1198            WindowFunctionDefinition::AggregateUDF(_) => None,
1199            WindowFunctionDefinition::WindowUDF(udwf) => udwf.simplify(),
1200        }
1201    }
1202}
1203
1204impl Display for WindowFunctionDefinition {
1205    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1206        match self {
1207            WindowFunctionDefinition::AggregateUDF(fun) => Display::fmt(fun, f),
1208            WindowFunctionDefinition::WindowUDF(fun) => Display::fmt(fun, f),
1209        }
1210    }
1211}
1212
1213impl From<Arc<AggregateUDF>> for WindowFunctionDefinition {
1214    fn from(value: Arc<AggregateUDF>) -> Self {
1215        Self::AggregateUDF(value)
1216    }
1217}
1218
1219impl From<Arc<WindowUDF>> for WindowFunctionDefinition {
1220    fn from(value: Arc<WindowUDF>) -> Self {
1221        Self::WindowUDF(value)
1222    }
1223}
1224
1225/// Window function
1226///
1227/// Holds the actual function to call [`WindowFunction`] as well as its
1228/// arguments (`args`) and the contents of the `OVER` clause:
1229///
1230/// 1. `PARTITION BY`
1231/// 2. `ORDER BY`
1232/// 3. Window frame (e.g. `ROWS 1 PRECEDING AND 1 FOLLOWING`)
1233///
1234/// See [`ExprFunctionExt`] for examples of how to create a `WindowFunction`.
1235///
1236/// [`ExprFunctionExt`]: crate::ExprFunctionExt
1237#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1238pub struct WindowFunction {
1239    /// Name of the function
1240    pub fun: WindowFunctionDefinition,
1241    pub params: WindowFunctionParams,
1242}
1243
1244#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1245pub struct WindowFunctionParams {
1246    /// List of expressions to feed to the functions as arguments
1247    pub args: Vec<Expr>,
1248    /// List of partition by expressions
1249    pub partition_by: Vec<Expr>,
1250    /// List of order by expressions
1251    pub order_by: Vec<Sort>,
1252    /// Window frame
1253    pub window_frame: WindowFrame,
1254    /// Optional filter expression (FILTER (WHERE ...))
1255    pub filter: Option<Box<Expr>>,
1256    /// Specifies how NULL value is treated: ignore or respect
1257    pub null_treatment: Option<NullTreatment>,
1258    /// Distinct flag
1259    pub distinct: bool,
1260}
1261
1262impl WindowFunction {
1263    /// Create a new Window expression with the specified argument an
1264    /// empty `OVER` clause
1265    pub fn new(fun: impl Into<WindowFunctionDefinition>, args: Vec<Expr>) -> Self {
1266        Self {
1267            fun: fun.into(),
1268            params: WindowFunctionParams {
1269                args,
1270                partition_by: Vec::default(),
1271                order_by: Vec::default(),
1272                window_frame: WindowFrame::new(None),
1273                filter: None,
1274                null_treatment: None,
1275                distinct: false,
1276            },
1277        }
1278    }
1279
1280    /// Returns this window function's simplification hook, if any.
1281    ///
1282    /// See [`WindowFunctionSimplification`] for more information
1283    pub fn simplify(&self) -> Option<WindowFunctionSimplification> {
1284        self.fun.simplify()
1285    }
1286}
1287
1288/// EXISTS expression
1289#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1290pub struct Exists {
1291    /// Subquery that will produce a single column of data
1292    pub subquery: Subquery,
1293    /// Whether the expression is negated
1294    pub negated: bool,
1295}
1296
1297impl Exists {
1298    // Create a new Exists expression.
1299    pub fn new(subquery: Subquery, negated: bool) -> Self {
1300        Self { subquery, negated }
1301    }
1302}
1303
1304/// Whether the set comparison uses `ANY`/`SOME` or `ALL`
1305#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Hash, Debug)]
1306pub enum SetQuantifier {
1307    /// `ANY` (or `SOME`)
1308    Any,
1309    /// `ALL`
1310    All,
1311}
1312
1313impl Display for SetQuantifier {
1314    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1315        match self {
1316            SetQuantifier::Any => write!(f, "ANY"),
1317            SetQuantifier::All => write!(f, "ALL"),
1318        }
1319    }
1320}
1321
1322/// Set comparison subquery (e.g. `= ANY`, `> ALL`)
1323#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1324pub struct SetComparison {
1325    /// The expression to compare
1326    pub expr: Box<Expr>,
1327    /// Subquery that will produce a single column of data to compare against
1328    pub subquery: Subquery,
1329    /// Comparison operator (e.g. `=`, `>`, `<`)
1330    pub op: Operator,
1331    /// Quantifier (`ANY`/`ALL`)
1332    pub quantifier: SetQuantifier,
1333}
1334
1335impl SetComparison {
1336    /// Create a new set comparison expression
1337    pub fn new(
1338        expr: Box<Expr>,
1339        subquery: Subquery,
1340        op: Operator,
1341        quantifier: SetQuantifier,
1342    ) -> Self {
1343        Self {
1344            expr,
1345            subquery,
1346            op,
1347            quantifier,
1348        }
1349    }
1350}
1351
1352/// InList expression
1353#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1354pub struct InList {
1355    /// The expression to compare
1356    pub expr: Box<Expr>,
1357    /// The list of values to compare against
1358    pub list: Vec<Expr>,
1359    /// Whether the expression is negated
1360    pub negated: bool,
1361}
1362
1363impl InList {
1364    /// Create a new InList expression
1365    pub fn new(expr: Box<Expr>, list: Vec<Expr>, negated: bool) -> Self {
1366        Self {
1367            expr,
1368            list,
1369            negated,
1370        }
1371    }
1372}
1373
1374/// IN subquery
1375#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1376pub struct InSubquery {
1377    /// The expression to compare
1378    pub expr: Box<Expr>,
1379    /// Subquery that will produce a single column of data to compare against
1380    pub subquery: Subquery,
1381    /// Whether the expression is negated
1382    pub negated: bool,
1383}
1384
1385impl InSubquery {
1386    /// Create a new InSubquery expression
1387    pub fn new(expr: Box<Expr>, subquery: Subquery, negated: bool) -> Self {
1388        Self {
1389            expr,
1390            subquery,
1391            negated,
1392        }
1393    }
1394}
1395
1396/// The tuple elements of a multi-column `(a, b, ...) IN (SELECT x, y, ...)`,
1397/// given the compared expression `expr` and the `subquery` plan, or `None`
1398/// for a single-column `IN`.
1399///
1400/// The tuple is planned as a `struct` call, which `simplify_expressions` folds
1401/// into a struct literal when every element is a literal. It is a
1402/// multi-column `IN` only when the subquery returns more than one column;
1403/// against a single column the struct is one value compared with a
1404/// struct-typed column.
1405///
1406/// Errors when the number of tuple elements does not match the number of
1407/// subquery columns.
1408pub fn in_subquery_tuple_values<'a>(
1409    expr: &'a Expr,
1410    subquery: &crate::LogicalPlan,
1411) -> Result<Option<Cow<'a, [Expr]>>> {
1412    let num_columns = subquery.schema().fields().len();
1413    if num_columns <= 1 {
1414        return Ok(None);
1415    }
1416    let values = match expr {
1417        Expr::ScalarFunction(func) if func.func.name() == "struct" => {
1418            Cow::Borrowed(func.args.as_slice())
1419        }
1420        Expr::Literal(ScalarValue::Struct(array), _)
1421            if arrow::array::Array::is_valid(array.as_ref(), 0) =>
1422        {
1423            Cow::Owned(
1424                array
1425                    .columns()
1426                    .iter()
1427                    .map(|column| {
1428                        Ok(Expr::Literal(ScalarValue::try_from_array(column, 0)?, None))
1429                    })
1430                    .collect::<Result<_>>()?,
1431            )
1432        }
1433        _ => return Ok(None),
1434    };
1435    if values.len() != num_columns {
1436        return plan_err!(
1437            "The number of columns in the tuple ({}) must match the number of columns in the subquery ({num_columns})",
1438            values.len()
1439        );
1440    }
1441    Ok(Some(values))
1442}
1443
1444/// Placeholder, representing bind parameter values such as `$1` or `$name`.
1445///
1446/// The type of these parameters is inferred using [`Expr::infer_placeholder_types`]
1447/// or can be specified directly using `PREPARE` statements.
1448#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1449pub struct Placeholder {
1450    /// The identifier of the parameter, including the leading `$` (e.g, `"$1"` or `"$foo"`)
1451    pub id: String,
1452    /// The type the parameter will be filled in with
1453    pub field: Option<FieldRef>,
1454}
1455
1456impl Placeholder {
1457    /// Create a new Placeholder expression
1458    #[deprecated(since = "51.0.0", note = "Use new_with_field instead")]
1459    pub fn new(id: String, data_type: Option<DataType>) -> Self {
1460        Self {
1461            id,
1462            field: data_type.map(|dt| Arc::new(Field::new("", dt, true))),
1463        }
1464    }
1465
1466    /// Create a new Placeholder expression from a Field
1467    pub fn new_with_field(id: String, field: Option<FieldRef>) -> Self {
1468        Self { id, field }
1469    }
1470}
1471
1472/// Grouping sets
1473///
1474/// See <https://www.postgresql.org/docs/current/queries-table-expressions.html#QUERIES-GROUPING-SETS>
1475/// for Postgres definition.
1476/// See <https://spark.apache.org/docs/latest/sql-ref-syntax-qry-select-groupby.html>
1477/// for Apache Spark definition.
1478#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1479pub enum GroupingSet {
1480    /// Rollup grouping sets
1481    Rollup(Vec<Expr>),
1482    /// Cube grouping sets
1483    Cube(Vec<Expr>),
1484    /// User-defined grouping sets
1485    GroupingSets(Vec<Vec<Expr>>),
1486}
1487
1488impl GroupingSet {
1489    /// Return all distinct exprs in the grouping set. For `CUBE` and `ROLLUP` this
1490    /// is just the underlying list of exprs. For `GROUPING SET` we need to deduplicate
1491    /// the exprs in the underlying sets.
1492    pub fn distinct_expr(&self) -> Vec<&Expr> {
1493        match self {
1494            GroupingSet::Rollup(exprs) | GroupingSet::Cube(exprs) => {
1495                exprs.iter().collect()
1496            }
1497            GroupingSet::GroupingSets(groups) => {
1498                let mut exprs: Vec<&Expr> = vec![];
1499                for exp in groups.iter().flatten() {
1500                    if !exprs.contains(&exp) {
1501                        exprs.push(exp);
1502                    }
1503                }
1504                exprs
1505            }
1506        }
1507    }
1508}
1509
1510/// A Lambda expression with a set of parameters names and a body
1511#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
1512pub struct Lambda {
1513    /// The parameters names
1514    pub params: Vec<String>,
1515    /// The body expression
1516    pub body: Box<Expr>,
1517}
1518
1519impl Lambda {
1520    /// Create a new lambda expression
1521    pub fn new(params: Vec<String>, body: Expr) -> Self {
1522        Self {
1523            params,
1524            body: Box::new(body),
1525        }
1526    }
1527}
1528
1529pub fn display_comma_separated<T>(slice: &[T]) -> String
1530where
1531    T: Display,
1532{
1533    use itertools::Itertools;
1534    slice.iter().map(|v| format!("{v}")).join(", ")
1535}
1536
1537/// Additional options for wildcards, e.g. Snowflake `EXCLUDE`/`RENAME` and Bigquery `EXCEPT`.
1538#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug, Default)]
1539pub struct WildcardOptions {
1540    /// `[ILIKE...]`.
1541    ///  Snowflake syntax: <https://docs.snowflake.com/en/sql-reference/sql/select#parameters>
1542    pub ilike: Option<IlikeSelectItem>,
1543    /// `[EXCLUDE...]`.
1544    ///  Snowflake syntax: <https://docs.snowflake.com/en/sql-reference/sql/select#parameters>
1545    pub exclude: Option<ExcludeSelectItem>,
1546    /// `[EXCEPT...]`.
1547    ///  BigQuery syntax: <https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#select_except>
1548    ///  Clickhouse syntax: <https://clickhouse.com/docs/en/sql-reference/statements/select#except>
1549    pub except: Option<ExceptSelectItem>,
1550    /// `[REPLACE]`
1551    ///  BigQuery syntax: <https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#select_replace>
1552    ///  Clickhouse syntax: <https://clickhouse.com/docs/en/sql-reference/statements/select#replace>
1553    ///  Snowflake syntax: <https://docs.snowflake.com/en/sql-reference/sql/select#parameters>
1554    pub replace: Option<PlannedReplaceSelectItem>,
1555    /// `[RENAME ...]`.
1556    ///  Snowflake syntax: <https://docs.snowflake.com/en/sql-reference/sql/select#parameters>
1557    pub rename: Option<RenameSelectItem>,
1558}
1559
1560impl WildcardOptions {
1561    pub fn with_replace(self, replace: PlannedReplaceSelectItem) -> Self {
1562        WildcardOptions {
1563            ilike: self.ilike,
1564            exclude: self.exclude,
1565            except: self.except,
1566            replace: Some(replace),
1567            rename: self.rename,
1568        }
1569    }
1570}
1571
1572impl Display for WildcardOptions {
1573    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1574        if let Some(ilike) = &self.ilike {
1575            write!(f, " {ilike}")?;
1576        }
1577        if let Some(exclude) = &self.exclude {
1578            write!(f, " {exclude}")?;
1579        }
1580        if let Some(except) = &self.except {
1581            write!(f, " {except}")?;
1582        }
1583        if let Some(replace) = &self.replace {
1584            write!(f, " {replace}")?;
1585        }
1586        if let Some(rename) = &self.rename {
1587            write!(f, " {rename}")?;
1588        }
1589        Ok(())
1590    }
1591}
1592
1593/// The planned expressions for `REPLACE`
1594#[derive(Clone, PartialEq, Eq, PartialOrd, Hash, Debug, Default)]
1595pub struct PlannedReplaceSelectItem {
1596    /// The original ast nodes
1597    pub items: Vec<ReplaceSelectElement>,
1598    /// The expression planned from the ast nodes. They will be used when expanding the wildcard.
1599    pub planned_expressions: Vec<Expr>,
1600}
1601
1602impl Display for PlannedReplaceSelectItem {
1603    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1604        write!(f, "REPLACE")?;
1605        write!(f, " ({})", display_comma_separated(&self.items))?;
1606        Ok(())
1607    }
1608}
1609
1610impl PlannedReplaceSelectItem {
1611    pub fn items(&self) -> &[ReplaceSelectElement] {
1612        &self.items
1613    }
1614
1615    pub fn expressions(&self) -> &[Expr] {
1616        &self.planned_expressions
1617    }
1618}
1619
1620impl Expr {
1621    /// The name of the column (field) that this `Expr` will produce.
1622    ///
1623    /// For example, for a projection (e.g. `SELECT <expr>`) the resulting arrow
1624    /// [`Schema`] will have a field with this name.
1625    ///
1626    /// Note that the resulting string is subtlety different from the `Display`
1627    /// representation for certain `Expr`. Some differences:
1628    ///
1629    /// 1. [`Expr::Alias`], which shows only the alias itself
1630    /// 2. [`Expr::Cast`] / [`Expr::TryCast`], which only displays the expression
1631    ///
1632    /// # Example
1633    /// ```
1634    /// # use datafusion_expr::{col, lit};
1635    /// let expr = col("foo").eq(lit(42));
1636    /// assert_eq!("foo = Int32(42)", expr.schema_name().to_string());
1637    ///
1638    /// let expr = col("foo").alias("bar").eq(lit(11));
1639    /// assert_eq!("bar = Int32(11)", expr.schema_name().to_string());
1640    /// ```
1641    ///
1642    /// [`Schema`]: arrow::datatypes::Schema
1643    pub fn schema_name(&self) -> impl Display + '_ {
1644        SchemaDisplay(self)
1645    }
1646
1647    /// Human readable display formatting for this expression.
1648    ///
1649    /// This function is primarily used in printing the explain tree output,
1650    /// (e.g. `EXPLAIN FORMAT TREE <query>`), providing a readable format to
1651    /// show how expressions are used in physical and logical plans. See the
1652    /// [`Expr`] for other ways to format expressions
1653    ///
1654    /// Note this format is intended for human consumption rather than SQL for
1655    /// other systems. If you need  SQL to pass to other systems, consider using
1656    /// [`Unparser`].
1657    ///
1658    /// [`Unparser`]: https://docs.rs/datafusion/latest/datafusion/sql/unparser/struct.Unparser.html
1659    ///
1660    /// # Example
1661    /// ```
1662    /// # use datafusion_expr::{col, lit};
1663    /// let expr = col("foo") + lit(42);
1664    /// // For EXPLAIN output:
1665    /// // "foo + 42"
1666    /// println!("{}", expr.human_display());
1667    /// ```
1668    pub fn human_display(&self) -> impl Display + '_ {
1669        SqlDisplay(self)
1670    }
1671
1672    /// Returns the qualifier and the schema name of this expression.
1673    ///
1674    /// Used when the expression forms the output field of a certain plan.
1675    /// The result is the field's qualifier and field name in the plan's
1676    /// output schema. We can use this qualified name to reference the field.
1677    pub fn qualified_name(&self) -> (Option<TableReference>, String) {
1678        match self {
1679            Expr::Column(Column {
1680                relation,
1681                name,
1682                spans: _,
1683            }) => (relation.clone(), name.clone()),
1684            Expr::Alias(Alias { relation, name, .. }) => (relation.clone(), name.clone()),
1685            _ => (None, self.schema_name().to_string()),
1686        }
1687    }
1688
1689    /// Returns placement information for this expression.
1690    ///
1691    /// This is used by optimizers to make decisions about expression placement,
1692    /// such as whether to push expressions down through projections.
1693    pub fn placement(&self) -> ExpressionPlacement {
1694        match self {
1695            Expr::Column(_) => ExpressionPlacement::Column,
1696            Expr::Literal(_, _) => ExpressionPlacement::Literal,
1697            Expr::Alias(inner) => inner.expr.placement(),
1698            Expr::ScalarFunction(func) => {
1699                let arg_placements: Vec<_> =
1700                    func.args.iter().map(|arg| arg.placement()).collect();
1701                func.func.placement(&arg_placements)
1702            }
1703            _ => ExpressionPlacement::KeepInPlace,
1704        }
1705    }
1706
1707    /// Return String representation of the variant represented by `self`
1708    /// Useful for non-rust based bindings
1709    pub fn variant_name(&self) -> &str {
1710        match self {
1711            Expr::AggregateFunction { .. } => "AggregateFunction",
1712            Expr::Alias(..) => "Alias",
1713            Expr::Between { .. } => "Between",
1714            Expr::BinaryExpr { .. } => "BinaryExpr",
1715            Expr::Case { .. } => "Case",
1716            Expr::Cast { .. } => "Cast",
1717            Expr::Column(..) => "Column",
1718            Expr::OuterReferenceColumn(_, _) => "Outer",
1719            Expr::Exists { .. } => "Exists",
1720            Expr::GroupingSet(..) => "GroupingSet",
1721            Expr::InList { .. } => "InList",
1722            Expr::InSubquery(..) => "InSubquery",
1723            Expr::SetComparison(..) => "SetComparison",
1724            Expr::IsNotNull(..) => "IsNotNull",
1725            Expr::IsNull(..) => "IsNull",
1726            Expr::Like { .. } => "Like",
1727            Expr::SimilarTo { .. } => "RLike",
1728            Expr::IsTrue(..) => "IsTrue",
1729            Expr::IsFalse(..) => "IsFalse",
1730            Expr::IsUnknown(..) => "IsUnknown",
1731            Expr::IsNotTrue(..) => "IsNotTrue",
1732            Expr::IsNotFalse(..) => "IsNotFalse",
1733            Expr::IsNotUnknown(..) => "IsNotUnknown",
1734            Expr::Literal(..) => "Literal",
1735            Expr::Negative(..) => "Negative",
1736            Expr::Not(..) => "Not",
1737            Expr::Placeholder(_) => "Placeholder",
1738            Expr::ScalarFunction(..) => "ScalarFunction",
1739            Expr::ScalarSubquery { .. } => "ScalarSubquery",
1740            Expr::ScalarVariable(..) => "ScalarVariable",
1741            Expr::TryCast { .. } => "TryCast",
1742            Expr::WindowFunction { .. } => "WindowFunction",
1743            #[expect(deprecated)]
1744            Expr::Wildcard { .. } => "Wildcard",
1745            Expr::Unnest { .. } => "Unnest",
1746            Expr::HigherOrderFunction { .. } => "HigherOrderFunction",
1747            Expr::Lambda { .. } => "Lambda",
1748            Expr::LambdaVariable { .. } => "LambdaVariable",
1749        }
1750    }
1751
1752    /// Return `self == other`
1753    pub fn eq(self, other: Expr) -> Expr {
1754        binary_expr(self, Operator::Eq, other)
1755    }
1756
1757    /// Return `self != other`
1758    pub fn not_eq(self, other: Expr) -> Expr {
1759        binary_expr(self, Operator::NotEq, other)
1760    }
1761
1762    /// Return `self > other`
1763    pub fn gt(self, other: Expr) -> Expr {
1764        binary_expr(self, Operator::Gt, other)
1765    }
1766
1767    /// Return `self >= other`
1768    pub fn gt_eq(self, other: Expr) -> Expr {
1769        binary_expr(self, Operator::GtEq, other)
1770    }
1771
1772    /// Return `self < other`
1773    pub fn lt(self, other: Expr) -> Expr {
1774        binary_expr(self, Operator::Lt, other)
1775    }
1776
1777    /// Return `self <= other`
1778    pub fn lt_eq(self, other: Expr) -> Expr {
1779        binary_expr(self, Operator::LtEq, other)
1780    }
1781
1782    /// Return `self && other`
1783    pub fn and(self, other: Expr) -> Expr {
1784        binary_expr(self, Operator::And, other)
1785    }
1786
1787    /// Return `self || other`
1788    pub fn or(self, other: Expr) -> Expr {
1789        binary_expr(self, Operator::Or, other)
1790    }
1791
1792    /// Return `self LIKE other`
1793    pub fn like(self, other: Expr) -> Expr {
1794        Expr::Like(Like::new(
1795            false,
1796            Box::new(self),
1797            Box::new(other),
1798            None,
1799            false,
1800        ))
1801    }
1802
1803    /// Return `self NOT LIKE other`
1804    pub fn not_like(self, other: Expr) -> Expr {
1805        Expr::Like(Like::new(
1806            true,
1807            Box::new(self),
1808            Box::new(other),
1809            None,
1810            false,
1811        ))
1812    }
1813
1814    /// Return `self ILIKE other`
1815    pub fn ilike(self, other: Expr) -> Expr {
1816        Expr::Like(Like::new(
1817            false,
1818            Box::new(self),
1819            Box::new(other),
1820            None,
1821            true,
1822        ))
1823    }
1824
1825    /// Return `self NOT ILIKE other`
1826    pub fn not_ilike(self, other: Expr) -> Expr {
1827        Expr::Like(Like::new(true, Box::new(self), Box::new(other), None, true))
1828    }
1829
1830    /// Return the name to use for the specific Expr
1831    pub fn name_for_alias(&self) -> Result<String> {
1832        Ok(self.schema_name().to_string())
1833    }
1834
1835    /// Ensure `expr` has the name as `original_name` by adding an
1836    /// alias if necessary.
1837    pub fn alias_if_changed(self, original_name: String) -> Result<Expr> {
1838        let new_name = self.name_for_alias()?;
1839        if new_name == original_name {
1840            return Ok(self);
1841        }
1842
1843        Ok(self.alias(original_name))
1844    }
1845
1846    /// Return `self AS name` alias expression
1847    pub fn alias(self, name: impl Into<String>) -> Expr {
1848        Expr::Alias(Alias::new(self, None::<&str>, name.into()))
1849    }
1850
1851    /// Return `self AS name` alias expression with metadata
1852    ///
1853    /// The metadata will be attached to the Arrow Schema field when the expression
1854    /// is converted to a field via `Expr.to_field()`.
1855    ///
1856    /// # Example
1857    /// ```
1858    /// # use datafusion_expr::col;
1859    /// # use std::collections::HashMap;
1860    /// # use datafusion_common::metadata::FieldMetadata;
1861    /// let metadata = HashMap::from([("key".to_string(), "value".to_string())]);
1862    /// let metadata = FieldMetadata::from(metadata);
1863    /// let expr = col("foo").alias_with_metadata("bar", Some(metadata));
1864    /// ```
1865    pub fn alias_with_metadata(
1866        self,
1867        name: impl Into<String>,
1868        metadata: Option<FieldMetadata>,
1869    ) -> Expr {
1870        Expr::Alias(Alias::new(self, None::<&str>, name.into()).with_metadata(metadata))
1871    }
1872
1873    /// Return `self AS name` alias expression with a specific qualifier
1874    pub fn alias_qualified(
1875        self,
1876        relation: Option<impl Into<TableReference>>,
1877        name: impl Into<String>,
1878    ) -> Expr {
1879        Expr::Alias(Alias::new(self, relation, name.into()))
1880    }
1881
1882    /// Return `self AS name` alias expression with a specific qualifier and metadata
1883    ///
1884    /// The metadata will be attached to the Arrow Schema field when the expression
1885    /// is converted to a field via `Expr.to_field()`.
1886    ///
1887    /// # Example
1888    /// ```
1889    /// # use datafusion_expr::col;
1890    /// # use std::collections::HashMap;
1891    /// # use datafusion_common::metadata::FieldMetadata;
1892    /// let metadata = HashMap::from([("key".to_string(), "value".to_string())]);
1893    /// let metadata = FieldMetadata::from(metadata);
1894    /// let expr =
1895    ///     col("foo").alias_qualified_with_metadata(Some("tbl"), "bar", Some(metadata));
1896    /// ```
1897    pub fn alias_qualified_with_metadata(
1898        self,
1899        relation: Option<impl Into<TableReference>>,
1900        name: impl Into<String>,
1901        metadata: Option<FieldMetadata>,
1902    ) -> Expr {
1903        Expr::Alias(Alias::new(self, relation, name.into()).with_metadata(metadata))
1904    }
1905
1906    /// Remove an alias from an expression if one exists.
1907    ///
1908    /// If the expression is not an alias, the expression is returned unchanged.
1909    /// This method does not remove aliases from nested expressions.
1910    ///
1911    /// # Example
1912    /// ```
1913    /// # use datafusion_expr::col;
1914    /// // `foo as "bar"` is unaliased to `foo`
1915    /// let expr = col("foo").alias("bar");
1916    /// assert_eq!(expr.unalias(), col("foo"));
1917    ///
1918    /// // `foo as "bar" + baz` is not unaliased
1919    /// let expr = col("foo").alias("bar") + col("baz");
1920    /// assert_eq!(expr.clone().unalias(), expr);
1921    ///
1922    /// // `foo as "bar" as "baz" is unaliased to foo as "bar"
1923    /// let expr = col("foo").alias("bar").alias("baz");
1924    /// assert_eq!(expr.unalias(), col("foo").alias("bar"));
1925    /// ```
1926    pub fn unalias(self) -> Expr {
1927        match self {
1928            Expr::Alias(alias) => *alias.expr,
1929            _ => self,
1930        }
1931    }
1932
1933    /// Recursively removed potentially multiple aliases from an expression.
1934    ///
1935    /// This method removes nested aliases and returns [`Transformed`]
1936    /// to signal if the expression was changed.
1937    ///
1938    /// # Example
1939    /// ```
1940    /// # use datafusion_expr::col;
1941    /// // `foo as "bar"` is unaliased to `foo`
1942    /// let expr = col("foo").alias("bar");
1943    /// assert_eq!(expr.unalias_nested().data, col("foo"));
1944    ///
1945    /// // `foo as "bar" + baz` is  unaliased
1946    /// let expr = col("foo").alias("bar") + col("baz");
1947    /// assert_eq!(expr.clone().unalias_nested().data, col("foo") + col("baz"));
1948    ///
1949    /// // `foo as "bar" as "baz" is unalaised to foo
1950    /// let expr = col("foo").alias("bar").alias("baz");
1951    /// assert_eq!(expr.unalias_nested().data, col("foo"));
1952    /// ```
1953    pub fn unalias_nested(self) -> Transformed<Expr> {
1954        self.transform_down_up(
1955            |expr| {
1956                // f_down: skip subqueries.  Check in f_down to avoid recursing into them
1957                let recursion = if matches!(
1958                    expr,
1959                    Expr::Exists { .. } | Expr::ScalarSubquery(_) | Expr::InSubquery(_)
1960                ) {
1961                    // Subqueries could contain aliases so don't recurse into those
1962                    TreeNodeRecursion::Jump
1963                } else {
1964                    TreeNodeRecursion::Continue
1965                };
1966                Ok(Transformed::new(expr, false, recursion))
1967            },
1968            |expr| {
1969                // f_up: unalias on up so we can remove nested aliases like
1970                // `(x as foo) as bar`
1971                if let Expr::Alias(alias) = expr {
1972                    match alias
1973                        .metadata
1974                        .as_ref()
1975                        .map(|h| h.is_empty())
1976                        .unwrap_or(true)
1977                    {
1978                        true => Ok(Transformed::yes(*alias.expr)),
1979                        false => Ok(Transformed::no(Expr::Alias(alias))),
1980                    }
1981                } else {
1982                    Ok(Transformed::no(expr))
1983                }
1984            },
1985        )
1986        // Unreachable code: internal closure doesn't return err
1987        .unwrap()
1988    }
1989
1990    /// Return `self IN <list>` if `negated` is false, otherwise
1991    /// return `self NOT IN <list>`.a
1992    pub fn in_list(self, list: Vec<Expr>, negated: bool) -> Expr {
1993        Expr::InList(InList::new(Box::new(self), list, negated))
1994    }
1995
1996    /// Return `IsNull(Box(self))
1997    pub fn is_null(self) -> Expr {
1998        Expr::IsNull(Box::new(self))
1999    }
2000
2001    /// Return `IsNotNull(Box(self))
2002    pub fn is_not_null(self) -> Expr {
2003        Expr::IsNotNull(Box::new(self))
2004    }
2005
2006    /// Create a sort configuration from an existing expression.
2007    ///
2008    /// ```
2009    /// # use datafusion_expr::col;
2010    /// let sort_expr = col("foo").sort(true, true); // SORT ASC NULLS_FIRST
2011    /// ```
2012    pub fn sort(self, asc: bool, nulls_first: bool) -> Sort {
2013        Sort::new(self, asc, nulls_first)
2014    }
2015
2016    /// Return `IsTrue(Box(self))`
2017    pub fn is_true(self) -> Expr {
2018        Expr::IsTrue(Box::new(self))
2019    }
2020
2021    /// Return `IsNotTrue(Box(self))`
2022    pub fn is_not_true(self) -> Expr {
2023        Expr::IsNotTrue(Box::new(self))
2024    }
2025
2026    /// Return `IsFalse(Box(self))`
2027    pub fn is_false(self) -> Expr {
2028        Expr::IsFalse(Box::new(self))
2029    }
2030
2031    /// Return `IsNotFalse(Box(self))`
2032    pub fn is_not_false(self) -> Expr {
2033        Expr::IsNotFalse(Box::new(self))
2034    }
2035
2036    /// Return `IsUnknown(Box(self))`
2037    pub fn is_unknown(self) -> Expr {
2038        Expr::IsUnknown(Box::new(self))
2039    }
2040
2041    /// Return `IsNotUnknown(Box(self))`
2042    pub fn is_not_unknown(self) -> Expr {
2043        Expr::IsNotUnknown(Box::new(self))
2044    }
2045
2046    /// return `self BETWEEN low AND high`
2047    pub fn between(self, low: Expr, high: Expr) -> Expr {
2048        Expr::Between(Between::new(
2049            Box::new(self),
2050            false,
2051            Box::new(low),
2052            Box::new(high),
2053        ))
2054    }
2055
2056    /// Return `self NOT BETWEEN low AND high`
2057    pub fn not_between(self, low: Expr, high: Expr) -> Expr {
2058        Expr::Between(Between::new(
2059            Box::new(self),
2060            true,
2061            Box::new(low),
2062            Box::new(high),
2063        ))
2064    }
2065    /// Return a reference to the inner `Column` if any
2066    ///
2067    /// returns `None` if the expression is not a `Column`
2068    ///
2069    /// Note: None may be returned for expressions that are not `Column` but
2070    /// are convertible to `Column` such as `Cast` expressions.
2071    ///
2072    /// Example
2073    /// ```
2074    /// # use datafusion_common::Column;
2075    /// use datafusion_expr::{col, Expr};
2076    /// let expr = col("foo");
2077    /// assert_eq!(expr.try_as_col(), Some(&Column::from("foo")));
2078    ///
2079    /// let expr = col("foo").alias("bar");
2080    /// assert_eq!(expr.try_as_col(), None);
2081    /// ```
2082    pub fn try_as_col(&self) -> Option<&Column> {
2083        if let Expr::Column(it) = self {
2084            Some(it)
2085        } else {
2086            None
2087        }
2088    }
2089
2090    /// Returns the inner `Column` if any. This is a specialized version of
2091    /// [`Self::try_as_col`] that take Cast expressions into account when the
2092    /// expression is as on condition for joins.
2093    ///
2094    /// Called this method when you are sure that the expression is a `Column`
2095    /// or a `Cast` expression that wraps a `Column`.
2096    pub fn get_as_join_column(&self) -> Option<&Column> {
2097        match self {
2098            Expr::Column(c) => Some(c),
2099            Expr::Cast(Cast { expr, .. }) => match &**expr {
2100                Expr::Column(c) => Some(c),
2101                _ => None,
2102            },
2103            _ => None,
2104        }
2105    }
2106
2107    /// Return all references to columns in this expression.
2108    ///
2109    /// # Example
2110    /// ```
2111    /// # use std::collections::HashSet;
2112    /// # use datafusion_common::Column;
2113    /// # use datafusion_expr::col;
2114    /// // For an expression `a + (b * a)`
2115    /// let expr = col("a") + (col("b") * col("a"));
2116    /// let refs = expr.column_refs();
2117    /// // refs contains "a" and "b"
2118    /// assert_eq!(refs.len(), 2);
2119    /// assert!(refs.contains(&Column::new_unqualified("a")));
2120    /// assert!(refs.contains(&Column::new_unqualified("b")));
2121    /// ```
2122    pub fn column_refs(&self) -> HashSet<&Column> {
2123        let mut using_columns = HashSet::new();
2124        self.add_column_refs(&mut using_columns);
2125        using_columns
2126    }
2127
2128    /// Adds references to all columns in this expression to the set
2129    ///
2130    /// See [`Self::column_refs`] for details
2131    pub fn add_column_refs<'a>(&'a self, set: &mut HashSet<&'a Column>) {
2132        self.apply(|expr| {
2133            if let Expr::Column(col) = expr {
2134                set.insert(col);
2135            }
2136            Ok(TreeNodeRecursion::Continue)
2137        })
2138        .expect("traversal is infallible");
2139    }
2140
2141    /// Return all references to columns and their occurrence counts in the expression.
2142    ///
2143    /// # Example
2144    /// ```
2145    /// # use std::collections::HashMap;
2146    /// # use datafusion_common::Column;
2147    /// # use datafusion_expr::col;
2148    /// // For an expression `a + (b * a)`
2149    /// let expr = col("a") + (col("b") * col("a"));
2150    /// let mut refs = expr.column_refs_counts();
2151    /// // refs contains "a" and "b"
2152    /// assert_eq!(refs.len(), 2);
2153    /// assert_eq!(*refs.get(&Column::new_unqualified("a")).unwrap(), 2);
2154    /// assert_eq!(*refs.get(&Column::new_unqualified("b")).unwrap(), 1);
2155    /// ```
2156    pub fn column_refs_counts(&self) -> HashMap<&Column, usize> {
2157        let mut map = HashMap::new();
2158        self.add_column_ref_counts(&mut map);
2159        map
2160    }
2161
2162    /// Adds references to all columns and their occurrence counts in the expression to
2163    /// the map.
2164    ///
2165    /// See [`Self::column_refs_counts`] for details
2166    pub fn add_column_ref_counts<'a>(&'a self, map: &mut HashMap<&'a Column, usize>) {
2167        self.apply(|expr| {
2168            if let Expr::Column(col) = expr {
2169                *map.entry(col).or_default() += 1;
2170            }
2171            Ok(TreeNodeRecursion::Continue)
2172        })
2173        .expect("traversal is infallible");
2174    }
2175
2176    /// Returns true if there are any column references in this Expr
2177    pub fn any_column_refs(&self) -> bool {
2178        self.exists(|expr| Ok(matches!(expr, Expr::Column(_))))
2179            .expect("exists closure is infallible")
2180    }
2181
2182    /// Return true if the expression contains out reference(correlated) expressions.
2183    pub fn contains_outer(&self) -> bool {
2184        self.exists(|expr| Ok(matches!(expr, Expr::OuterReferenceColumn { .. })))
2185            .expect("exists closure is infallible")
2186    }
2187
2188    /// Returns true if the expression contains a scalar subquery.
2189    pub fn contains_scalar_subquery(&self) -> bool {
2190        self.exists(|expr| Ok(matches!(expr, Expr::ScalarSubquery(_))))
2191            .expect("exists closure is infallible")
2192    }
2193
2194    /// Returns true if the expression node is volatile, i.e. whether it can return
2195    /// different results when evaluated multiple times with the same input.
2196    /// Note: unlike [`Self::is_volatile`], this function does not consider inputs:
2197    /// - `rand()` returns `true`,
2198    /// - `a + rand()` returns `false`
2199    pub fn is_volatile_node(&self) -> bool {
2200        let volatility = match self {
2201            Expr::ScalarFunction(func) => func.func.signature().volatility,
2202            Expr::AggregateFunction(func) => func.func.signature().volatility,
2203            Expr::WindowFunction(func) => match &func.fun {
2204                WindowFunctionDefinition::AggregateUDF(func) => {
2205                    func.signature().volatility
2206                }
2207                WindowFunctionDefinition::WindowUDF(func) => func.signature().volatility,
2208            },
2209            Expr::HigherOrderFunction(func) => func.func.signature().volatility,
2210            _ => return false,
2211        };
2212        volatility == Volatility::Volatile
2213    }
2214
2215    /// Returns true if the expression is volatile, i.e. whether it can return different
2216    /// results when evaluated multiple times with the same input.
2217    ///
2218    /// For example the function call `RANDOM()` is volatile as each call will
2219    /// return a different value.
2220    ///
2221    /// See [`Volatility`] for more information.
2222    pub fn is_volatile(&self) -> bool {
2223        self.exists(|expr| Ok(expr.is_volatile_node()))
2224            .expect("exists closure is infallible")
2225    }
2226
2227    /// Recursively find all [`Expr::Placeholder`] expressions, and
2228    /// to infer their [`DataType`] from the context of their use.
2229    ///
2230    /// For example, given an expression like `<int32> = $0` will infer `$0` to
2231    /// have type `int32`.
2232    ///
2233    /// Returns transformed expression and flag that is true if expression contains
2234    /// at least one placeholder.
2235    pub fn infer_placeholder_types(self, schema: &DFSchema) -> Result<(Expr, bool)> {
2236        let mut has_placeholder = false;
2237        self.transform(|mut expr| {
2238            match &mut expr {
2239                // Default to assuming the arguments are the same type
2240                Expr::BinaryExpr(BinaryExpr { left, op: _, right }) => {
2241                    rewrite_placeholder(left.as_mut(), right.as_ref(), schema)?;
2242                    rewrite_placeholder(right.as_mut(), left.as_ref(), schema)?;
2243                }
2244                Expr::Between(Between {
2245                    expr,
2246                    negated: _,
2247                    low,
2248                    high,
2249                }) => {
2250                    rewrite_placeholder(low.as_mut(), expr.as_ref(), schema)?;
2251                    rewrite_placeholder(high.as_mut(), expr.as_ref(), schema)?;
2252                }
2253                Expr::InList(InList {
2254                    expr,
2255                    list,
2256                    negated: _,
2257                }) => {
2258                    for item in list.iter_mut() {
2259                        rewrite_placeholder(item, expr.as_ref(), schema)?;
2260                    }
2261                }
2262                Expr::InSubquery(InSubquery {
2263                    expr,
2264                    subquery,
2265                    negated: _,
2266                }) => {
2267                    // Multi-column `(a, b) IN (SELECT x, y ...)`: infer each
2268                    // tuple element from the subquery column at the same
2269                    // position.
2270                    let subquery_schema = subquery.subquery.schema();
2271                    let is_tuple =
2272                        in_subquery_tuple_values(expr.as_ref(), &subquery.subquery)?
2273                            .is_some();
2274                    match expr.as_mut() {
2275                        Expr::ScalarFunction(func) if is_tuple => {
2276                            for (i, arg) in func.args.iter_mut().enumerate() {
2277                                // Qualified, since two subquery columns can
2278                                // share a name under different qualifiers.
2279                                let column = Expr::Column(Column::from(
2280                                    subquery_schema.qualified_field(i),
2281                                ));
2282                                rewrite_placeholder(arg, &column, subquery_schema)?;
2283                            }
2284                        }
2285                        // A struct literal holds no placeholder.
2286                        _ if is_tuple => {}
2287                        expr => rewrite_placeholder_from_subquery(
2288                            "InSubquery",
2289                            expr,
2290                            subquery,
2291                        )?,
2292                    }
2293                }
2294                Expr::SetComparison(SetComparison {
2295                    expr,
2296                    subquery,
2297                    op: _,
2298                    quantifier: _,
2299                }) => {
2300                    rewrite_placeholder_from_subquery(
2301                        "SetComparison",
2302                        expr.as_mut(),
2303                        subquery,
2304                    )?;
2305                }
2306                Expr::Like(Like { expr, pattern, .. })
2307                | Expr::SimilarTo(Like { expr, pattern, .. }) => {
2308                    rewrite_placeholder(pattern.as_mut(), expr.as_ref(), schema)?;
2309                }
2310                Expr::Placeholder(_) => {
2311                    has_placeholder = true;
2312                }
2313                _ => {}
2314            }
2315            Ok(Transformed::yes(expr))
2316        })
2317        .data()
2318        .map(|data| (data, has_placeholder))
2319    }
2320
2321    /// Returns true if some of this `exprs` subexpressions may not be evaluated
2322    /// and thus any side effects (like divide by zero) may not be encountered
2323    pub fn short_circuits(&self) -> bool {
2324        match self {
2325            Expr::ScalarFunction(ScalarFunction { func, .. }) => func.short_circuits(),
2326            Expr::HigherOrderFunction(HigherOrderFunction { func, .. }) => {
2327                func.short_circuits()
2328            }
2329            Expr::BinaryExpr(BinaryExpr { op, .. }) => {
2330                matches!(op, Operator::And | Operator::Or)
2331            }
2332            Expr::Case { .. } => true,
2333            // Use explicit pattern match instead of a default
2334            // implementation, so that in the future if someone adds
2335            // new Expr types, they will check here as well
2336            // TODO: remove the next line after `Expr::Wildcard` is removed
2337            #[expect(deprecated)]
2338            Expr::AggregateFunction(..)
2339            | Expr::Alias(..)
2340            | Expr::Between(..)
2341            | Expr::Cast(..)
2342            | Expr::Column(..)
2343            | Expr::Exists(..)
2344            | Expr::GroupingSet(..)
2345            | Expr::InList(..)
2346            | Expr::InSubquery(..)
2347            | Expr::SetComparison(..)
2348            | Expr::IsFalse(..)
2349            | Expr::IsNotFalse(..)
2350            | Expr::IsNotNull(..)
2351            | Expr::IsNotTrue(..)
2352            | Expr::IsNotUnknown(..)
2353            | Expr::IsNull(..)
2354            | Expr::IsTrue(..)
2355            | Expr::IsUnknown(..)
2356            | Expr::Like(..)
2357            | Expr::ScalarSubquery(..)
2358            | Expr::ScalarVariable(_, _)
2359            | Expr::SimilarTo(..)
2360            | Expr::Not(..)
2361            | Expr::Negative(..)
2362            | Expr::OuterReferenceColumn(_, _)
2363            | Expr::TryCast(..)
2364            | Expr::Unnest(..)
2365            | Expr::Wildcard { .. }
2366            | Expr::WindowFunction(..)
2367            | Expr::Literal(..)
2368            | Expr::Placeholder(..)
2369            | Expr::Lambda(..)
2370            | Expr::LambdaVariable(..) => false,
2371        }
2372    }
2373
2374    /// Returns a reference to the set of locations in the SQL query where this
2375    /// expression appears, if known. [`None`] is returned if the expression
2376    /// type doesn't support tracking locations yet.
2377    pub fn spans(&self) -> Option<&Spans> {
2378        match self {
2379            Expr::Column(col) => Some(&col.spans),
2380            Expr::Not(inner) | Expr::Negative(inner) => inner.spans(),
2381            _ => None,
2382        }
2383    }
2384
2385    /// Check if the Expr is literal and get the literal value if it is.
2386    pub fn as_literal(&self) -> Option<&ScalarValue> {
2387        if let Expr::Literal(lit, _) = self {
2388            Some(lit)
2389        } else {
2390            None
2391        }
2392    }
2393
2394    /// Return a `Expr` with all [`LambdaVariable`] resolved only if all of them
2395    /// are contained in the subtree of the [`HigherOrderFunction`] it originates from,
2396    /// otherwise returns an error
2397    pub fn resolve_lambda_variables(
2398        self,
2399        schema: &DFSchema,
2400    ) -> Result<Transformed<Expr>> {
2401        resolve_lambda_variables(self, schema, &mut HashMap::new())
2402    }
2403}
2404
2405impl Normalizeable for Expr {
2406    fn can_normalize(&self) -> bool {
2407        #[expect(clippy::match_like_matches_macro)]
2408        match self {
2409            Expr::BinaryExpr(BinaryExpr {
2410                op:
2411                    _op @ (Operator::Plus
2412                    | Operator::Multiply
2413                    | Operator::BitwiseAnd
2414                    | Operator::BitwiseOr
2415                    | Operator::BitwiseXor
2416                    | Operator::Eq
2417                    | Operator::NotEq),
2418                ..
2419            }) => true,
2420            _ => false,
2421        }
2422    }
2423}
2424
2425impl NormalizeEq for Expr {
2426    fn normalize_eq(&self, other: &Self) -> bool {
2427        match (self, other) {
2428            (
2429                Expr::BinaryExpr(BinaryExpr {
2430                    left: self_left,
2431                    op: self_op,
2432                    right: self_right,
2433                }),
2434                Expr::BinaryExpr(BinaryExpr {
2435                    left: other_left,
2436                    op: other_op,
2437                    right: other_right,
2438                }),
2439            ) => {
2440                if self_op != other_op {
2441                    return false;
2442                }
2443
2444                if matches!(
2445                    self_op,
2446                    Operator::Plus
2447                        | Operator::Multiply
2448                        | Operator::BitwiseAnd
2449                        | Operator::BitwiseOr
2450                        | Operator::BitwiseXor
2451                        | Operator::Eq
2452                        | Operator::NotEq
2453                ) {
2454                    (self_left.normalize_eq(other_left)
2455                        && self_right.normalize_eq(other_right))
2456                        || (self_left.normalize_eq(other_right)
2457                            && self_right.normalize_eq(other_left))
2458                } else {
2459                    self_left.normalize_eq(other_left)
2460                        && self_right.normalize_eq(other_right)
2461                }
2462            }
2463            (
2464                Expr::Alias(Alias {
2465                    expr: self_expr,
2466                    relation: self_relation,
2467                    name: self_name,
2468                    ..
2469                }),
2470                Expr::Alias(Alias {
2471                    expr: other_expr,
2472                    relation: other_relation,
2473                    name: other_name,
2474                    ..
2475                }),
2476            ) => {
2477                self_name == other_name
2478                    && self_relation == other_relation
2479                    && self_expr.normalize_eq(other_expr)
2480            }
2481            (
2482                Expr::Like(Like {
2483                    negated: self_negated,
2484                    expr: self_expr,
2485                    pattern: self_pattern,
2486                    escape_char: self_escape_char,
2487                    case_insensitive: self_case_insensitive,
2488                }),
2489                Expr::Like(Like {
2490                    negated: other_negated,
2491                    expr: other_expr,
2492                    pattern: other_pattern,
2493                    escape_char: other_escape_char,
2494                    case_insensitive: other_case_insensitive,
2495                }),
2496            )
2497            | (
2498                Expr::SimilarTo(Like {
2499                    negated: self_negated,
2500                    expr: self_expr,
2501                    pattern: self_pattern,
2502                    escape_char: self_escape_char,
2503                    case_insensitive: self_case_insensitive,
2504                }),
2505                Expr::SimilarTo(Like {
2506                    negated: other_negated,
2507                    expr: other_expr,
2508                    pattern: other_pattern,
2509                    escape_char: other_escape_char,
2510                    case_insensitive: other_case_insensitive,
2511                }),
2512            ) => {
2513                self_negated == other_negated
2514                    && self_escape_char == other_escape_char
2515                    && self_case_insensitive == other_case_insensitive
2516                    && self_expr.normalize_eq(other_expr)
2517                    && self_pattern.normalize_eq(other_pattern)
2518            }
2519            (Expr::Not(self_expr), Expr::Not(other_expr))
2520            | (Expr::IsNull(self_expr), Expr::IsNull(other_expr))
2521            | (Expr::IsTrue(self_expr), Expr::IsTrue(other_expr))
2522            | (Expr::IsFalse(self_expr), Expr::IsFalse(other_expr))
2523            | (Expr::IsUnknown(self_expr), Expr::IsUnknown(other_expr))
2524            | (Expr::IsNotNull(self_expr), Expr::IsNotNull(other_expr))
2525            | (Expr::IsNotTrue(self_expr), Expr::IsNotTrue(other_expr))
2526            | (Expr::IsNotFalse(self_expr), Expr::IsNotFalse(other_expr))
2527            | (Expr::IsNotUnknown(self_expr), Expr::IsNotUnknown(other_expr))
2528            | (Expr::Negative(self_expr), Expr::Negative(other_expr)) => {
2529                self_expr.normalize_eq(other_expr)
2530            }
2531            (
2532                Expr::Unnest(Unnest {
2533                    expr: self_expr,
2534                    outer: self_outer,
2535                }),
2536                Expr::Unnest(Unnest {
2537                    expr: other_expr,
2538                    outer: other_outer,
2539                }),
2540            ) => self_outer == other_outer && self_expr.normalize_eq(other_expr),
2541            (
2542                Expr::Between(Between {
2543                    expr: self_expr,
2544                    negated: self_negated,
2545                    low: self_low,
2546                    high: self_high,
2547                }),
2548                Expr::Between(Between {
2549                    expr: other_expr,
2550                    negated: other_negated,
2551                    low: other_low,
2552                    high: other_high,
2553                }),
2554            ) => {
2555                self_negated == other_negated
2556                    && self_expr.normalize_eq(other_expr)
2557                    && self_low.normalize_eq(other_low)
2558                    && self_high.normalize_eq(other_high)
2559            }
2560            (
2561                Expr::Cast(Cast {
2562                    expr: self_expr,
2563                    field: self_field,
2564                }),
2565                Expr::Cast(Cast {
2566                    expr: other_expr,
2567                    field: other_field,
2568                }),
2569            )
2570            | (
2571                Expr::TryCast(TryCast {
2572                    expr: self_expr,
2573                    field: self_field,
2574                }),
2575                Expr::TryCast(TryCast {
2576                    expr: other_expr,
2577                    field: other_field,
2578                }),
2579            ) => self_field == other_field && self_expr.normalize_eq(other_expr),
2580            (
2581                Expr::ScalarFunction(ScalarFunction {
2582                    func: self_func,
2583                    args: self_args,
2584                }),
2585                Expr::ScalarFunction(ScalarFunction {
2586                    func: other_func,
2587                    args: other_args,
2588                }),
2589            ) => {
2590                self_func == other_func
2591                    && self_args.len() == other_args.len()
2592                    && self_args
2593                        .iter()
2594                        .zip(other_args.iter())
2595                        .all(|(a, b)| a.normalize_eq(b))
2596            }
2597            (
2598                Expr::AggregateFunction(AggregateFunction {
2599                    func: self_func,
2600                    params:
2601                        AggregateFunctionParams {
2602                            args: self_args,
2603                            distinct: self_distinct,
2604                            filter: self_filter,
2605                            order_by: self_order_by,
2606                            null_treatment: self_null_treatment,
2607                        },
2608                }),
2609                Expr::AggregateFunction(AggregateFunction {
2610                    func: other_func,
2611                    params:
2612                        AggregateFunctionParams {
2613                            args: other_args,
2614                            distinct: other_distinct,
2615                            filter: other_filter,
2616                            order_by: other_order_by,
2617                            null_treatment: other_null_treatment,
2618                        },
2619                }),
2620            ) => {
2621                self_func == other_func
2622                    && self_distinct == other_distinct
2623                    && self_null_treatment == other_null_treatment
2624                    && self_args.len() == other_args.len()
2625                    && self_args
2626                        .iter()
2627                        .zip(other_args.iter())
2628                        .all(|(a, b)| a.normalize_eq(b))
2629                    && match (self_filter, other_filter) {
2630                        (Some(self_filter), Some(other_filter)) => {
2631                            self_filter.normalize_eq(other_filter)
2632                        }
2633                        (None, None) => true,
2634                        _ => false,
2635                    }
2636                    && self_order_by
2637                        .iter()
2638                        .zip(other_order_by.iter())
2639                        .all(|(a, b)| {
2640                            a.asc == b.asc
2641                                && a.nulls_first == b.nulls_first
2642                                && a.expr.normalize_eq(&b.expr)
2643                        })
2644                    && self_order_by.len() == other_order_by.len()
2645            }
2646            (Expr::WindowFunction(left), Expr::WindowFunction(other)) => {
2647                let WindowFunction {
2648                    fun: self_fun,
2649                    params:
2650                        WindowFunctionParams {
2651                            args: self_args,
2652                            window_frame: self_window_frame,
2653                            partition_by: self_partition_by,
2654                            order_by: self_order_by,
2655                            filter: self_filter,
2656                            null_treatment: self_null_treatment,
2657                            distinct: self_distinct,
2658                        },
2659                } = left.as_ref();
2660                let WindowFunction {
2661                    fun: other_fun,
2662                    params:
2663                        WindowFunctionParams {
2664                            args: other_args,
2665                            window_frame: other_window_frame,
2666                            partition_by: other_partition_by,
2667                            order_by: other_order_by,
2668                            filter: other_filter,
2669                            null_treatment: other_null_treatment,
2670                            distinct: other_distinct,
2671                        },
2672                } = other.as_ref();
2673
2674                self_fun == other_fun
2675                    && self_window_frame == other_window_frame
2676                    && match (self_filter, other_filter) {
2677                        (Some(a), Some(b)) => a.normalize_eq(b),
2678                        (None, None) => true,
2679                        _ => false,
2680                    }
2681                    && self_null_treatment == other_null_treatment
2682                    && self_args.len() == other_args.len()
2683                    && self_args
2684                        .iter()
2685                        .zip(other_args.iter())
2686                        .all(|(a, b)| a.normalize_eq(b))
2687                    && self_partition_by.len() == other_partition_by.len()
2688                    && self_partition_by
2689                        .iter()
2690                        .zip(other_partition_by.iter())
2691                        .all(|(a, b)| a.normalize_eq(b))
2692                    && self_order_by.len() == other_order_by.len()
2693                    && self_order_by
2694                        .iter()
2695                        .zip(other_order_by.iter())
2696                        .all(|(a, b)| {
2697                            a.asc == b.asc
2698                                && a.nulls_first == b.nulls_first
2699                                && a.expr.normalize_eq(&b.expr)
2700                        })
2701                    && self_distinct == other_distinct
2702            }
2703            (
2704                Expr::Exists(Exists {
2705                    subquery: self_subquery,
2706                    negated: self_negated,
2707                }),
2708                Expr::Exists(Exists {
2709                    subquery: other_subquery,
2710                    negated: other_negated,
2711                }),
2712            ) => {
2713                self_negated == other_negated
2714                    && self_subquery.normalize_eq(other_subquery)
2715            }
2716            (
2717                Expr::InSubquery(InSubquery {
2718                    expr: self_expr,
2719                    subquery: self_subquery,
2720                    negated: self_negated,
2721                }),
2722                Expr::InSubquery(InSubquery {
2723                    expr: other_expr,
2724                    subquery: other_subquery,
2725                    negated: other_negated,
2726                }),
2727            ) => {
2728                self_negated == other_negated
2729                    && self_expr.normalize_eq(other_expr)
2730                    && self_subquery.normalize_eq(other_subquery)
2731            }
2732            (
2733                Expr::ScalarSubquery(self_subquery),
2734                Expr::ScalarSubquery(other_subquery),
2735            ) => self_subquery.normalize_eq(other_subquery),
2736            (
2737                Expr::GroupingSet(GroupingSet::Rollup(self_exprs)),
2738                Expr::GroupingSet(GroupingSet::Rollup(other_exprs)),
2739            )
2740            | (
2741                Expr::GroupingSet(GroupingSet::Cube(self_exprs)),
2742                Expr::GroupingSet(GroupingSet::Cube(other_exprs)),
2743            ) => {
2744                self_exprs.len() == other_exprs.len()
2745                    && self_exprs
2746                        .iter()
2747                        .zip(other_exprs.iter())
2748                        .all(|(a, b)| a.normalize_eq(b))
2749            }
2750            (
2751                Expr::GroupingSet(GroupingSet::GroupingSets(self_exprs)),
2752                Expr::GroupingSet(GroupingSet::GroupingSets(other_exprs)),
2753            ) => {
2754                self_exprs.len() == other_exprs.len()
2755                    && self_exprs.iter().zip(other_exprs.iter()).all(|(a, b)| {
2756                        a.len() == b.len()
2757                            && a.iter().zip(b.iter()).all(|(x, y)| x.normalize_eq(y))
2758                    })
2759            }
2760            (
2761                Expr::InList(InList {
2762                    expr: self_expr,
2763                    list: self_list,
2764                    negated: self_negated,
2765                }),
2766                Expr::InList(InList {
2767                    expr: other_expr,
2768                    list: other_list,
2769                    negated: other_negated,
2770                }),
2771            ) => {
2772                // TODO: normalize_eq for lists, for example `a IN (c1 + c3, c3)` is equal to `a IN (c3, c1 + c3)`
2773                self_negated == other_negated
2774                    && self_expr.normalize_eq(other_expr)
2775                    && self_list.len() == other_list.len()
2776                    && self_list
2777                        .iter()
2778                        .zip(other_list.iter())
2779                        .all(|(a, b)| a.normalize_eq(b))
2780            }
2781            (
2782                Expr::Case(Case {
2783                    expr: self_expr,
2784                    when_then_expr: self_when_then_expr,
2785                    else_expr: self_else_expr,
2786                }),
2787                Expr::Case(Case {
2788                    expr: other_expr,
2789                    when_then_expr: other_when_then_expr,
2790                    else_expr: other_else_expr,
2791                }),
2792            ) => {
2793                // TODO: normalize_eq for when_then_expr
2794                // for example `CASE a WHEN 1 THEN 2 WHEN 3 THEN 4 ELSE 5 END` is equal to `CASE a WHEN 3 THEN 4 WHEN 1 THEN 2 ELSE 5 END`
2795                self_when_then_expr.len() == other_when_then_expr.len()
2796                    && self_when_then_expr
2797                        .iter()
2798                        .zip(other_when_then_expr.iter())
2799                        .all(|((self_when, self_then), (other_when, other_then))| {
2800                            self_when.normalize_eq(other_when)
2801                                && self_then.normalize_eq(other_then)
2802                        })
2803                    && match (self_expr, other_expr) {
2804                        (Some(self_expr), Some(other_expr)) => {
2805                            self_expr.normalize_eq(other_expr)
2806                        }
2807                        (None, None) => true,
2808                        (_, _) => false,
2809                    }
2810                    && match (self_else_expr, other_else_expr) {
2811                        (Some(self_else_expr), Some(other_else_expr)) => {
2812                            self_else_expr.normalize_eq(other_else_expr)
2813                        }
2814                        (None, None) => true,
2815                        (_, _) => false,
2816                    }
2817            }
2818            (_, _) => self == other,
2819        }
2820    }
2821}
2822
2823impl HashNode for Expr {
2824    /// As it is pretty easy to forget changing this method when `Expr` changes the
2825    /// implementation doesn't use wildcard patterns (`..`, `_`) to catch changes
2826    /// compile time.
2827    fn hash_node<H: Hasher>(&self, state: &mut H) {
2828        mem::discriminant(self).hash(state);
2829        match self {
2830            Expr::Alias(Alias {
2831                expr: _expr,
2832                relation,
2833                name,
2834                ..
2835            }) => {
2836                relation.hash(state);
2837                name.hash(state);
2838            }
2839            Expr::Column(column) => {
2840                column.hash(state);
2841            }
2842            Expr::ScalarVariable(field, name) => {
2843                field.hash(state);
2844                name.hash(state);
2845            }
2846            Expr::Literal(scalar_value, _) => {
2847                scalar_value.hash(state);
2848            }
2849            Expr::BinaryExpr(BinaryExpr {
2850                left: _left,
2851                op,
2852                right: _right,
2853            }) => {
2854                op.hash(state);
2855            }
2856            Expr::Like(Like {
2857                negated,
2858                expr: _expr,
2859                pattern: _pattern,
2860                escape_char,
2861                case_insensitive,
2862            })
2863            | Expr::SimilarTo(Like {
2864                negated,
2865                expr: _expr,
2866                pattern: _pattern,
2867                escape_char,
2868                case_insensitive,
2869            }) => {
2870                negated.hash(state);
2871                escape_char.hash(state);
2872                case_insensitive.hash(state);
2873            }
2874            Expr::Not(_expr)
2875            | Expr::IsNotNull(_expr)
2876            | Expr::IsNull(_expr)
2877            | Expr::IsTrue(_expr)
2878            | Expr::IsFalse(_expr)
2879            | Expr::IsUnknown(_expr)
2880            | Expr::IsNotTrue(_expr)
2881            | Expr::IsNotFalse(_expr)
2882            | Expr::IsNotUnknown(_expr)
2883            | Expr::Negative(_expr) => {}
2884            Expr::Between(Between {
2885                expr: _expr,
2886                negated,
2887                low: _low,
2888                high: _high,
2889            }) => {
2890                negated.hash(state);
2891            }
2892            Expr::Case(Case {
2893                expr: _expr,
2894                when_then_expr: _when_then_expr,
2895                else_expr: _else_expr,
2896            }) => {}
2897            Expr::Cast(Cast { expr: _expr, field })
2898            | Expr::TryCast(TryCast { expr: _expr, field }) => {
2899                field.hash(state);
2900            }
2901            Expr::ScalarFunction(ScalarFunction { func, args: _args }) => {
2902                func.hash(state);
2903            }
2904            Expr::AggregateFunction(AggregateFunction {
2905                func,
2906                params:
2907                    AggregateFunctionParams {
2908                        args: _args,
2909                        distinct,
2910                        filter: _,
2911                        order_by: _,
2912                        null_treatment,
2913                    },
2914            }) => {
2915                func.hash(state);
2916                distinct.hash(state);
2917                null_treatment.hash(state);
2918            }
2919            Expr::WindowFunction(window_fun) => {
2920                let WindowFunction {
2921                    fun,
2922                    params:
2923                        WindowFunctionParams {
2924                            args: _args,
2925                            partition_by: _,
2926                            order_by: _,
2927                            window_frame,
2928                            filter,
2929                            null_treatment,
2930                            distinct,
2931                        },
2932                } = window_fun.as_ref();
2933                fun.hash(state);
2934                window_frame.hash(state);
2935                filter.hash(state);
2936                null_treatment.hash(state);
2937                distinct.hash(state);
2938            }
2939            Expr::InList(InList {
2940                expr: _expr,
2941                list: _list,
2942                negated,
2943            }) => {
2944                negated.hash(state);
2945            }
2946            Expr::Exists(Exists { subquery, negated }) => {
2947                subquery.hash(state);
2948                negated.hash(state);
2949            }
2950            Expr::InSubquery(InSubquery {
2951                expr: _expr,
2952                subquery,
2953                negated,
2954            }) => {
2955                subquery.hash(state);
2956                negated.hash(state);
2957            }
2958            Expr::SetComparison(SetComparison {
2959                expr: _,
2960                subquery,
2961                op,
2962                quantifier,
2963            }) => {
2964                subquery.hash(state);
2965                op.hash(state);
2966                quantifier.hash(state);
2967            }
2968            Expr::ScalarSubquery(subquery) => {
2969                subquery.hash(state);
2970            }
2971            #[expect(deprecated)]
2972            Expr::Wildcard { qualifier, options } => {
2973                qualifier.hash(state);
2974                options.hash(state);
2975            }
2976            Expr::GroupingSet(grouping_set) => {
2977                mem::discriminant(grouping_set).hash(state);
2978                match grouping_set {
2979                    GroupingSet::Rollup(_exprs) | GroupingSet::Cube(_exprs) => {}
2980                    GroupingSet::GroupingSets(_exprs) => {}
2981                }
2982            }
2983            Expr::Placeholder(place_holder) => {
2984                place_holder.hash(state);
2985            }
2986            Expr::OuterReferenceColumn(field, column) => {
2987                field.hash(state);
2988                column.hash(state);
2989            }
2990            Expr::Unnest(Unnest { expr: _expr, outer }) => {
2991                outer.hash(state);
2992            }
2993            Expr::HigherOrderFunction(HigherOrderFunction { func, args: _args }) => {
2994                func.hash(state);
2995            }
2996            Expr::Lambda(Lambda { params, body: _ }) => {
2997                params.hash(state);
2998            }
2999            Expr::LambdaVariable(LambdaVariable {
3000                name,
3001                field,
3002                spans: _,
3003            }) => {
3004                name.hash(state);
3005                field.hash(state);
3006            }
3007        }
3008    }
3009}
3010
3011// Modifies expr to match the DataType, metadata, and nullability of other if it is
3012// a placeholder with previously unspecified type information (i.e., most placeholders)
3013fn rewrite_placeholder(expr: &mut Expr, other: &Expr, schema: &DFSchema) -> Result<()> {
3014    if let Expr::Placeholder(Placeholder { id: _, field }) = expr
3015        && field.is_none()
3016    {
3017        let other_field = other.to_field(schema);
3018        match other_field {
3019            Err(e) => {
3020                Err(e.context(format!(
3021                    "Can not find type of {other} needed to infer type of {expr}"
3022                )))?;
3023            }
3024            Ok((_, other_field)) => {
3025                // We can't infer the nullability of the future parameter that might
3026                // be bound, so ensure this is set to true
3027                *field = Some(other_field.as_ref().clone().with_nullable(true).into());
3028            }
3029        }
3030    }
3031    Ok(())
3032}
3033
3034#[macro_export]
3035macro_rules! expr_vec_fmt {
3036    ( $ARRAY:expr ) => {{
3037        $ARRAY
3038            .iter()
3039            .map(|e| format!("{e}"))
3040            .collect::<Vec<String>>()
3041            .join(", ")
3042    }};
3043}
3044/// Infer an untyped placeholder on the left of a single-column subquery predicate from the subquery projection
3045fn rewrite_placeholder_from_subquery(
3046    kind: &str,
3047    expr: &mut Expr,
3048    subquery: &Subquery,
3049) -> Result<()> {
3050    let subquery_schema = subquery.subquery.schema();
3051    match &subquery_schema.fields()[..] {
3052        [subquery_field] => {
3053            let column =
3054                Expr::Column(Column::new_unqualified(subquery_field.name().clone()));
3055            rewrite_placeholder(expr, &column, subquery_schema)
3056        }
3057        _ => plan_err!(
3058            "{kind} should only return one column, but found {}: {}",
3059            subquery_schema.fields().len(),
3060            subquery_schema.field_names().join(", ")
3061        ),
3062    }
3063}
3064
3065struct SchemaDisplay<'a>(&'a Expr);
3066impl Display for SchemaDisplay<'_> {
3067    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
3068        match self.0 {
3069            // The same as Display
3070            // TODO: remove the next line after `Expr::Wildcard` is removed
3071            #[expect(deprecated)]
3072            Expr::Column(_)
3073            | Expr::Literal(_, _)
3074            | Expr::ScalarVariable(..)
3075            | Expr::OuterReferenceColumn(..)
3076            | Expr::Placeholder(_)
3077            | Expr::Wildcard { .. } => write!(f, "{}", self.0),
3078            Expr::AggregateFunction(AggregateFunction { func, params }) => {
3079                match func.schema_name(params) {
3080                    Ok(name) => {
3081                        write!(f, "{name}")
3082                    }
3083                    Err(e) => {
3084                        write!(f, "got error from schema_name {e}")
3085                    }
3086                }
3087            }
3088            // Expr is not shown since it is aliased
3089            Expr::Alias(Alias {
3090                name,
3091                relation: Some(relation),
3092                ..
3093            }) => write!(f, "{relation}.{name}"),
3094            Expr::Alias(Alias { name, .. }) => write!(f, "{name}"),
3095            Expr::Between(Between {
3096                expr,
3097                negated,
3098                low,
3099                high,
3100            }) => {
3101                let not = if *negated { "NOT " } else { "" };
3102                write!(
3103                    f,
3104                    "{} {not}BETWEEN {} AND {}",
3105                    SchemaDisplay(expr),
3106                    SchemaDisplay(low),
3107                    SchemaDisplay(high),
3108                )
3109            }
3110            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
3111                write!(f, "{} {op} {}", SchemaDisplay(left), SchemaDisplay(right))
3112            }
3113            Expr::Case(Case {
3114                expr,
3115                when_then_expr,
3116                else_expr,
3117            }) => {
3118                write!(f, "CASE ")?;
3119
3120                if let Some(e) = expr {
3121                    write!(f, "{} ", SchemaDisplay(e))?;
3122                }
3123
3124                for (when, then) in when_then_expr {
3125                    write!(
3126                        f,
3127                        "WHEN {} THEN {} ",
3128                        SchemaDisplay(when),
3129                        SchemaDisplay(then),
3130                    )?;
3131                }
3132
3133                if let Some(e) = else_expr {
3134                    write!(f, "ELSE {} ", SchemaDisplay(e))?;
3135                }
3136
3137                write!(f, "END")
3138            }
3139            // Cast expr is not shown to be consistent with Postgres and Spark <https://github.com/apache/datafusion/pull/3222>
3140            Expr::Cast(Cast { expr, .. }) | Expr::TryCast(TryCast { expr, .. }) => {
3141                write!(f, "{}", SchemaDisplay(expr))
3142            }
3143            Expr::InList(InList {
3144                expr,
3145                list,
3146                negated,
3147            }) => {
3148                let inlist_name = schema_name_from_exprs(list)?;
3149
3150                if *negated {
3151                    write!(f, "{} NOT IN {}", SchemaDisplay(expr), inlist_name)
3152                } else {
3153                    write!(f, "{} IN {}", SchemaDisplay(expr), inlist_name)
3154                }
3155            }
3156            Expr::Exists(Exists { negated: true, .. }) => write!(f, "NOT EXISTS"),
3157            Expr::Exists(Exists { negated: false, .. }) => write!(f, "EXISTS"),
3158            Expr::GroupingSet(GroupingSet::Cube(exprs)) => {
3159                write!(f, "ROLLUP ({})", schema_name_from_exprs(exprs)?)
3160            }
3161            Expr::GroupingSet(GroupingSet::GroupingSets(lists_of_exprs)) => {
3162                write!(f, "GROUPING SETS (")?;
3163                for exprs in lists_of_exprs.iter() {
3164                    write!(f, "({})", schema_name_from_exprs(exprs)?)?;
3165                }
3166                write!(f, ")")
3167            }
3168            Expr::GroupingSet(GroupingSet::Rollup(exprs)) => {
3169                write!(f, "ROLLUP ({})", schema_name_from_exprs(exprs)?)
3170            }
3171            Expr::IsNull(expr) => write!(f, "{} IS NULL", SchemaDisplay(expr)),
3172            Expr::IsNotNull(expr) => {
3173                write!(f, "{} IS NOT NULL", SchemaDisplay(expr))
3174            }
3175            Expr::IsUnknown(expr) => {
3176                write!(f, "{} IS UNKNOWN", SchemaDisplay(expr))
3177            }
3178            Expr::IsNotUnknown(expr) => {
3179                write!(f, "{} IS NOT UNKNOWN", SchemaDisplay(expr))
3180            }
3181            Expr::InSubquery(InSubquery { negated: true, .. }) => {
3182                write!(f, "NOT IN")
3183            }
3184            Expr::InSubquery(InSubquery { negated: false, .. }) => write!(f, "IN"),
3185            Expr::SetComparison(SetComparison {
3186                expr,
3187                op,
3188                quantifier,
3189                ..
3190            }) => write!(f, "{} {op} {quantifier}", SchemaDisplay(expr.as_ref())),
3191            Expr::IsTrue(expr) => write!(f, "{} IS TRUE", SchemaDisplay(expr)),
3192            Expr::IsFalse(expr) => write!(f, "{} IS FALSE", SchemaDisplay(expr)),
3193            Expr::IsNotTrue(expr) => {
3194                write!(f, "{} IS NOT TRUE", SchemaDisplay(expr))
3195            }
3196            Expr::IsNotFalse(expr) => {
3197                write!(f, "{} IS NOT FALSE", SchemaDisplay(expr))
3198            }
3199            Expr::Like(Like {
3200                negated,
3201                expr,
3202                pattern,
3203                escape_char,
3204                case_insensitive,
3205            }) => {
3206                write!(
3207                    f,
3208                    "{} {}{} {}",
3209                    SchemaDisplay(expr),
3210                    if *negated { "NOT " } else { "" },
3211                    if *case_insensitive { "ILIKE" } else { "LIKE" },
3212                    SchemaDisplay(pattern),
3213                )?;
3214
3215                if let Some(char) = escape_char {
3216                    write!(f, " CHAR '{char}'")?;
3217                }
3218
3219                Ok(())
3220            }
3221            Expr::Negative(expr) => write!(f, "(- {})", SchemaDisplay(expr)),
3222            Expr::Not(expr) => write!(f, "NOT {}", SchemaDisplay(expr)),
3223            Expr::Unnest(Unnest { expr, outer }) => {
3224                let name = if *outer { "UNNEST_OUTER" } else { "UNNEST" };
3225                write!(f, "{name}({})", SchemaDisplay(expr))
3226            }
3227            Expr::ScalarFunction(ScalarFunction { func, args }) => {
3228                match func.schema_name(args) {
3229                    Ok(name) => {
3230                        write!(f, "{name}")
3231                    }
3232                    Err(e) => {
3233                        write!(f, "got error from schema_name {e}")
3234                    }
3235                }
3236            }
3237            Expr::ScalarSubquery(Subquery { subquery, .. }) => {
3238                write!(f, "{}", subquery.schema().field(0).name())
3239            }
3240            Expr::SimilarTo(Like {
3241                negated,
3242                expr,
3243                pattern,
3244                escape_char,
3245                ..
3246            }) => {
3247                write!(
3248                    f,
3249                    "{} {} {}",
3250                    SchemaDisplay(expr),
3251                    if *negated {
3252                        "NOT SIMILAR TO"
3253                    } else {
3254                        "SIMILAR TO"
3255                    },
3256                    SchemaDisplay(pattern),
3257                )?;
3258                if let Some(char) = escape_char {
3259                    write!(f, " CHAR '{char}'")?;
3260                }
3261
3262                Ok(())
3263            }
3264            Expr::WindowFunction(window_fun) => {
3265                let WindowFunction { fun, params } = window_fun.as_ref();
3266                match fun {
3267                    WindowFunctionDefinition::AggregateUDF(fun) => {
3268                        match fun.window_function_schema_name(params) {
3269                            Ok(name) => {
3270                                write!(f, "{name}")
3271                            }
3272                            Err(e) => {
3273                                write!(
3274                                    f,
3275                                    "got error from window_function_schema_name {e}"
3276                                )
3277                            }
3278                        }
3279                    }
3280                    _ => {
3281                        let WindowFunctionParams {
3282                            args,
3283                            partition_by,
3284                            order_by,
3285                            window_frame,
3286                            filter,
3287                            null_treatment,
3288                            distinct,
3289                        } = params;
3290
3291                        // Write function name and open parenthesis
3292                        write!(f, "{fun}(")?;
3293
3294                        // If DISTINCT, emit the keyword
3295                        if *distinct {
3296                            write!(f, "DISTINCT ")?;
3297                        }
3298
3299                        // Write the comma‑separated argument list
3300                        write!(
3301                            f,
3302                            "{}",
3303                            schema_name_from_exprs_comma_separated_without_space(args)?
3304                        )?;
3305
3306                        // **Close the argument parenthesis**
3307                        write!(f, ")")?;
3308
3309                        if let Some(null_treatment) = null_treatment {
3310                            write!(f, " {null_treatment}")?;
3311                        }
3312
3313                        if let Some(filter) = filter {
3314                            write!(f, " FILTER (WHERE {filter})")?;
3315                        }
3316
3317                        if !partition_by.is_empty() {
3318                            write!(
3319                                f,
3320                                " PARTITION BY [{}]",
3321                                schema_name_from_exprs(partition_by)?
3322                            )?;
3323                        }
3324
3325                        if !order_by.is_empty() {
3326                            write!(
3327                                f,
3328                                " ORDER BY [{}]",
3329                                schema_name_from_sorts(order_by)?
3330                            )?;
3331                        }
3332
3333                        write!(f, " {window_frame}")
3334                    }
3335                }
3336            }
3337            Expr::HigherOrderFunction(HigherOrderFunction { func, args }) => {
3338                match func.schema_name(args) {
3339                    Ok(name) => {
3340                        write!(f, "{name}")
3341                    }
3342                    Err(e) => {
3343                        write!(f, "got error from schema_name {e}")
3344                    }
3345                }
3346            }
3347            Expr::Lambda(Lambda { params, body }) => {
3348                write!(
3349                    f,
3350                    "({}) -> {}",
3351                    display_comma_separated(params),
3352                    SchemaDisplay(body)
3353                )
3354            }
3355            Expr::LambdaVariable(c) => f.write_str(&c.name),
3356        }
3357    }
3358}
3359
3360/// A helper struct for displaying an `Expr` as an SQL-like string.
3361struct SqlDisplay<'a>(&'a Expr);
3362
3363impl Display for SqlDisplay<'_> {
3364    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
3365        match self.0 {
3366            Expr::Literal(scalar, _) => scalar.fmt(f),
3367            Expr::Alias(Alias { name, .. }) => write!(f, "{name}"),
3368            Expr::Between(Between {
3369                expr,
3370                negated,
3371                low,
3372                high,
3373            }) => {
3374                let not = if *negated { "NOT " } else { "" };
3375                write!(
3376                    f,
3377                    "{} {not}BETWEEN {} AND {}",
3378                    SqlDisplay(expr),
3379                    SqlDisplay(low),
3380                    SqlDisplay(high),
3381                )
3382            }
3383            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
3384                write!(f, "{} {op} {}", SqlDisplay(left), SqlDisplay(right))
3385            }
3386            Expr::Case(Case {
3387                expr,
3388                when_then_expr,
3389                else_expr,
3390            }) => {
3391                write!(f, "CASE ")?;
3392
3393                if let Some(e) = expr {
3394                    write!(f, "{} ", SqlDisplay(e))?;
3395                }
3396
3397                for (when, then) in when_then_expr {
3398                    write!(f, "WHEN {} THEN {} ", SqlDisplay(when), SqlDisplay(then))?;
3399                }
3400
3401                if let Some(e) = else_expr {
3402                    write!(f, "ELSE {} ", SqlDisplay(e))?;
3403                }
3404
3405                write!(f, "END")
3406            }
3407            Expr::Cast(Cast { expr, .. }) | Expr::TryCast(TryCast { expr, .. }) => {
3408                write!(f, "{}", SqlDisplay(expr))
3409            }
3410            Expr::InList(InList {
3411                expr,
3412                list,
3413                negated,
3414            }) => {
3415                write!(
3416                    f,
3417                    "{}{} IN {}",
3418                    SqlDisplay(expr),
3419                    if *negated { " NOT" } else { "" },
3420                    ExprListDisplay::comma_separated(list.as_slice())
3421                )
3422            }
3423            Expr::GroupingSet(GroupingSet::Cube(exprs)) => {
3424                write!(
3425                    f,
3426                    "ROLLUP ({})",
3427                    ExprListDisplay::comma_separated(exprs.as_slice())
3428                )
3429            }
3430            Expr::GroupingSet(GroupingSet::GroupingSets(lists_of_exprs)) => {
3431                write!(f, "GROUPING SETS (")?;
3432                for exprs in lists_of_exprs.iter() {
3433                    write!(
3434                        f,
3435                        "({})",
3436                        ExprListDisplay::comma_separated(exprs.as_slice())
3437                    )?;
3438                }
3439                write!(f, ")")
3440            }
3441            Expr::GroupingSet(GroupingSet::Rollup(exprs)) => {
3442                write!(
3443                    f,
3444                    "ROLLUP ({})",
3445                    ExprListDisplay::comma_separated(exprs.as_slice())
3446                )
3447            }
3448            Expr::IsNull(expr) => write!(f, "{} IS NULL", SqlDisplay(expr)),
3449            Expr::IsNotNull(expr) => {
3450                write!(f, "{} IS NOT NULL", SqlDisplay(expr))
3451            }
3452            Expr::IsUnknown(expr) => {
3453                write!(f, "{} IS UNKNOWN", SqlDisplay(expr))
3454            }
3455            Expr::IsNotUnknown(expr) => {
3456                write!(f, "{} IS NOT UNKNOWN", SqlDisplay(expr))
3457            }
3458            Expr::IsTrue(expr) => write!(f, "{} IS TRUE", SqlDisplay(expr)),
3459            Expr::IsFalse(expr) => write!(f, "{} IS FALSE", SqlDisplay(expr)),
3460            Expr::IsNotTrue(expr) => {
3461                write!(f, "{} IS NOT TRUE", SqlDisplay(expr))
3462            }
3463            Expr::IsNotFalse(expr) => {
3464                write!(f, "{} IS NOT FALSE", SqlDisplay(expr))
3465            }
3466            Expr::Like(Like {
3467                negated,
3468                expr,
3469                pattern,
3470                escape_char,
3471                case_insensitive,
3472            }) => {
3473                write!(
3474                    f,
3475                    "{} {}{} {}",
3476                    SqlDisplay(expr),
3477                    if *negated { "NOT " } else { "" },
3478                    if *case_insensitive { "ILIKE" } else { "LIKE" },
3479                    SqlDisplay(pattern),
3480                )?;
3481
3482                if let Some(char) = escape_char {
3483                    write!(f, " CHAR '{char}'")?;
3484                }
3485
3486                Ok(())
3487            }
3488            Expr::Negative(expr) => write!(f, "(- {})", SqlDisplay(expr)),
3489            Expr::Not(expr) => write!(f, "NOT {}", SqlDisplay(expr)),
3490            Expr::Unnest(Unnest { expr, outer }) => {
3491                let name = if *outer { "UNNEST_OUTER" } else { "UNNEST" };
3492                write!(f, "{name}({})", SqlDisplay(expr))
3493            }
3494            Expr::SimilarTo(Like {
3495                negated,
3496                expr,
3497                pattern,
3498                escape_char,
3499                ..
3500            }) => {
3501                write!(
3502                    f,
3503                    "{} {} {}",
3504                    SqlDisplay(expr),
3505                    if *negated {
3506                        "NOT SIMILAR TO"
3507                    } else {
3508                        "SIMILAR TO"
3509                    },
3510                    SqlDisplay(pattern),
3511                )?;
3512                if let Some(char) = escape_char {
3513                    write!(f, " CHAR '{char}'")?;
3514                }
3515
3516                Ok(())
3517            }
3518            Expr::AggregateFunction(AggregateFunction { func, params }) => {
3519                match func.human_display(params) {
3520                    Ok(name) => {
3521                        write!(f, "{name}")
3522                    }
3523                    Err(e) => {
3524                        write!(f, "got error from schema_name {e}")
3525                    }
3526                }
3527            }
3528            Expr::Lambda(Lambda { params, body }) => {
3529                write!(f, "({}) -> {}", params.join(", "), SchemaDisplay(body))
3530            }
3531            _ => write!(f, "{}", self.0),
3532        }
3533    }
3534}
3535
3536/// Get schema_name for Vector of expressions
3537///
3538/// Internal usage. Please call `schema_name_from_exprs` instead
3539// TODO: Use ", " to standardize the formatting of Vec<Expr>,
3540// <https://github.com/apache/datafusion/issues/10364>
3541pub(crate) fn schema_name_from_exprs_comma_separated_without_space(
3542    exprs: &[Expr],
3543) -> Result<String, fmt::Error> {
3544    schema_name_from_exprs_inner(exprs, ",")
3545}
3546
3547/// Formats a list of `&Expr` with a custom separator using SQL display format
3548pub struct ExprListDisplay<'a> {
3549    exprs: &'a [Expr],
3550    sep: &'a str,
3551}
3552
3553impl<'a> ExprListDisplay<'a> {
3554    /// Create a new display struct with the given expressions and separator
3555    pub fn new(exprs: &'a [Expr], sep: &'a str) -> Self {
3556        Self { exprs, sep }
3557    }
3558
3559    /// Create a new display struct with comma-space separator
3560    pub fn comma_separated(exprs: &'a [Expr]) -> Self {
3561        Self::new(exprs, ", ")
3562    }
3563}
3564
3565impl Display for ExprListDisplay<'_> {
3566    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
3567        let mut first = true;
3568        for expr in self.exprs {
3569            if !first {
3570                write!(f, "{}", self.sep)?;
3571            }
3572            write!(f, "{}", SqlDisplay(expr))?;
3573            first = false;
3574        }
3575        Ok(())
3576    }
3577}
3578
3579/// Get schema_name for Vector of expressions
3580pub fn schema_name_from_exprs(exprs: &[Expr]) -> Result<String, fmt::Error> {
3581    schema_name_from_exprs_inner(exprs, ", ")
3582}
3583
3584fn schema_name_from_exprs_inner(exprs: &[Expr], sep: &str) -> Result<String, fmt::Error> {
3585    let mut s = String::new();
3586    for (i, e) in exprs.iter().enumerate() {
3587        if i > 0 {
3588            write!(&mut s, "{sep}")?;
3589        }
3590        write!(&mut s, "{}", SchemaDisplay(e))?;
3591    }
3592
3593    Ok(s)
3594}
3595
3596pub fn schema_name_from_sorts(sorts: &[Sort]) -> Result<String, fmt::Error> {
3597    let mut s = String::new();
3598    for (i, e) in sorts.iter().enumerate() {
3599        if i > 0 {
3600            write!(&mut s, ", ")?;
3601        }
3602        let ordering = if e.asc { "ASC" } else { "DESC" };
3603        let nulls_ordering = if e.nulls_first {
3604            "NULLS FIRST"
3605        } else {
3606            "NULLS LAST"
3607        };
3608        write!(&mut s, "{} {} {}", e.expr, ordering, nulls_ordering)?;
3609    }
3610
3611    Ok(s)
3612}
3613
3614pub const OUTER_REFERENCE_COLUMN_PREFIX: &str = "outer_ref";
3615pub const UNNEST_COLUMN_PREFIX: &str = "UNNEST";
3616
3617/// Format expressions for display as part of a logical plan. In many cases, this will produce
3618/// similar output to `Expr.name()` except that column names will be prefixed with '#'.
3619impl Display for Expr {
3620    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
3621        match self {
3622            Expr::Alias(Alias { expr, name, .. }) => write!(f, "{expr} AS {name}"),
3623            Expr::Column(c) => write!(f, "{c}"),
3624            Expr::OuterReferenceColumn(_, c) => {
3625                write!(f, "{OUTER_REFERENCE_COLUMN_PREFIX}({c})")
3626            }
3627            Expr::ScalarVariable(_, var_names) => write!(f, "{}", var_names.join(".")),
3628            Expr::Literal(v, metadata) => {
3629                match metadata.as_ref().map(|m| m.is_empty()).unwrap_or(true) {
3630                    false => write!(f, "{v:?} {:?}", metadata.as_ref().unwrap()),
3631                    true => write!(f, "{v:?}"),
3632                }
3633            }
3634            Expr::Case(case) => {
3635                write!(f, "CASE ")?;
3636                if let Some(e) = &case.expr {
3637                    write!(f, "{e} ")?;
3638                }
3639                for (w, t) in &case.when_then_expr {
3640                    write!(f, "WHEN {w} THEN {t} ")?;
3641                }
3642                if let Some(e) = &case.else_expr {
3643                    write!(f, "ELSE {e} ")?;
3644                }
3645                write!(f, "END")
3646            }
3647            Expr::Cast(Cast { expr, field }) => {
3648                let formatted =
3649                    format_type_and_metadata(field.data_type(), Some(field.metadata()));
3650                write!(f, "CAST({expr} AS {formatted})")
3651            }
3652            Expr::TryCast(TryCast { expr, field }) => {
3653                let formatted =
3654                    format_type_and_metadata(field.data_type(), Some(field.metadata()));
3655                write!(f, "TRY_CAST({expr} AS {formatted})")
3656            }
3657            Expr::Not(expr) => write!(f, "NOT {expr}"),
3658            Expr::Negative(expr) => write!(f, "(- {expr})"),
3659            Expr::IsNull(expr) => write!(f, "{expr} IS NULL"),
3660            Expr::IsNotNull(expr) => write!(f, "{expr} IS NOT NULL"),
3661            Expr::IsTrue(expr) => write!(f, "{expr} IS TRUE"),
3662            Expr::IsFalse(expr) => write!(f, "{expr} IS FALSE"),
3663            Expr::IsUnknown(expr) => write!(f, "{expr} IS UNKNOWN"),
3664            Expr::IsNotTrue(expr) => write!(f, "{expr} IS NOT TRUE"),
3665            Expr::IsNotFalse(expr) => write!(f, "{expr} IS NOT FALSE"),
3666            Expr::IsNotUnknown(expr) => write!(f, "{expr} IS NOT UNKNOWN"),
3667            Expr::Exists(Exists {
3668                subquery,
3669                negated: true,
3670            }) => write!(f, "NOT EXISTS ({subquery:?})"),
3671            Expr::Exists(Exists {
3672                subquery,
3673                negated: false,
3674            }) => write!(f, "EXISTS ({subquery:?})"),
3675            Expr::InSubquery(InSubquery {
3676                expr,
3677                subquery,
3678                negated: true,
3679            }) => write!(f, "{expr} NOT IN ({subquery:?})"),
3680            Expr::InSubquery(InSubquery {
3681                expr,
3682                subquery,
3683                negated: false,
3684            }) => write!(f, "{expr} IN ({subquery:?})"),
3685            Expr::SetComparison(SetComparison {
3686                expr,
3687                subquery,
3688                op,
3689                quantifier,
3690            }) => write!(f, "{expr} {op} {quantifier} ({subquery:?})"),
3691            Expr::ScalarSubquery(subquery) => write!(f, "({subquery:?})"),
3692            Expr::BinaryExpr(expr) => write!(f, "{expr}"),
3693            Expr::ScalarFunction(fun) => {
3694                fmt_function(f, fun.name(), false, &fun.args, true)
3695            }
3696            Expr::WindowFunction(window_fun) => {
3697                let WindowFunction { fun, params } = window_fun.as_ref();
3698                match fun {
3699                    WindowFunctionDefinition::AggregateUDF(fun) => {
3700                        match fun.window_function_display_name(params) {
3701                            Ok(name) => {
3702                                write!(f, "{name}")
3703                            }
3704                            Err(e) => {
3705                                write!(
3706                                    f,
3707                                    "got error from window_function_display_name {e}"
3708                                )
3709                            }
3710                        }
3711                    }
3712                    WindowFunctionDefinition::WindowUDF(fun) => {
3713                        let WindowFunctionParams {
3714                            args,
3715                            partition_by,
3716                            order_by,
3717                            window_frame,
3718                            filter,
3719                            null_treatment,
3720                            distinct,
3721                        } = params;
3722
3723                        fmt_function(f, &fun.to_string(), *distinct, args, true)?;
3724
3725                        if let Some(nt) = null_treatment {
3726                            write!(f, "{nt}")?;
3727                        }
3728
3729                        if let Some(fe) = filter {
3730                            write!(f, " FILTER (WHERE {fe})")?;
3731                        }
3732
3733                        if !partition_by.is_empty() {
3734                            write!(f, " PARTITION BY [{}]", expr_vec_fmt!(partition_by))?;
3735                        }
3736                        if !order_by.is_empty() {
3737                            write!(f, " ORDER BY [{}]", expr_vec_fmt!(order_by))?;
3738                        }
3739                        write!(
3740                            f,
3741                            " {} BETWEEN {} AND {}",
3742                            window_frame.units,
3743                            window_frame.start_bound,
3744                            window_frame.end_bound
3745                        )
3746                    }
3747                }
3748            }
3749            Expr::AggregateFunction(AggregateFunction { func, params }) => {
3750                match func.display_name(params) {
3751                    Ok(name) => {
3752                        write!(f, "{name}")
3753                    }
3754                    Err(e) => {
3755                        write!(f, "got error from display_name {e}")
3756                    }
3757                }
3758            }
3759            Expr::Between(Between {
3760                expr,
3761                negated,
3762                low,
3763                high,
3764            }) => {
3765                if *negated {
3766                    write!(f, "{expr} NOT BETWEEN {low} AND {high}")
3767                } else {
3768                    write!(f, "{expr} BETWEEN {low} AND {high}")
3769                }
3770            }
3771            Expr::Like(Like {
3772                negated,
3773                expr,
3774                pattern,
3775                escape_char,
3776                case_insensitive,
3777            }) => {
3778                write!(f, "{expr}")?;
3779                let op_name = if *case_insensitive { "ILIKE" } else { "LIKE" };
3780                if *negated {
3781                    write!(f, " NOT")?;
3782                }
3783                if let Some(char) = escape_char {
3784                    write!(f, " {op_name} {pattern} ESCAPE '{char}'")
3785                } else {
3786                    write!(f, " {op_name} {pattern}")
3787                }
3788            }
3789            Expr::SimilarTo(Like {
3790                negated,
3791                expr,
3792                pattern,
3793                escape_char,
3794                case_insensitive: _,
3795            }) => {
3796                write!(f, "{expr}")?;
3797                if *negated {
3798                    write!(f, " NOT")?;
3799                }
3800                if let Some(char) = escape_char {
3801                    write!(f, " SIMILAR TO {pattern} ESCAPE '{char}'")
3802                } else {
3803                    write!(f, " SIMILAR TO {pattern}")
3804                }
3805            }
3806            Expr::InList(InList {
3807                expr,
3808                list,
3809                negated,
3810            }) => {
3811                if *negated {
3812                    write!(f, "{expr} NOT IN ([{}])", expr_vec_fmt!(list))
3813                } else {
3814                    write!(f, "{expr} IN ([{}])", expr_vec_fmt!(list))
3815                }
3816            }
3817            #[expect(deprecated)]
3818            Expr::Wildcard { qualifier, options } => match qualifier {
3819                Some(qualifier) => write!(f, "{qualifier}.*{options}"),
3820                None => write!(f, "*{options}"),
3821            },
3822            Expr::GroupingSet(grouping_sets) => match grouping_sets {
3823                GroupingSet::Rollup(exprs) => {
3824                    // ROLLUP (c0, c1, c2)
3825                    write!(f, "ROLLUP ({})", expr_vec_fmt!(exprs))
3826                }
3827                GroupingSet::Cube(exprs) => {
3828                    // CUBE (c0, c1, c2)
3829                    write!(f, "CUBE ({})", expr_vec_fmt!(exprs))
3830                }
3831                GroupingSet::GroupingSets(lists_of_exprs) => {
3832                    // GROUPING SETS ((c0), (c1, c2), (c3, c4))
3833                    write!(
3834                        f,
3835                        "GROUPING SETS ({})",
3836                        lists_of_exprs
3837                            .iter()
3838                            .map(|exprs| format!("({})", expr_vec_fmt!(exprs)))
3839                            .collect::<Vec<String>>()
3840                            .join(", ")
3841                    )
3842                }
3843            },
3844            Expr::Placeholder(Placeholder { id, .. }) => write!(f, "{id}"),
3845            Expr::Unnest(Unnest { expr, .. }) => {
3846                write!(f, "{UNNEST_COLUMN_PREFIX}({expr})")
3847            }
3848            Expr::HigherOrderFunction(fun) => {
3849                fmt_function(f, fun.name(), false, &fun.args, true)
3850            }
3851            Expr::Lambda(Lambda { params, body }) => {
3852                write!(f, "({}) -> {body}", params.join(", "))
3853            }
3854            Expr::LambdaVariable(c) => f.write_str(&c.name),
3855        }
3856    }
3857}
3858
3859fn fmt_function(
3860    f: &mut Formatter,
3861    fun: &str,
3862    distinct: bool,
3863    args: &[Expr],
3864    display: bool,
3865) -> fmt::Result {
3866    let args: Vec<String> = match display {
3867        true => args.iter().map(|arg| format!("{arg}")).collect(),
3868        false => args.iter().map(|arg| format!("{arg:?}")).collect(),
3869    };
3870
3871    let distinct_str = match distinct {
3872        true => "DISTINCT ",
3873        false => "",
3874    };
3875    write!(f, "{}({}{})", fun, distinct_str, args.join(", "))
3876}
3877
3878/// The name of the column (field) that this `Expr` will produce in the physical plan.
3879/// The difference from [Expr::schema_name] is that top-level columns are unqualified.
3880pub fn physical_name(expr: &Expr) -> Result<String> {
3881    match expr {
3882        Expr::Column(col) => Ok(col.name.clone()),
3883        Expr::Alias(alias) => Ok(alias.name.clone()),
3884        _ => Ok(expr.schema_name().to_string()),
3885    }
3886}
3887
3888#[cfg(test)]
3889mod test {
3890    use crate::expr_fn::col;
3891    use crate::test::function_stub::max_udaf;
3892    use crate::{
3893        ColumnarValue, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Volatility, case,
3894        lit, placeholder, qualified_wildcard, wildcard, wildcard_with_options,
3895    };
3896    use arrow::datatypes::{Field, Schema};
3897    use sqlparser::ast;
3898    use sqlparser::ast::{Ident, IdentWithAlias};
3899
3900    #[test]
3901    fn infer_placeholder_in_clause() {
3902        // SELECT * FROM employees WHERE department_id IN ($1, $2, $3);
3903        let column = col("department_id");
3904        let param_placeholders = vec![
3905            Expr::Placeholder(Placeholder {
3906                id: "$1".to_string(),
3907                field: None,
3908            }),
3909            Expr::Placeholder(Placeholder {
3910                id: "$2".to_string(),
3911                field: None,
3912            }),
3913            Expr::Placeholder(Placeholder {
3914                id: "$3".to_string(),
3915                field: None,
3916            }),
3917        ];
3918        let in_list = Expr::InList(InList {
3919            expr: Box::new(column),
3920            list: param_placeholders,
3921            negated: false,
3922        });
3923
3924        let schema = Arc::new(Schema::new(vec![
3925            Field::new("name", DataType::Utf8, true),
3926            Field::new("department_id", DataType::Int32, true),
3927        ]));
3928        let df_schema = DFSchema::try_from(schema).unwrap();
3929
3930        let (inferred_expr, contains_placeholder) =
3931            in_list.infer_placeholder_types(&df_schema).unwrap();
3932
3933        assert!(contains_placeholder);
3934
3935        match inferred_expr {
3936            Expr::InList(in_list) => {
3937                for expr in in_list.list {
3938                    match expr {
3939                        Expr::Placeholder(placeholder) => {
3940                            assert_eq!(
3941                                placeholder.field.unwrap().data_type(),
3942                                &DataType::Int32,
3943                                "Placeholder {} should infer Int32",
3944                                placeholder.id
3945                            );
3946                        }
3947                        _ => panic!("Expected Placeholder expression"),
3948                    }
3949                }
3950            }
3951            _ => panic!("Expected InList expression"),
3952        }
3953    }
3954
3955    #[test]
3956    fn infer_placeholder_in_subquery() {
3957        // WHERE $1 IN (SELECT a FROM t)
3958        let subquery_field = Field::new("a", DataType::Int32, false);
3959        let subquery_schema = Arc::new(
3960            DFSchema::from_unqualified_fields(
3961                vec![subquery_field].into(),
3962                Metadata::new(),
3963            )
3964            .unwrap(),
3965        );
3966        let subquery = Subquery {
3967            subquery: Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
3968                produce_one_row: false,
3969                schema: subquery_schema,
3970            })),
3971            outer_ref_columns: vec![],
3972            spans: Spans::new(),
3973        };
3974
3975        let in_subquery = Expr::InSubquery(InSubquery {
3976            expr: Box::new(Expr::Placeholder(Placeholder {
3977                id: "$1".to_string(),
3978                field: None,
3979            })),
3980            subquery,
3981            negated: false,
3982        });
3983
3984        let outer_schema = DFSchema::empty();
3985        let (inferred_expr, contains_placeholder) =
3986            in_subquery.infer_placeholder_types(&outer_schema).unwrap();
3987
3988        assert!(contains_placeholder);
3989
3990        match inferred_expr {
3991            Expr::InSubquery(in_subquery) => match *in_subquery.expr {
3992                Expr::Placeholder(placeholder) => {
3993                    let inferred = placeholder.field.expect("placeholder field");
3994                    assert_eq!(inferred.data_type(), &DataType::Int32);
3995                    assert!(inferred.is_nullable());
3996                }
3997                _ => panic!("Expected Placeholder expression in InSubquery"),
3998            },
3999            _ => panic!("Expected InSubquery expression"),
4000        }
4001    }
4002
4003    #[test]
4004    fn infer_placeholder_not_in_subquery() {
4005        // WHERE $1 NOT IN (SELECT a FROM t)
4006        let subquery_field = Field::new("a", DataType::Int32, false);
4007        let subquery_schema = Arc::new(
4008            DFSchema::from_unqualified_fields(
4009                vec![subquery_field].into(),
4010                Metadata::new(),
4011            )
4012            .unwrap(),
4013        );
4014        let subquery = Subquery {
4015            subquery: Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
4016                produce_one_row: false,
4017                schema: subquery_schema,
4018            })),
4019            outer_ref_columns: vec![],
4020            spans: Spans::new(),
4021        };
4022
4023        let not_in_subquery = Expr::InSubquery(InSubquery {
4024            expr: Box::new(Expr::Placeholder(Placeholder {
4025                id: "$1".to_string(),
4026                field: None,
4027            })),
4028            subquery,
4029            negated: true,
4030        });
4031
4032        let outer_schema = DFSchema::empty();
4033        let (inferred_expr, contains_placeholder) = not_in_subquery
4034            .infer_placeholder_types(&outer_schema)
4035            .unwrap();
4036
4037        assert!(contains_placeholder);
4038
4039        match inferred_expr {
4040            Expr::InSubquery(in_subquery) => {
4041                assert!(in_subquery.negated, "negated flag must be preserved");
4042                match *in_subquery.expr {
4043                    Expr::Placeholder(placeholder) => {
4044                        let inferred = placeholder.field.expect("placeholder field");
4045                        assert_eq!(inferred.data_type(), &DataType::Int32);
4046                        assert!(inferred.is_nullable());
4047                    }
4048                    _ => {
4049                        panic!("Expected Placeholder expression in InSubquery")
4050                    }
4051                }
4052            }
4053            _ => panic!("Expected InSubquery expression"),
4054        }
4055    }
4056
4057    #[test]
4058    fn infer_placeholder_set_comparison_any() {
4059        // WHERE $1 = ANY (SELECT a FROM t) -- parallel to infer_placeholder_in_subquery
4060        let subquery_field = Field::new("a", DataType::Int32, false);
4061        let subquery_schema = Arc::new(
4062            DFSchema::from_unqualified_fields(
4063                vec![subquery_field].into(),
4064                Metadata::new(),
4065            )
4066            .unwrap(),
4067        );
4068        let subquery = Subquery {
4069            subquery: Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
4070                produce_one_row: false,
4071                schema: subquery_schema,
4072            })),
4073            outer_ref_columns: vec![],
4074            spans: Spans::new(),
4075        };
4076
4077        let set_cmp = Expr::SetComparison(SetComparison {
4078            expr: Box::new(Expr::Placeholder(Placeholder {
4079                id: "$1".to_string(),
4080                field: None,
4081            })),
4082            subquery,
4083            op: Operator::Eq,
4084            quantifier: SetQuantifier::Any,
4085        });
4086
4087        let outer_schema = DFSchema::empty();
4088        let (inferred_expr, contains_placeholder) =
4089            set_cmp.infer_placeholder_types(&outer_schema).unwrap();
4090
4091        assert!(contains_placeholder);
4092
4093        match inferred_expr {
4094            Expr::SetComparison(sc) => {
4095                assert_eq!(sc.quantifier, SetQuantifier::Any);
4096                match *sc.expr {
4097                    Expr::Placeholder(p) => {
4098                        let inferred =
4099                            p.field.expect("placeholder field should be Int32");
4100                        assert_eq!(inferred.data_type(), &DataType::Int32);
4101                        assert!(inferred.is_nullable());
4102                    }
4103                    _ => panic!("Expected Placeholder expression in SetComparison"),
4104                }
4105            }
4106            _ => panic!("Expected SetComparison expression"),
4107        }
4108    }
4109
4110    #[test]
4111    fn infer_placeholder_set_comparison_all() {
4112        // WHERE $1 <> ALL (SELECT a FROM t)
4113        let subquery_field = Field::new("a", DataType::Int32, false);
4114        let subquery_schema = Arc::new(
4115            DFSchema::from_unqualified_fields(
4116                vec![subquery_field].into(),
4117                Metadata::new(),
4118            )
4119            .unwrap(),
4120        );
4121        let subquery = Subquery {
4122            subquery: Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
4123                produce_one_row: false,
4124                schema: subquery_schema,
4125            })),
4126            outer_ref_columns: vec![],
4127            spans: Spans::new(),
4128        };
4129
4130        let set_cmp = Expr::SetComparison(SetComparison {
4131            expr: Box::new(Expr::Placeholder(Placeholder {
4132                id: "$1".to_string(),
4133                field: None,
4134            })),
4135            subquery,
4136            op: Operator::NotEq,
4137            quantifier: SetQuantifier::All,
4138        });
4139
4140        let outer_schema = DFSchema::empty();
4141        let (inferred_expr, contains_placeholder) =
4142            set_cmp.infer_placeholder_types(&outer_schema).unwrap();
4143
4144        assert!(contains_placeholder);
4145
4146        match inferred_expr {
4147            Expr::SetComparison(sc) => {
4148                assert_eq!(sc.quantifier, SetQuantifier::All);
4149                match *sc.expr {
4150                    Expr::Placeholder(p) => {
4151                        let inferred =
4152                            p.field.expect("placeholder field should be Int32");
4153                        assert_eq!(inferred.data_type(), &DataType::Int32);
4154                        assert!(inferred.is_nullable());
4155                    }
4156                    _ => panic!("Expected Placeholder expression in SetComparison"),
4157                }
4158            }
4159            _ => panic!("Expected SetComparison expression"),
4160        }
4161    }
4162
4163    #[test]
4164    fn infer_placeholder_like_and_similar_to() {
4165        // name LIKE $1
4166        let schema =
4167            Arc::new(Schema::new(vec![Field::new("name", DataType::Utf8, true)]));
4168        let df_schema = DFSchema::try_from(schema).unwrap();
4169
4170        let like = Like {
4171            expr: Box::new(col("name")),
4172            pattern: Box::new(Expr::Placeholder(Placeholder {
4173                id: "$1".to_string(),
4174                field: None,
4175            })),
4176            negated: false,
4177            case_insensitive: false,
4178            escape_char: None,
4179        };
4180
4181        let expr = Expr::Like(like.clone());
4182
4183        let (inferred_expr, _) = expr.infer_placeholder_types(&df_schema).unwrap();
4184        match inferred_expr {
4185            Expr::Like(like) => match *like.pattern {
4186                Expr::Placeholder(placeholder) => {
4187                    assert_eq!(placeholder.field.unwrap().data_type(), &DataType::Utf8);
4188                }
4189                _ => panic!("Expected Placeholder"),
4190            },
4191            _ => panic!("Expected Like"),
4192        }
4193
4194        // name SIMILAR TO $1
4195        let expr = Expr::SimilarTo(like);
4196
4197        let (inferred_expr, _) = expr.infer_placeholder_types(&df_schema).unwrap();
4198        match inferred_expr {
4199            Expr::SimilarTo(like) => match *like.pattern {
4200                Expr::Placeholder(placeholder) => {
4201                    assert_eq!(
4202                        placeholder.field.unwrap().data_type(),
4203                        &DataType::Utf8,
4204                        "Placeholder {} should infer Utf8",
4205                        placeholder.id
4206                    );
4207                }
4208                _ => panic!("Expected Placeholder expression"),
4209            },
4210            _ => panic!("Expected SimilarTo expression"),
4211        }
4212    }
4213
4214    #[test]
4215    fn infer_placeholder_with_metadata() {
4216        // name == $1, where name is a non-nullable string
4217        let schema = Arc::new(Schema::new(vec![
4218            Field::new("name", DataType::Utf8, false)
4219                .with_metadata(Metadata::new().with("some_key", "some_value")),
4220        ]));
4221        let df_schema = DFSchema::try_from(schema).unwrap();
4222
4223        let expr = binary_expr(col("name"), Operator::Eq, placeholder("$1"));
4224
4225        let (inferred_expr, _) = expr.infer_placeholder_types(&df_schema).unwrap();
4226        match inferred_expr {
4227            Expr::BinaryExpr(BinaryExpr { right, .. }) => match *right {
4228                Expr::Placeholder(placeholder) => {
4229                    assert_eq!(
4230                        placeholder.field.as_ref().unwrap().data_type(),
4231                        &DataType::Utf8
4232                    );
4233                    assert_eq!(
4234                        placeholder.field.as_ref().unwrap().metadata(),
4235                        df_schema.field(0).metadata()
4236                    );
4237                    // Inferred placeholder should still be nullable
4238                    assert!(placeholder.field.as_ref().unwrap().is_nullable());
4239                }
4240                _ => panic!("Expected Placeholder"),
4241            },
4242            _ => panic!("Expected BinaryExpr"),
4243        }
4244    }
4245
4246    #[test]
4247    fn format_case_when() -> Result<()> {
4248        let expr = case(col("a"))
4249            .when(lit(1), lit(true))
4250            .when(lit(0), lit(false))
4251            .otherwise(lit(ScalarValue::Null))?;
4252        let expected = "CASE a WHEN Int32(1) THEN Boolean(true) WHEN Int32(0) THEN Boolean(false) ELSE NULL END";
4253        assert_eq!(expected, format!("{expr}"));
4254        Ok(())
4255    }
4256
4257    #[test]
4258    fn format_cast() -> Result<()> {
4259        let expr = Expr::Cast(Cast {
4260            expr: Box::new(Expr::Literal(ScalarValue::Float32(Some(1.23)), None)),
4261            field: DataType::Utf8.into_nullable_field_ref(),
4262        });
4263        let expected_canonical = "CAST(Float32(1.23) AS Utf8)";
4264        assert_eq!(expected_canonical, format!("{expr}"));
4265        // Note that CAST intentionally has a name that is different from its `Display`
4266        // representation. CAST does not change the name of expressions.
4267        assert_eq!("Float32(1.23)", expr.schema_name().to_string());
4268        Ok(())
4269    }
4270
4271    #[test]
4272    fn format_decimal_literal() {
4273        let expr = lit(ScalarValue::Decimal128(Some(1), 1, 1));
4274        assert_eq!("Decimal128(0.1,1,1)", format!("{expr}"));
4275        assert_eq!("Decimal128(0.1,1,1)", expr.schema_name().to_string());
4276        assert_eq!("0.1", expr.human_display().to_string());
4277
4278        let expr = lit(ScalarValue::Decimal128(Some(120), 3, 2));
4279        assert_eq!("Decimal128(1.20,3,2)", format!("{expr}"));
4280        assert_eq!("Decimal128(1.20,3,2)", expr.schema_name().to_string());
4281        assert_eq!("1.20", expr.human_display().to_string());
4282
4283        let null_expr = lit(ScalarValue::Decimal128(None, 10, 2));
4284        assert_eq!("Decimal128(NULL,10,2)", format!("{null_expr}"));
4285        assert_eq!("Decimal128(NULL,10,2)", null_expr.schema_name().to_string());
4286        assert_eq!("NULL", null_expr.human_display().to_string());
4287    }
4288
4289    #[test]
4290    fn test_partial_ord() {
4291        // Test validates that partial ord is defined for Expr, not
4292        // intended to exhaustively test all possibilities
4293        let exp1 = col("a") + lit(1);
4294        let exp2 = col("a") + lit(2);
4295        let exp3 = !(col("a") + lit(2));
4296
4297        assert!(exp1 < exp2);
4298        assert!(exp3 > exp2);
4299        assert!(exp1 < exp3)
4300    }
4301
4302    #[test]
4303    fn test_collect_expr() -> Result<()> {
4304        // single column
4305        {
4306            let expr = &Expr::Cast(Cast::new(Box::new(col("a")), DataType::Float64));
4307            let columns = expr.column_refs();
4308            assert_eq!(1, columns.len());
4309            assert!(columns.contains(&Column::from_name("a")));
4310        }
4311
4312        // multiple columns
4313        {
4314            let expr = col("a") + col("b") + lit(1);
4315            let columns = expr.column_refs();
4316            assert_eq!(2, columns.len());
4317            assert!(columns.contains(&Column::from_name("a")));
4318            assert!(columns.contains(&Column::from_name("b")));
4319        }
4320
4321        Ok(())
4322    }
4323
4324    #[test]
4325    fn test_logical_ops() {
4326        assert_eq!(
4327            format!("{}", lit(1u32).eq(lit(2u32))),
4328            "UInt32(1) = UInt32(2)"
4329        );
4330        assert_eq!(
4331            format!("{}", lit(1u32).not_eq(lit(2u32))),
4332            "UInt32(1) != UInt32(2)"
4333        );
4334        assert_eq!(
4335            format!("{}", lit(1u32).gt(lit(2u32))),
4336            "UInt32(1) > UInt32(2)"
4337        );
4338        assert_eq!(
4339            format!("{}", lit(1u32).gt_eq(lit(2u32))),
4340            "UInt32(1) >= UInt32(2)"
4341        );
4342        assert_eq!(
4343            format!("{}", lit(1u32).lt(lit(2u32))),
4344            "UInt32(1) < UInt32(2)"
4345        );
4346        assert_eq!(
4347            format!("{}", lit(1u32).lt_eq(lit(2u32))),
4348            "UInt32(1) <= UInt32(2)"
4349        );
4350        assert_eq!(
4351            format!("{}", lit(1u32).and(lit(2u32))),
4352            "UInt32(1) AND UInt32(2)"
4353        );
4354        assert_eq!(
4355            format!("{}", lit(1u32).or(lit(2u32))),
4356            "UInt32(1) OR UInt32(2)"
4357        );
4358    }
4359
4360    #[test]
4361    fn test_is_volatile_scalar_func() {
4362        // UDF
4363        #[derive(Debug, PartialEq, Eq, Hash)]
4364        struct TestScalarUDF {
4365            signature: Signature,
4366        }
4367        impl ScalarUDFImpl for TestScalarUDF {
4368            fn name(&self) -> &str {
4369                "TestScalarUDF"
4370            }
4371
4372            fn signature(&self) -> &Signature {
4373                &self.signature
4374            }
4375
4376            fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
4377                Ok(DataType::Utf8)
4378            }
4379
4380            fn invoke_with_args(
4381                &self,
4382                _args: ScalarFunctionArgs,
4383            ) -> Result<ColumnarValue> {
4384                Ok(ColumnarValue::Scalar(ScalarValue::from("a")))
4385            }
4386        }
4387        let udf = Arc::new(ScalarUDF::from(TestScalarUDF {
4388            signature: Signature::uniform(1, vec![DataType::Float32], Volatility::Stable),
4389        }));
4390        assert_ne!(udf.signature().volatility, Volatility::Volatile);
4391
4392        let udf = Arc::new(ScalarUDF::from(TestScalarUDF {
4393            signature: Signature::uniform(
4394                1,
4395                vec![DataType::Float32],
4396                Volatility::Volatile,
4397            ),
4398        }));
4399        assert_eq!(udf.signature().volatility, Volatility::Volatile);
4400    }
4401
4402    use super::*;
4403    use crate::logical_plan::{EmptyRelation, LogicalPlan};
4404
4405    #[test]
4406    fn normalize_eq_window_function_over_clause_lengths() {
4407        let window = |partition_by: Vec<Expr>, order_by: Vec<Sort>| {
4408            let mut window = WindowFunction::new(max_udaf(), vec![col("value")]);
4409            window.params.partition_by = partition_by;
4410            window.params.order_by = order_by;
4411            Expr::from(window)
4412        };
4413        let base = window(vec![col("a")], vec![Sort::new(col("a"), true, true)]);
4414
4415        let extra_partition = window(
4416            vec![col("a"), col("b")],
4417            vec![Sort::new(col("a"), true, true)],
4418        );
4419        assert!(!base.normalize_eq(&extra_partition));
4420
4421        let extra_order = window(
4422            vec![col("a")],
4423            vec![
4424                Sort::new(col("a"), true, true),
4425                Sort::new(col("b"), true, true),
4426            ],
4427        );
4428        assert!(!base.normalize_eq(&extra_order));
4429    }
4430
4431    #[test]
4432    fn test_display_wildcard() {
4433        assert_eq!(format!("{}", wildcard()), "*");
4434        assert_eq!(format!("{}", qualified_wildcard("t1")), "t1.*");
4435        assert_eq!(
4436            format!(
4437                "{}",
4438                wildcard_with_options(wildcard_options(
4439                    Some(IlikeSelectItem {
4440                        pattern: "c1".to_string()
4441                    }),
4442                    None,
4443                    None,
4444                    None,
4445                    None
4446                ))
4447            ),
4448            "* ILIKE 'c1'"
4449        );
4450        assert_eq!(
4451            format!(
4452                "{}",
4453                wildcard_with_options(wildcard_options(
4454                    None,
4455                    Some(ExcludeSelectItem::Multiple(vec![
4456                        Ident::from("c1").into(),
4457                        Ident::from("c2").into()
4458                    ])),
4459                    None,
4460                    None,
4461                    None
4462                ))
4463            ),
4464            "* EXCLUDE (c1, c2)"
4465        );
4466        assert_eq!(
4467            format!(
4468                "{}",
4469                wildcard_with_options(wildcard_options(
4470                    None,
4471                    None,
4472                    Some(ExceptSelectItem {
4473                        first_element: Ident::from("c1"),
4474                        additional_elements: vec![Ident::from("c2")]
4475                    }),
4476                    None,
4477                    None
4478                ))
4479            ),
4480            "* EXCEPT (c1, c2)"
4481        );
4482        assert_eq!(
4483            format!(
4484                "{}",
4485                wildcard_with_options(wildcard_options(
4486                    None,
4487                    None,
4488                    None,
4489                    Some(PlannedReplaceSelectItem {
4490                        items: vec![ReplaceSelectElement {
4491                            expr: ast::Expr::Identifier(Ident::from("c1")),
4492                            column_name: Ident::from("a1"),
4493                            as_keyword: false
4494                        }],
4495                        planned_expressions: vec![]
4496                    }),
4497                    None
4498                ))
4499            ),
4500            "* REPLACE (c1 a1)"
4501        );
4502        assert_eq!(
4503            format!(
4504                "{}",
4505                wildcard_with_options(wildcard_options(
4506                    None,
4507                    None,
4508                    None,
4509                    None,
4510                    Some(RenameSelectItem::Multiple(vec![IdentWithAlias {
4511                        ident: Ident::from("c1"),
4512                        alias: Ident::from("a1")
4513                    }]))
4514                ))
4515            ),
4516            "* RENAME (c1 AS a1)"
4517        )
4518    }
4519
4520    #[test]
4521    fn test_display_set_comparison() {
4522        let subquery = Subquery {
4523            subquery: Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
4524                produce_one_row: false,
4525                schema: Arc::new(DFSchema::empty()),
4526            })),
4527            outer_ref_columns: vec![],
4528            spans: Spans::new(),
4529        };
4530
4531        let expr = Expr::SetComparison(SetComparison::new(
4532            Box::new(Expr::Column(Column::from_name("a"))),
4533            subquery,
4534            Operator::Gt,
4535            SetQuantifier::Any,
4536        ));
4537
4538        assert_eq!(format!("{expr}"), "a > ANY (<subquery>)");
4539        assert_eq!(format!("{}", expr.human_display()), "a > ANY (<subquery>)");
4540    }
4541
4542    #[test]
4543    fn test_schema_display_alias_with_relation() {
4544        assert_eq!(
4545            format!(
4546                "{}",
4547                SchemaDisplay(
4548                    &lit(1).alias_qualified("table_name".into(), "column_name")
4549                )
4550            ),
4551            "table_name.column_name"
4552        );
4553    }
4554
4555    #[test]
4556    fn test_schema_display_alias_without_relation() {
4557        assert_eq!(
4558            format!(
4559                "{}",
4560                SchemaDisplay(&lit(1).alias_qualified(None::<&str>, "column_name"))
4561            ),
4562            "column_name"
4563        );
4564    }
4565
4566    #[test]
4567    fn test_unalias_nested_respects_user_metadata() {
4568        use std::collections::HashMap;
4569
4570        let base_expr = col("id");
4571
4572        let no_metadata = base_expr.clone().alias("alias");
4573        assert_eq!(no_metadata.unalias_nested().data, base_expr);
4574
4575        let Expr::Alias(empty_metadata_alias) = base_expr.clone().alias("alias") else {
4576            unreachable!();
4577        };
4578        let empty_metadata_alias = Expr::Alias(
4579            empty_metadata_alias.with_metadata(Some(FieldMetadata::default())),
4580        );
4581        assert_eq!(empty_metadata_alias.unalias_nested().data, base_expr);
4582
4583        let user_metadata = FieldMetadata::from(HashMap::from([(
4584            "some_key".to_string(),
4585            "some_value".to_string(),
4586        )]));
4587
4588        let Expr::Alias(user_alias) = base_expr.clone().alias("alias") else {
4589            unreachable!();
4590        };
4591        let user_alias =
4592            Expr::Alias(user_alias.with_metadata(Some(user_metadata.clone())));
4593        assert_eq!(user_alias.clone().unalias_nested().data, user_alias);
4594    }
4595
4596    fn wildcard_options(
4597        opt_ilike: Option<IlikeSelectItem>,
4598        opt_exclude: Option<ExcludeSelectItem>,
4599        opt_except: Option<ExceptSelectItem>,
4600        opt_replace: Option<PlannedReplaceSelectItem>,
4601        opt_rename: Option<RenameSelectItem>,
4602    ) -> WildcardOptions {
4603        WildcardOptions {
4604            ilike: opt_ilike,
4605            exclude: opt_exclude,
4606            except: opt_except,
4607            replace: opt_replace,
4608            rename: opt_rename,
4609        }
4610    }
4611
4612    #[test]
4613    fn test_size_of_expr() {
4614        // because Expr is such a widely used struct in DataFusion
4615        // it is important to keep its size as small as possible
4616        //
4617        // If this test fails when you change `Expr`, please try
4618        // `Box`ing the fields to make `Expr` smaller
4619        // See https://github.com/apache/datafusion/issues/16199 for details
4620        assert_eq!(size_of::<Expr>(), 112);
4621        assert_eq!(size_of::<ScalarValue>(), 64);
4622        assert_eq!(size_of::<DataType>(), 24); // 3 ptrs
4623        assert_eq!(size_of::<Vec<Expr>>(), 24);
4624        assert_eq!(size_of::<Arc<Expr>>(), 8);
4625    }
4626
4627    #[test]
4628    fn test_accept_exprs() {
4629        fn accept_exprs<E: AsRef<Expr>>(_: &[E]) {}
4630
4631        let expr = || -> Expr { lit(1) };
4632
4633        // Call accept_exprs with owned expressions
4634        let owned_exprs = vec![expr(), expr()];
4635        accept_exprs(&owned_exprs);
4636
4637        // Call accept_exprs with expressions from expr tree
4638        let udf = Expr::ScalarFunction(ScalarFunction {
4639            func: Arc::new(ScalarUDF::new_from_impl(TestUDF {})),
4640            args: vec![expr(), expr()],
4641        });
4642        let Expr::ScalarFunction(scalar) = &udf else {
4643            unreachable!()
4644        };
4645        accept_exprs(&scalar.args);
4646
4647        // Call accept_exprs with expressions collected from expr tree, without cloning
4648        let mut collected_refs: Vec<&Expr> = scalar.args.iter().collect();
4649        collected_refs.extend(&owned_exprs);
4650        accept_exprs(&collected_refs);
4651
4652        // test helpers
4653        #[derive(Debug, PartialEq, Eq, Hash)]
4654        struct TestUDF {}
4655        impl ScalarUDFImpl for TestUDF {
4656            fn name(&self) -> &str {
4657                unimplemented!()
4658            }
4659
4660            fn signature(&self) -> &Signature {
4661                unimplemented!()
4662            }
4663
4664            fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
4665                unimplemented!()
4666            }
4667
4668            fn invoke_with_args(
4669                &self,
4670                _args: ScalarFunctionArgs,
4671            ) -> Result<ColumnarValue> {
4672                unimplemented!()
4673            }
4674        }
4675    }
4676
4677    #[expect(deprecated)]
4678    mod intersect_metadata_tests {
4679        use super::super::intersect_metadata_for_union;
4680        use arrow::datatypes::Metadata;
4681
4682        #[test]
4683        fn all_branches_same_metadata() {
4684            let m1 = Metadata::new().with("key", "val");
4685            let m2 = Metadata::new().with("key", "val");
4686            let result = intersect_metadata_for_union([&m1, &m2]);
4687            assert_eq!(result, Metadata::new().with("key", "val"));
4688        }
4689
4690        #[test]
4691        fn conflicting_metadata_dropped() {
4692            let m1 = Metadata::new().with("key", "a");
4693            let m2 = Metadata::new().with("key", "b");
4694            let result = intersect_metadata_for_union([&m1, &m2]);
4695            assert!(result.is_empty());
4696        }
4697
4698        #[test]
4699        fn empty_metadata_branch_skipped() {
4700            let m1 = Metadata::new().with("key", "val");
4701            let m2 = Metadata::new(); // e.g. NULL literal
4702            let result = intersect_metadata_for_union([&m1, &m2]);
4703            assert_eq!(result, Metadata::new().with("key", "val"));
4704        }
4705
4706        #[test]
4707        fn empty_metadata_first_branch_skipped() {
4708            let m1 = Metadata::new();
4709            let m2 = Metadata::new().with("key", "val");
4710            let result = intersect_metadata_for_union([&m1, &m2]);
4711            assert_eq!(result, Metadata::new().with("key", "val"));
4712        }
4713
4714        #[test]
4715        fn all_branches_empty_metadata() {
4716            let m1 = Metadata::new();
4717            let m2 = Metadata::new();
4718            let result = intersect_metadata_for_union([&m1, &m2]);
4719            assert!(result.is_empty());
4720        }
4721
4722        #[test]
4723        fn mixed_empty_and_conflicting() {
4724            let m1 = Metadata::new().with("key", "a");
4725            let m2 = Metadata::new();
4726            let m3 = Metadata::new().with("key", "b");
4727            let result = intersect_metadata_for_union([&m1, &m2, &m3]);
4728            // m2 is skipped; m1 and m3 conflict → dropped
4729            assert!(result.is_empty());
4730        }
4731
4732        #[test]
4733        fn no_inputs() {
4734            let result = intersect_metadata_for_union(std::iter::empty::<&Metadata>());
4735            assert!(result.is_empty());
4736        }
4737    }
4738}