Skip to main content

datafusion_expr/
utils.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//! Expression utilities
6
7use std::cmp::Ordering;
8use std::collections::{BTreeSet, HashSet};
9use std::sync::Arc;
10
11use crate::expr::{Alias, Sort, WildcardOptions, WindowFunctionParams};
12use crate::expr_rewriter::strip_outer_reference;
13use crate::{
14    BinaryExpr, Expr, ExprSchemable, Filter, GroupingSet, LogicalPlan, Operator, and,
15};
16use datafusion_expr_common::signature::{Signature, TypeSignature};
17
18use arrow::datatypes::{DataType, Field, FieldRef, Schema};
19use datafusion_common::tree_node::{
20    Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
21};
22use datafusion_common::utils::get_at_indices;
23use datafusion_common::{
24    Column, DFSchema, DFSchemaRef, DataFusionError, Diagnostic, HashMap, Result, Span,
25    TableReference, internal_err, plan_datafusion_err, plan_err,
26};
27
28#[cfg(not(feature = "sql"))]
29use crate::sql::{ExceptSelectItem, ExcludeSelectItem, Ident, ObjectName};
30use indexmap::IndexSet;
31#[cfg(feature = "sql")]
32use sqlparser::ast::{ExceptSelectItem, ExcludeSelectItem, Ident, ObjectName};
33
34pub use datafusion_functions_aggregate_common::order::AggregateOrderSensitivity;
35
36///  The value to which `COUNT(*)` is expanded to in
37///  `COUNT(<constant>)` expressions
38pub use datafusion_common::utils::expr::COUNT_STAR_EXPANSION;
39
40/// Count the number of distinct exprs in a list of group by expressions. If the
41/// first element is a `GroupingSet` expression then it must be the only expr.
42pub fn grouping_set_expr_count(group_expr: &[Expr]) -> Result<usize> {
43    if let Some(Expr::GroupingSet(grouping_set)) = group_expr.first() {
44        if group_expr.len() > 1 {
45            return plan_err!(
46                "Invalid group by expressions, GroupingSet must be the only expression"
47            );
48        }
49        // Groupings sets have an additional integral column for the grouping id
50        Ok(grouping_set.distinct_expr().len() + 1)
51    } else {
52        grouping_set_to_exprlist(group_expr).map(|exprs| exprs.len())
53    }
54}
55
56/// Internal helper that generates indices for powerset subsets using bitset iteration.
57/// Returns an iterator of index vectors, where each vector contains the indices
58/// of elements to include in that subset.
59fn powerset_indices(len: usize) -> impl Iterator<Item = Vec<usize>> {
60    (0..(1 << len)).map(move |mask: u64| {
61        let mut indices = Vec::with_capacity(mask.count_ones() as usize);
62        let mut bitset = mask;
63        while bitset > 0 {
64            let rightmost: u64 = bitset & !(bitset - 1);
65            let idx = rightmost.trailing_zeros() as usize;
66            indices.push(idx);
67            bitset &= bitset - 1;
68        }
69        indices
70    })
71}
72
73/// The [power set] (or powerset) of a set S is the set of all subsets of S, \
74/// including the empty set and S itself.
75///
76/// Example:
77///
78/// If S is the set {x, y, z}, then all the subsets of S are \
79///  {} \
80///  {x} \
81///  {y} \
82///  {z} \
83///  {x, y} \
84///  {x, z} \
85///  {y, z} \
86///  {x, y, z} \
87///  and hence the power set of S is {{}, {x}, {y}, {z}, {x, y}, {x, z}, {y, z}, {x, y, z}}.
88///
89/// [power set]: https://en.wikipedia.org/wiki/Power_set
90pub fn powerset<T>(slice: &[T]) -> Result<Vec<Vec<&T>>> {
91    if slice.len() >= 64 {
92        return plan_err!("The size of the set must be less than 64");
93    }
94
95    Ok(powerset_indices(slice.len())
96        .map(|indices| indices.iter().map(|&idx| &slice[idx]).collect())
97        .collect())
98}
99
100/// check the number of expressions contained in the grouping_set
101fn check_grouping_set_size_limit(size: usize) -> Result<()> {
102    let max_grouping_set_size = 65535;
103    if size > max_grouping_set_size {
104        return plan_err!(
105            "The number of group_expression in grouping_set exceeds the maximum limit {max_grouping_set_size}, found {size}"
106        );
107    }
108
109    Ok(())
110}
111
112/// check the number of grouping_set contained in the grouping sets
113fn check_grouping_sets_size_limit(size: usize) -> Result<()> {
114    let max_grouping_sets_size = 4096;
115    if size > max_grouping_sets_size {
116        return plan_err!(
117            "The number of grouping_set in grouping_sets exceeds the maximum limit {max_grouping_sets_size}, found {size}"
118        );
119    }
120
121    Ok(())
122}
123
124/// Merge two grouping_set
125///
126/// # Example
127/// ```text
128/// (A, B), (C, D) -> (A, B, C, D)
129/// ```
130///
131/// # Error
132/// - [`DataFusionError`]: The number of group_expression in grouping_set exceeds the maximum limit
133///
134/// [`DataFusionError`]: datafusion_common::DataFusionError
135fn merge_grouping_set<T: Clone>(left: &[T], right: &[T]) -> Result<Vec<T>> {
136    check_grouping_set_size_limit(left.len() + right.len())?;
137    Ok(left.iter().chain(right.iter()).cloned().collect())
138}
139
140/// Compute the cross product of two grouping_sets
141///
142/// # Example
143/// ```text
144/// [(A, B), (C, D)], [(E), (F)] -> [(A, B, E), (A, B, F), (C, D, E), (C, D, F)]
145/// ```
146///
147/// # Error
148/// - [`DataFusionError`]: The number of group_expression in grouping_set exceeds the maximum limit
149/// - [`DataFusionError`]: The number of grouping_set in grouping_sets exceeds the maximum limit
150///
151/// [`DataFusionError`]: datafusion_common::DataFusionError
152fn cross_join_grouping_sets<T: Clone>(
153    left: &[Vec<T>],
154    right: &[Vec<T>],
155) -> Result<Vec<Vec<T>>> {
156    let grouping_sets_size = left.len() * right.len();
157
158    check_grouping_sets_size_limit(grouping_sets_size)?;
159
160    let mut result = Vec::with_capacity(grouping_sets_size);
161    for le in left {
162        for re in right {
163            result.push(merge_grouping_set(le, re)?);
164        }
165    }
166    Ok(result)
167}
168
169/// Convert multiple grouping expressions into one [`GroupingSet::GroupingSets`],\
170/// if the grouping expression does not contain [`Expr::GroupingSet`] or only has one expression,\
171/// no conversion will be performed.
172///
173/// e.g.
174///
175/// person.id,\
176/// GROUPING SETS ((person.age, person.salary),(person.age)),\
177/// ROLLUP(person.state, person.birth_date)
178///
179/// =>
180///
181/// GROUPING SETS (\
182///   (person.id, person.age, person.salary),\
183///   (person.id, person.age, person.salary, person.state),\
184///   (person.id, person.age, person.salary, person.state, person.birth_date),\
185///   (person.id, person.age),\
186///   (person.id, person.age, person.state),\
187///   (person.id, person.age, person.state, person.birth_date)\
188/// )
189pub fn enumerate_grouping_sets(group_expr: Vec<Expr>) -> Result<Vec<Expr>> {
190    let has_grouping_set = group_expr
191        .iter()
192        .any(|expr| matches!(expr, Expr::GroupingSet(_)));
193    if !has_grouping_set || group_expr.len() == 1 {
194        return Ok(group_expr);
195    }
196    // Only process mix grouping sets
197    let partial_sets = group_expr
198        .iter()
199        .map(|expr| {
200            let exprs = match expr {
201                Expr::GroupingSet(GroupingSet::GroupingSets(grouping_sets)) => {
202                    check_grouping_sets_size_limit(grouping_sets.len())?;
203                    grouping_sets.iter().map(|e| e.iter().collect()).collect()
204                }
205                Expr::GroupingSet(GroupingSet::Cube(group_exprs)) => {
206                    let grouping_sets = powerset(group_exprs)?;
207                    check_grouping_sets_size_limit(grouping_sets.len())?;
208                    grouping_sets
209                }
210                Expr::GroupingSet(GroupingSet::Rollup(group_exprs)) => {
211                    let size = group_exprs.len();
212                    let slice = group_exprs.as_slice();
213                    check_grouping_sets_size_limit(size * (size + 1) / 2 + 1)?;
214                    (0..=size).map(|i| slice[0..i].iter().collect()).collect()
215                }
216                expr => vec![vec![expr]],
217            };
218            Ok(exprs)
219        })
220        .collect::<Result<Vec<_>>>()?;
221
222    // Cross Join
223    let grouping_sets = partial_sets
224        .into_iter()
225        .map(Ok)
226        .reduce(|l, r| cross_join_grouping_sets(&l?, &r?))
227        .transpose()?
228        .map(|e| {
229            e.into_iter()
230                .map(|e| e.into_iter().cloned().collect())
231                .collect()
232        })
233        .unwrap_or_default();
234
235    Ok(vec![Expr::GroupingSet(GroupingSet::GroupingSets(
236        grouping_sets,
237    ))])
238}
239
240/// Find all distinct exprs in a list of group by expressions. If the
241/// first element is a `GroupingSet` expression then it must be the only expr.
242pub fn grouping_set_to_exprlist(group_expr: &[Expr]) -> Result<Vec<&Expr>> {
243    if let Some(Expr::GroupingSet(grouping_set)) = group_expr.first() {
244        if group_expr.len() > 1 {
245            return plan_err!(
246                "Invalid group by expressions, GroupingSet must be the only expression"
247            );
248        }
249        Ok(grouping_set.distinct_expr())
250    } else {
251        Ok(group_expr
252            .iter()
253            .collect::<IndexSet<_>>()
254            .into_iter()
255            .collect())
256    }
257}
258
259/// Recursively walk an expression tree, collecting the unique set of columns
260/// referenced in the expression
261pub fn expr_to_columns(expr: &Expr, accum: &mut HashSet<Column>) -> Result<()> {
262    expr.apply(|expr| {
263        match expr {
264            Expr::Column(qc) => {
265                accum.insert(qc.clone());
266            }
267            // Use explicit pattern match instead of a default
268            // implementation, so that in the future if someone adds
269            // new Expr types, they will check here as well
270            // TODO: remove the next line after `Expr::Wildcard` is removed
271            #[expect(deprecated)]
272            Expr::Unnest(_)
273            | Expr::ScalarVariable(_, _)
274            | Expr::Alias(_)
275            | Expr::Literal(_, _)
276            | Expr::BinaryExpr { .. }
277            | Expr::Like { .. }
278            | Expr::SimilarTo { .. }
279            | Expr::Not(_)
280            | Expr::IsNotNull(_)
281            | Expr::IsNull(_)
282            | Expr::IsTrue(_)
283            | Expr::IsFalse(_)
284            | Expr::IsUnknown(_)
285            | Expr::IsNotTrue(_)
286            | Expr::IsNotFalse(_)
287            | Expr::IsNotUnknown(_)
288            | Expr::Negative(_)
289            | Expr::Between { .. }
290            | Expr::Case { .. }
291            | Expr::Cast { .. }
292            | Expr::TryCast { .. }
293            | Expr::ScalarFunction(..)
294            | Expr::WindowFunction { .. }
295            | Expr::AggregateFunction { .. }
296            | Expr::GroupingSet(_)
297            | Expr::InList { .. }
298            | Expr::Exists { .. }
299            | Expr::InSubquery(_)
300            | Expr::SetComparison(_)
301            | Expr::ScalarSubquery(_)
302            | Expr::Wildcard { .. }
303            | Expr::Placeholder(_)
304            | Expr::OuterReferenceColumn { .. }
305            | Expr::HigherOrderFunction(_)
306            | Expr::Lambda(_)
307            | Expr::LambdaVariable(_) => {}
308        }
309        Ok(TreeNodeRecursion::Continue)
310    })
311    .map(|_| ())
312}
313
314/// Find excluded columns in the schema, if any
315/// SELECT * EXCLUDE(col1, col2), would return `vec![col1, col2]`
316fn get_excluded_columns(
317    opt_exclude: Option<&ExcludeSelectItem>,
318    opt_except: Option<&ExceptSelectItem>,
319    schema: &DFSchema,
320    qualifier: Option<&TableReference>,
321) -> Result<Vec<Column>> {
322    let mut idents = vec![];
323    if let Some(excepts) = opt_except {
324        idents.push(&excepts.first_element);
325        idents.extend(&excepts.additional_elements);
326    }
327    // Declared outside the `if let` so `idents.extend(exclude_owned.iter())`
328    // below can borrow references that outlive the inner scope.
329    let exclude_owned: Vec<Ident>;
330    if let Some(exclude) = opt_exclude {
331        let object_name_to_ident = |name: &ObjectName| -> Result<Ident> {
332            if name.0.len() != 1 {
333                return plan_err!(
334                    "EXCLUDE with multi-part identifiers is not supported: {name}"
335                );
336            }
337            let part = &name.0[0];
338            let Some(ident) = part.as_ident() else {
339                return plan_err!(
340                    "EXCLUDE with non-identifier name part is not supported: {part}"
341                );
342            };
343            Ok(ident.clone())
344        };
345        exclude_owned = match exclude {
346            ExcludeSelectItem::Single(name) => vec![object_name_to_ident(name)?],
347            ExcludeSelectItem::Multiple(names) => names
348                .iter()
349                .map(object_name_to_ident)
350                .collect::<Result<Vec<_>>>()?,
351        };
352        idents.extend(exclude_owned.iter());
353    }
354    // Excluded columns should be unique
355    let n_elem = idents.len();
356    let unique_idents = idents.into_iter().collect::<HashSet<_>>();
357    // If HashSet size, and vector length are different, this means that some of the excluded columns
358    // are not unique. In this case return error.
359    if n_elem != unique_idents.len() {
360        return plan_err!("EXCLUDE or EXCEPT contains duplicate column names");
361    }
362
363    let mut result = Vec::with_capacity(unique_idents.len());
364    for ident in unique_idents.into_iter() {
365        let col_name = ident.value.as_str();
366        let (qualifier, field) = schema.qualified_field_with_name(qualifier, col_name)?;
367        result.push(Column::from((qualifier, field)));
368    }
369    Ok(result)
370}
371
372/// Returns all `Expr`s in the schema, except the `Column`s in the `columns_to_skip`
373fn get_exprs_except_skipped(
374    schema: &DFSchema,
375    columns_to_skip: &HashSet<Column>,
376) -> Vec<Expr> {
377    if columns_to_skip.is_empty() {
378        schema.iter().map(Expr::from).collect::<Vec<Expr>>()
379    } else {
380        schema
381            .columns()
382            .iter()
383            .filter_map(|c| {
384                if !columns_to_skip.contains(c) {
385                    Some(Expr::Column(c.clone()))
386                } else {
387                    None
388                }
389            })
390            .collect::<Vec<Expr>>()
391    }
392}
393
394/// When a JOIN has a USING clause, the join columns appear in the output
395/// schema once per side (for inner/outer joins) or once total (for semi/anti
396/// joins). An unqualified wildcard should include each USING column only once.
397/// This function returns the duplicate columns that should be excluded.
398fn exclude_using_columns(plan: &LogicalPlan) -> Result<HashSet<Column>> {
399    let output_columns: HashSet<_> = plan.schema().columns().iter().cloned().collect();
400    let mut excluded = HashSet::new();
401    for cols in plan.using_columns()? {
402        // `using_columns()` returns join columns from both sides regardless of
403        // the join type. For semi/anti joins, only one side's columns appear in
404        // the output schema. Filter to output columns so that columns from the
405        // non-output side don't participate in the deduplication process below
406        // and displace real output columns.
407        let mut cols: Vec<_> = cols
408            .into_iter()
409            .filter(|c| output_columns.contains(c))
410            .collect();
411
412        // Sort so we keep the same qualified column, regardless of HashSet
413        // iteration order.
414        cols.sort();
415
416        // Keep only one column per name from the columns set, adding any
417        // duplicates to the excluded set.
418        let mut seen_names = HashSet::new();
419        for col in cols {
420            if seen_names.contains(col.name.as_str()) {
421                excluded.insert(col); // exclude columns with already seen name
422            } else {
423                seen_names.insert(col.name.clone()); // mark column name as seen
424            }
425        }
426    }
427    Ok(excluded)
428}
429
430/// Resolves an `Expr::Wildcard` to a collection of `Expr::Column`'s.
431pub fn expand_wildcard(
432    schema: &DFSchema,
433    plan: &LogicalPlan,
434    wildcard_options: Option<&WildcardOptions>,
435) -> Result<Vec<Expr>> {
436    let mut columns_to_skip = exclude_using_columns(plan)?;
437    let excluded_columns = if let Some(WildcardOptions {
438        exclude: opt_exclude,
439        except: opt_except,
440        ..
441    }) = wildcard_options
442    {
443        get_excluded_columns(opt_exclude.as_ref(), opt_except.as_ref(), schema, None)?
444    } else {
445        vec![]
446    };
447    // Add each excluded `Column` to columns_to_skip
448    columns_to_skip.extend(excluded_columns);
449    Ok(get_exprs_except_skipped(schema, &columns_to_skip))
450}
451
452/// Resolves an `Expr::Wildcard` to a collection of qualified `Expr::Column`'s.
453pub fn expand_qualified_wildcard(
454    qualifier: &TableReference,
455    schema: &DFSchema,
456    wildcard_options: Option<&WildcardOptions>,
457) -> Result<Vec<Expr>> {
458    let qualified_indices = schema.fields_indices_with_qualified(qualifier);
459    let projected_func_dependencies = schema
460        .functional_dependencies()
461        .project_functional_dependencies(&qualified_indices, qualified_indices.len());
462    let fields_with_qualified = get_at_indices(schema.fields(), &qualified_indices)?;
463    if fields_with_qualified.is_empty() {
464        return plan_err!("Invalid qualifier {qualifier}");
465    }
466
467    let qualified_schema = Arc::new(Schema::new_with_metadata(
468        fields_with_qualified,
469        schema.metadata().clone(),
470    ));
471    let qualified_dfschema =
472        DFSchema::try_from_qualified_schema(qualifier.clone(), &qualified_schema)?
473            .with_functional_dependencies(projected_func_dependencies)?;
474    let excluded_columns = if let Some(WildcardOptions {
475        exclude: opt_exclude,
476        except: opt_except,
477        ..
478    }) = wildcard_options
479    {
480        get_excluded_columns(
481            opt_exclude.as_ref(),
482            opt_except.as_ref(),
483            schema,
484            Some(qualifier),
485        )?
486    } else {
487        vec![]
488    };
489    // Add each excluded `Column` to columns_to_skip
490    let mut columns_to_skip = HashSet::new();
491    columns_to_skip.extend(excluded_columns);
492    Ok(get_exprs_except_skipped(
493        &qualified_dfschema,
494        &columns_to_skip,
495    ))
496}
497
498/// (expr, "is the SortExpr for window (either comes from PARTITION BY or ORDER BY columns)")
499/// If bool is true SortExpr comes from `PARTITION BY` column, if false comes from `ORDER BY` column
500type WindowSortKey = Vec<(Sort, bool)>;
501
502/// Generate a sort key for a given window expr's partition_by and order_by expr
503pub fn generate_sort_key(
504    partition_by: &[Expr],
505    order_by: &[Sort],
506) -> Result<WindowSortKey> {
507    let normalized_order_by_keys = order_by
508        .iter()
509        .map(|e| {
510            let Sort { expr, .. } = e;
511            Sort::new(expr.clone(), true, false)
512        })
513        .collect::<Vec<_>>();
514
515    let num_keys = partition_by.len() + order_by.len();
516    let mut final_sort_keys = Vec::with_capacity(num_keys);
517    let mut is_partition_flag = Vec::with_capacity(num_keys);
518    for e in partition_by {
519        // By default, create sort key with ASC is true and NULLS LAST to be consistent with
520        // PostgreSQL's rule: https://www.postgresql.org/docs/current/queries-order.html
521        let e = e.clone().sort(true, false);
522        if let Some(pos) = normalized_order_by_keys.iter().position(|key| key.eq(&e)) {
523            let order_by_key = &order_by[pos];
524            if !final_sort_keys.contains(order_by_key) {
525                final_sort_keys.push(order_by_key.clone());
526                is_partition_flag.push(true);
527            }
528        } else if !final_sort_keys.contains(&e) {
529            final_sort_keys.push(e);
530            is_partition_flag.push(true);
531        }
532    }
533
534    for e in order_by {
535        if !final_sort_keys.contains(e) {
536            final_sort_keys.push(e.clone());
537            is_partition_flag.push(false);
538        }
539    }
540    let res = final_sort_keys
541        .into_iter()
542        .zip(is_partition_flag)
543        .collect::<Vec<_>>();
544    Ok(res)
545}
546
547/// Compare the sort expr as PostgreSQL's common_prefix_cmp():
548/// <https://github.com/postgres/postgres/blob/master/src/backend/optimizer/plan/planner.c>
549pub fn compare_sort_expr(
550    sort_expr_a: &Sort,
551    sort_expr_b: &Sort,
552    schema: &DFSchemaRef,
553) -> Ordering {
554    let Sort {
555        expr: expr_a,
556        asc: asc_a,
557        nulls_first: nulls_first_a,
558    } = sort_expr_a;
559
560    let Sort {
561        expr: expr_b,
562        asc: asc_b,
563        nulls_first: nulls_first_b,
564    } = sort_expr_b;
565
566    let ref_indexes_a = find_column_indexes_referenced_by_expr(expr_a, schema);
567    let ref_indexes_b = find_column_indexes_referenced_by_expr(expr_b, schema);
568    for (idx_a, idx_b) in ref_indexes_a.iter().zip(ref_indexes_b.iter()) {
569        match idx_a.cmp(idx_b) {
570            Ordering::Less => {
571                return Ordering::Less;
572            }
573            Ordering::Greater => {
574                return Ordering::Greater;
575            }
576            Ordering::Equal => {}
577        }
578    }
579    match ref_indexes_a.len().cmp(&ref_indexes_b.len()) {
580        Ordering::Less => return Ordering::Greater,
581        Ordering::Greater => {
582            return Ordering::Less;
583        }
584        Ordering::Equal => {}
585    }
586    match (asc_a, asc_b) {
587        (true, false) => {
588            return Ordering::Greater;
589        }
590        (false, true) => {
591            return Ordering::Less;
592        }
593        _ => {}
594    }
595    match (nulls_first_a, nulls_first_b) {
596        (true, false) => {
597            return Ordering::Less;
598        }
599        (false, true) => {
600            return Ordering::Greater;
601        }
602        _ => {}
603    }
604    Ordering::Equal
605}
606
607/// Group window expressions by their sort keys, preserving any outer alias.
608pub fn group_window_expr_by_sort_keys(
609    window_expr: impl IntoIterator<Item = Expr>,
610) -> Result<Vec<(WindowSortKey, Vec<Expr>)>> {
611    let mut result = vec![];
612
613    window_expr.into_iter().try_for_each(|expr| {
614        // Read the window's settings through one alias.
615        // Keep `expr` intact so its output name is preserved.
616        let inner = match &expr {
617            Expr::Alias(alias) => alias.expr.as_ref(),
618            _ => &expr,
619        };
620
621        let Expr::WindowFunction(window_fun) = inner else {
622            return internal_err!("Impossibly got non-window expr {expr:?}");
623        };
624
625        let WindowFunctionParams {
626            partition_by,
627            order_by,
628            ..
629        } = &window_fun.as_ref().params;
630
631        let sort_key = generate_sort_key(partition_by, order_by)?;
632
633        if let Some((_, values)) = result.iter_mut().find(
634            |group: &&mut (WindowSortKey, Vec<Expr>)| {
635                matches!(group, (key, _) if *key == sort_key)
636            },
637        ) {
638            values.push(expr);
639        } else {
640            result.push((sort_key, vec![expr]));
641        }
642
643        Ok(())
644    })?;
645
646    Ok(result)
647}
648
649/// Collect all deeply nested `Expr::AggregateFunction`.
650/// They are returned in order of occurrence (depth
651/// first), with duplicates omitted.
652pub fn find_aggregate_exprs<'a>(exprs: impl IntoIterator<Item = &'a Expr>) -> Vec<Expr> {
653    find_exprs_in_exprs(exprs, &|nested_expr| {
654        matches!(nested_expr, Expr::AggregateFunction { .. })
655    })
656}
657
658/// Returns an error if any of `exprs` nests aggregate or window function calls
659/// in a way that has no physical equivalent: an aggregate call may not contain
660/// another aggregate call (`sum(sum(x))`) or a window call
661/// (`sum(sum(x) OVER ())`), and a window call may not contain another window
662/// call (`sum(sum(x) OVER ()) OVER ()`). The reverse nesting, an aggregate used
663/// as the argument of a window call (`sum(sum(x)) OVER ()`), is legal: there the
664/// aggregate is evaluated by the `Aggregate` node and the window function is
665/// evaluated on top of its result.
666///
667/// Such expressions are not valid SQL either, so they are rejected while the
668/// logical plan is built rather than failing later with an error that does not
669/// point back at the original SQL.
670///
671/// [`Aggregate::try_new`] and [`Window::try_new`] call this, so the SQL planner
672/// and the `DataFrame`/`LogicalPlanBuilder` paths are checked without callers
673/// invoking it directly. The lower-level `try_new_with_schema` constructors and
674/// building a `Window` from its public fields bypass the check, so a caller
675/// that constructs those nodes by hand should call this itself.
676///
677/// [`Aggregate::try_new`]: crate::logical_plan::Aggregate::try_new
678/// [`Window::try_new`]: crate::logical_plan::Window::try_new
679pub(crate) fn check_aggregate_and_window_nesting<'a>(
680    exprs: impl IntoIterator<Item = &'a Expr>,
681) -> Result<()> {
682    for expr in exprs {
683        expr.apply(|outer| {
684            if !matches!(outer, Expr::AggregateFunction(_) | Expr::WindowFunction(_)) {
685                return Ok(TreeNodeRecursion::Continue);
686            }
687
688            // Look for an illegally nested call in the arguments, `FILTER`,
689            // `ORDER BY` and `PARTITION BY` of this call
690            let mut err = None;
691            outer.apply_children(|child| {
692                child.apply(|inner| {
693                    err = illegal_nesting_err(outer, inner);
694                    if err.is_some() {
695                        Ok(TreeNodeRecursion::Stop)
696                    } else {
697                        Ok(TreeNodeRecursion::Continue)
698                    }
699                })
700            })?;
701
702            match err {
703                Some(err) => Err(err),
704                None => Ok(TreeNodeRecursion::Continue),
705            }
706        })?;
707    }
708    Ok(())
709}
710
711/// The planning error for a call to `inner` nested inside a call to `outer`, or
712/// `None` if that nesting is legal.
713fn illegal_nesting_err(outer: &Expr, inner: &Expr) -> Option<DataFusionError> {
714    // Messages follow PostgreSQL, which rejects the same three cases
715    let (message, help) = match (outer, inner) {
716        (Expr::AggregateFunction(_), Expr::AggregateFunction(_)) => (
717            "Aggregate function calls cannot be nested",
718            format!("Compute '{inner}' in an inner query and aggregate its result"),
719        ),
720        (Expr::AggregateFunction(_), Expr::WindowFunction(_)) => (
721            "Aggregate function calls cannot contain window function calls",
722            format!("Compute '{inner}' in an inner query and aggregate its result"),
723        ),
724        (Expr::WindowFunction(_), Expr::WindowFunction(_)) => (
725            "Window function calls cannot be nested",
726            format!("Compute '{inner}' in an inner query and use its result here"),
727        ),
728        // Anything else, including an aggregate inside a window call
729        _ => return None,
730    };
731
732    Some(
733        plan_datafusion_err!("{message}: '{inner}' is nested inside '{outer}'")
734            .with_diagnostic(
735                Diagnostic::new_error(message, first_span(inner)).with_help(help, None),
736            ),
737    )
738}
739
740/// Best effort source location for `expr`: the first [`Span`] found in its
741/// subtree. Only some expressions (currently columns) carry spans, so pointing
742/// at e.g. the column of `sum(x)` is the closest we can get to the location of
743/// the whole expression.
744fn first_span(expr: &Expr) -> Option<Span> {
745    let mut span = None;
746    expr.apply(|e| {
747        span = e.spans().and_then(|spans| spans.first());
748        if span.is_some() {
749            Ok(TreeNodeRecursion::Stop)
750        } else {
751            Ok(TreeNodeRecursion::Continue)
752        }
753    })
754    .ok()?;
755    span
756}
757
758/// Returns an error if `expr` contains a window function call.
759///
760/// `clause` names where `expr` came from and completes the message
761/// `Window function calls are not allowed in {clause}`, for example `WHERE` or
762/// `HAVING`. Filters are evaluated before window functions are computed, so a
763/// window call in a filter predicate has no physical equivalent and is not
764/// valid SQL either (PostgreSQL: `window functions are not allowed in HAVING`).
765/// Rejecting it while the logical plan is built gives an error that names the
766/// offending call instead of a late physical planning failure.
767///
768/// [`Filter::try_new`] calls this for every predicate, so the SQL planner and
769/// the `DataFrame`/`LogicalPlanBuilder` paths are covered without callers
770/// invoking it directly. Window calls inside subqueries of `expr` are not
771/// visited and are legal.
772///
773/// The error is built by [`window_function_not_allowed_err`] with the best
774/// effort span of the call (see [`Expr::spans`]) and a generic help message. A
775/// caller that knows where the call is in the original query, such as the SQL
776/// planner, can build a more precise error with that function directly.
777///
778/// [`Filter::try_new`]: crate::logical_plan::Filter::try_new
779pub fn check_no_window_functions(expr: &Expr, clause: &str) -> Result<()> {
780    match first_window_function(expr) {
781        None => Ok(()),
782        Some(window) => Err(window_function_not_allowed_err(
783            window,
784            clause,
785            first_span(window),
786            format!(
787                "Compute '{window}' first, in a Window node or an inner query, and filter on its result"
788            ),
789        )),
790    }
791}
792
793/// The first window function call in `expr`, if any. Subqueries are not
794/// visited.
795fn first_window_function(expr: &Expr) -> Option<&Expr> {
796    let mut window = None;
797    expr.apply(|e| {
798        if matches!(e, Expr::WindowFunction(_)) {
799            window = Some(e);
800            Ok(TreeNodeRecursion::Stop)
801        } else {
802            Ok(TreeNodeRecursion::Continue)
803        }
804    })
805    .ok()?;
806    window
807}
808
809/// The planning error for `window`, a window function call that appeared in
810/// `clause` where it is not allowed (see [`check_no_window_functions`]).
811///
812/// The message is `Window function calls are not allowed in {clause}:
813/// '{window}'`. The error carries a [`Diagnostic`] with the same message,
814/// pointing at `span`, and with `help`.
815pub fn window_function_not_allowed_err(
816    window: &Expr,
817    clause: &str,
818    span: Option<Span>,
819    help: impl Into<String>,
820) -> DataFusionError {
821    let message = format!("Window function calls are not allowed in {clause}");
822    plan_datafusion_err!("{message}: '{window}'")
823        .with_diagnostic(Diagnostic::new_error(message, span).with_help(help, None))
824}
825
826/// Collect all deeply nested `Expr::WindowFunction`. They are returned in order of occurrence
827/// (depth first), with duplicates omitted.
828pub fn find_window_exprs<'a>(exprs: impl IntoIterator<Item = &'a Expr>) -> Vec<Expr> {
829    find_exprs_in_exprs(exprs, &|nested_expr| {
830        matches!(nested_expr, Expr::WindowFunction { .. })
831    })
832}
833
834/// Collect all deeply nested `Expr::OuterReferenceColumn`. They are returned in order of occurrence
835/// (depth first), with duplicates omitted.
836pub fn find_out_reference_exprs(expr: &Expr) -> Vec<Expr> {
837    find_exprs_in_expr(expr, &|nested_expr| {
838        matches!(nested_expr, Expr::OuterReferenceColumn { .. })
839    })
840}
841
842/// Search the provided `Expr`'s, and all of their nested `Expr`, for any that
843/// pass the provided test. The returned `Expr`'s are deduplicated and returned
844/// in order of appearance (depth first).
845fn find_exprs_in_exprs<'a, F>(
846    exprs: impl IntoIterator<Item = &'a Expr>,
847    test_fn: &F,
848) -> Vec<Expr>
849where
850    F: Fn(&Expr) -> bool,
851{
852    let mut found = IndexSet::new();
853    for expr in exprs {
854        collect_exprs_in_expr(expr, test_fn, &mut found);
855    }
856    found.into_iter().collect()
857}
858
859/// Search an `Expr`, and all of its nested `Expr`'s, for any that pass the
860/// provided test. The returned `Expr`'s are deduplicated and returned in order
861/// of appearance (depth first).
862fn find_exprs_in_expr<F>(expr: &Expr, test_fn: &F) -> Vec<Expr>
863where
864    F: Fn(&Expr) -> bool,
865{
866    find_exprs_in_exprs(std::iter::once(expr), test_fn)
867}
868
869fn collect_exprs_in_expr<F>(expr: &Expr, test_fn: &F, found: &mut IndexSet<Expr>)
870where
871    F: Fn(&Expr) -> bool,
872{
873    expr.apply(|expr| {
874        if test_fn(expr) {
875            if !found.contains(expr) {
876                found.insert(expr.clone());
877            }
878            // Stop recursing down this expr once we find a match
879            return Ok(TreeNodeRecursion::Jump);
880        }
881
882        Ok(TreeNodeRecursion::Continue)
883    })
884    // pre_visit always returns OK, so this will always too
885    .expect("no way to return error during recursion");
886}
887
888/// Recursively inspect an [`Expr`] and all its children.
889pub fn inspect_expr_pre<F, E>(expr: &Expr, mut f: F) -> Result<(), E>
890where
891    F: FnMut(&Expr) -> Result<(), E>,
892{
893    let mut err = Ok(());
894    expr.apply(|expr| {
895        if let Err(e) = f(expr) {
896            // Save the error for later (it may not be a DataFusionError)
897            err = Err(e);
898            Ok(TreeNodeRecursion::Stop)
899        } else {
900            // keep going
901            Ok(TreeNodeRecursion::Continue)
902        }
903    })
904    // The closure always returns OK, so this will always too
905    .expect("no way to return error during recursion");
906
907    err
908}
909
910/// Returns the element field at the given list unnesting depth.
911pub(crate) fn get_unnested_list_field(
912    data_type: &DataType,
913    depth: usize,
914) -> Result<&Field> {
915    match data_type {
916        DataType::List(field)
917        | DataType::FixedSizeList(field, _)
918        | DataType::LargeList(field)
919        | DataType::ListView(field)
920        | DataType::LargeListView(field) => {
921            if depth == 1 {
922                return Ok(field.as_ref());
923            }
924            return get_unnested_list_field(field.data_type(), depth - 1);
925        }
926        _ => {}
927    }
928
929    internal_err!("trying to unnest on invalid data type {data_type}")
930}
931
932/// Create schema fields from an expression list, for use in result set schema construction
933///
934/// This function converts a list of expressions into a list of complete schema fields,
935/// making comprehensive determinations about each field's properties including:
936/// - **Data type**: Resolved based on expression type and input schema context
937/// - **Nullability**: Determined by expression-specific nullability rules
938/// - **Metadata**: Computed based on expression type (preserving, merging, or generating new metadata)
939/// - **Table reference scoping**: Establishing proper qualified field references
940///
941/// Each expression is converted to a field by calling [`Expr::to_field`], which performs
942/// the complete field resolution process for all field properties.
943///
944/// # Returns
945///
946/// A `Result` containing a vector of `(Option<TableReference>, Arc<Field>)` tuples,
947/// where each Field contains complete schema information (type, nullability, metadata)
948/// and proper table reference scoping for the corresponding expression.
949pub fn exprlist_to_fields<'a>(
950    exprs: impl IntoIterator<Item = &'a Expr>,
951    plan: &LogicalPlan,
952) -> Result<Vec<(Option<TableReference>, Arc<Field>)>> {
953    // Look for exact match in plan's output schema
954    let input_schema = plan.schema();
955    exprs
956        .into_iter()
957        .map(|e| e.to_field(input_schema))
958        .collect()
959}
960
961/// Convert an expression into Column expression if it's already provided as input plan.
962///
963/// For example, it rewrites:
964///
965/// ```text
966/// .aggregate(vec![col("c1")], vec![sum(col("c2"))])?
967/// .project(vec![col("c1"), sum(col("c2"))?
968/// ```
969///
970/// Into:
971///
972/// ```text
973/// .aggregate(vec![col("c1")], vec![sum(col("c2"))])?
974/// .project(vec![col("c1"), col("SUM(c2)")?
975/// ```
976pub fn columnize_expr(e: Expr, input: &LogicalPlan) -> Result<Expr> {
977    Columnizer::new(input).columnize(e)
978}
979
980/// Applies [`columnize_expr`] to many expressions over the same input plan,
981/// building the lookup of the input's output expressions only once.
982pub(crate) struct Columnizer<'a> {
983    output_exprs: HashMap<&'a Expr, Column>,
984}
985
986impl<'a> Columnizer<'a> {
987    pub(crate) fn new(input: &'a LogicalPlan) -> Self {
988        let output_exprs = input
989            .columnized_output_exprs()
990            .map(|exprs| exprs.into_iter().collect())
991            .unwrap_or_default();
992        Self { output_exprs }
993    }
994
995    pub(crate) fn columnize(&self, e: Expr) -> Result<Expr> {
996        if self.output_exprs.is_empty() {
997            return Ok(e);
998        }
999        e.transform_down(|node: Expr| match self.output_exprs.get(&node) {
1000            Some(column) => Ok(Transformed::new(
1001                Expr::Column(column.clone()),
1002                true,
1003                TreeNodeRecursion::Jump,
1004            )),
1005            None => Ok(Transformed::no(node)),
1006        })
1007        .data()
1008    }
1009}
1010
1011/// Collect all deeply nested `Expr::Column`'s. They are returned in order of
1012/// appearance (depth first), and may contain duplicates.
1013pub fn find_column_exprs(exprs: &[Expr]) -> Vec<Expr> {
1014    exprs
1015        .iter()
1016        .flat_map(find_columns_referenced_by_expr)
1017        .map(Expr::Column)
1018        .collect()
1019}
1020
1021pub(crate) fn find_columns_referenced_by_expr(e: &Expr) -> Vec<Column> {
1022    let mut exprs = vec![];
1023    e.apply(|expr| {
1024        if let Expr::Column(c) = expr {
1025            exprs.push(c.clone())
1026        }
1027        Ok(TreeNodeRecursion::Continue)
1028    })
1029    // As the closure always returns Ok, this "can't" error
1030    .expect("Unexpected error");
1031    exprs
1032}
1033
1034/// Returns the index of the `schema` field that `expr` passes through
1035/// unchanged, or `None` if `expr` computes a new value.
1036///
1037/// Only a column reference (possibly aliased) passes a field through. Use this
1038/// instead of comparing [`Expr::schema_name`] with field names: different
1039/// expressions can have the same name, e.g. `CAST(t.a AS INT)` is named `t.a`.
1040///
1041/// A column is resolved like any other column reference, so an ambiguous
1042/// unqualified name (e.g. `id` over `a.id` and `b.id`) passes nothing through.
1043pub fn passthrough_field_index(expr: &Expr, schema: &DFSchema) -> Option<usize> {
1044    match expr {
1045        Expr::Column(col) => {
1046            let (_, field) = schema.qualified_field_from_column(col).ok()?;
1047            schema.fields().iter().position(|f| std::ptr::eq(f, field))
1048        }
1049        Expr::Alias(alias) => passthrough_field_index(&alias.expr, schema),
1050        _ => None,
1051    }
1052}
1053
1054/// Convert any `Expr` to an `Expr::Column`.
1055pub fn expr_as_column_expr(expr: &Expr, plan: &LogicalPlan) -> Result<Expr> {
1056    match expr {
1057        Expr::Column(col) => {
1058            let (qualifier, field) = plan.schema().qualified_field_from_column(col)?;
1059            Ok(Expr::from(Column::from((qualifier, field))))
1060        }
1061        _ => Ok(Expr::Column(Column::from_name(
1062            expr.schema_name().to_string(),
1063        ))),
1064    }
1065}
1066
1067/// Recursively walk an expression tree, collecting the column indexes
1068/// referenced in the expression
1069pub(crate) fn find_column_indexes_referenced_by_expr(
1070    e: &Expr,
1071    schema: &DFSchemaRef,
1072) -> Vec<usize> {
1073    let mut indexes = vec![];
1074    e.apply(|expr| {
1075        match expr {
1076            Expr::Column(qc) => {
1077                if let Ok(idx) = schema.index_of_column(qc) {
1078                    indexes.push(idx);
1079                }
1080            }
1081            Expr::Literal(_, _) => {
1082                indexes.push(usize::MAX);
1083            }
1084            _ => {}
1085        }
1086        Ok(TreeNodeRecursion::Continue)
1087    })
1088    .unwrap();
1089    indexes
1090}
1091
1092/// Can this data type be used in hash join equal conditions??
1093/// Data types here come from function 'equal_rows', if more data types are supported
1094/// in create_hashes, add those data types here to generate join logical plan.
1095pub fn can_hash(data_type: &DataType) -> bool {
1096    match data_type {
1097        DataType::Null => true,
1098        DataType::Boolean => true,
1099        DataType::Int8 => true,
1100        DataType::Int16 => true,
1101        DataType::Int32 => true,
1102        DataType::Int64 => true,
1103        DataType::UInt8 => true,
1104        DataType::UInt16 => true,
1105        DataType::UInt32 => true,
1106        DataType::UInt64 => true,
1107        DataType::Float16 => true,
1108        DataType::Float32 => true,
1109        DataType::Float64 => true,
1110        DataType::Decimal32(_, _) => true,
1111        DataType::Decimal64(_, _) => true,
1112        DataType::Decimal128(_, _) => true,
1113        DataType::Decimal256(_, _) => true,
1114        DataType::Timestamp(_, _) => true,
1115        DataType::Utf8 => true,
1116        DataType::LargeUtf8 => true,
1117        DataType::Utf8View => true,
1118        DataType::Binary => true,
1119        DataType::LargeBinary => true,
1120        DataType::BinaryView => true,
1121        DataType::Date32 => true,
1122        DataType::Date64 => true,
1123        DataType::Time32(_) => true,
1124        DataType::Time64(_) => true,
1125        DataType::Duration(_) => true,
1126        DataType::Interval(_) => true,
1127        DataType::FixedSizeBinary(_) => true,
1128        DataType::Dictionary(key_type, value_type) => {
1129            DataType::is_dictionary_key_type(key_type) && can_hash(value_type)
1130        }
1131        DataType::List(value_type) => can_hash(value_type.data_type()),
1132        DataType::LargeList(value_type) => can_hash(value_type.data_type()),
1133        DataType::FixedSizeList(value_type, _) => can_hash(value_type.data_type()),
1134        DataType::Map(map_struct, true | false) => can_hash(map_struct.data_type()),
1135        DataType::Struct(fields) => fields.iter().all(|f| can_hash(f.data_type())),
1136
1137        DataType::ListView(_)
1138        | DataType::LargeListView(_)
1139        | DataType::Union(_, _)
1140        | DataType::RunEndEncoded(_, _) => false,
1141    }
1142}
1143
1144/// Check whether all columns are from the schema.
1145pub fn check_all_columns_from_schema(
1146    columns: &HashSet<&Column>,
1147    schema: &DFSchema,
1148) -> Result<bool> {
1149    for col in columns.iter() {
1150        let exist = schema.is_column_from_schema(col);
1151        if !exist {
1152            return Ok(false);
1153        }
1154    }
1155
1156    Ok(true)
1157}
1158
1159/// Give two sides of the equijoin predicate, return a valid join key pair.
1160/// If there is no valid join key pair, return None.
1161///
1162/// A valid join means:
1163/// 1. All referenced column of the left side is from the left schema, and
1164///    all referenced column of the right side is from the right schema.
1165/// 2. Or opposite. All referenced column of the left side is from the right schema,
1166///    and the right side is from the left schema.
1167pub fn find_valid_equijoin_key_pair(
1168    left_key: &Expr,
1169    right_key: &Expr,
1170    left_schema: &DFSchema,
1171    right_schema: &DFSchema,
1172) -> Result<Option<(Expr, Expr)>> {
1173    let left_using_columns = left_key.column_refs();
1174    let right_using_columns = right_key.column_refs();
1175
1176    // Conditions like a = 10, will be added to non-equijoin.
1177    if left_using_columns.is_empty() || right_using_columns.is_empty() {
1178        return Ok(None);
1179    }
1180
1181    // Returns whether all `left_columns` are from `left_schema` and all
1182    // `right_columns` are from `right_schema`. Looking up a column scans the
1183    // schema, so check the narrower schema first: a key that does not belong
1184    // to the join inputs is then usually rejected without scanning the wider
1185    // one, such as the accumulated left input of a left-deep join tree.
1186    let left_is_narrower = left_schema.fields().len() <= right_schema.fields().len();
1187    let check = |left_columns: &HashSet<&Column>,
1188                 right_columns: &HashSet<&Column>|
1189     -> Result<bool> {
1190        let left = (left_columns, left_schema);
1191        let right = (right_columns, right_schema);
1192        let (first, second) = if left_is_narrower {
1193            (left, right)
1194        } else {
1195            (right, left)
1196        };
1197        Ok(check_all_columns_from_schema(first.0, first.1)?
1198            && check_all_columns_from_schema(second.0, second.1)?)
1199    };
1200
1201    if check(&left_using_columns, &right_using_columns)? {
1202        return Ok(Some((left_key.clone(), right_key.clone())));
1203    } else if check(&right_using_columns, &left_using_columns)? {
1204        return Ok(Some((right_key.clone(), left_key.clone())));
1205    }
1206
1207    Ok(None)
1208}
1209
1210/// Creates a detailed error message for a function with wrong signature.
1211///
1212/// For example, a query like `select round(3.14, 1.1);` would yield:
1213/// ```text
1214/// Error during planning: No function matches 'round(Float64, Float64)'. You might need to add explicit type casts.
1215///     Candidate functions:
1216///     round(Float64, Int64)
1217///     round(Float32, Int64)
1218///     round(Float64)
1219///     round(Float32)
1220/// ```
1221#[expect(clippy::needless_pass_by_value)]
1222#[deprecated(since = "53.0.0", note = "Internal function")]
1223pub fn generate_signature_error_msg(
1224    func_name: &str,
1225    func_signature: Signature,
1226    input_expr_types: &[DataType],
1227) -> String {
1228    let candidate_signatures = func_signature
1229        .type_signature
1230        .to_string_repr_with_names(func_signature.parameter_names.as_deref())
1231        .iter()
1232        .map(|args_str| format!("\t{func_name}({args_str})"))
1233        .collect::<Vec<String>>()
1234        .join("\n");
1235
1236    format!(
1237        "No function matches the given name and argument types '{}({})'. You might need to add explicit type casts.\n\tCandidate functions:\n{}",
1238        func_name,
1239        TypeSignature::join_types(input_expr_types, ", "),
1240        candidate_signatures
1241    )
1242}
1243
1244/// Creates a detailed error message for a function with wrong signature.
1245///
1246/// For example, a query like `select round(3.14, 1.1);` would yield:
1247/// ```text
1248/// Error during planning: No function matches 'round(Float64, Float64)'. You might need to add explicit type casts.
1249///     Candidate functions:
1250///     round(Float64, Int64)
1251///     round(Float32, Int64)
1252///     round(Float64)
1253///     round(Float32)
1254/// ```
1255pub(crate) fn generate_signature_error_message(
1256    func_name: &str,
1257    func_signature: &Signature,
1258    input_expr_types: &[DataType],
1259) -> String {
1260    #[expect(deprecated)]
1261    generate_signature_error_msg(func_name, func_signature.clone(), input_expr_types)
1262}
1263
1264/// Splits a conjunctive [`Expr`] such as `A AND B AND C` => `[A, B, C]`
1265///
1266/// See [`split_conjunction_owned`] for more details and an example.
1267pub fn split_conjunction(expr: &Expr) -> Vec<&Expr> {
1268    split_conjunction_impl(expr, vec![])
1269}
1270
1271fn split_conjunction_impl<'a>(expr: &'a Expr, mut exprs: Vec<&'a Expr>) -> Vec<&'a Expr> {
1272    match expr {
1273        Expr::BinaryExpr(BinaryExpr {
1274            right,
1275            op: Operator::And,
1276            left,
1277        }) => {
1278            let exprs = split_conjunction_impl(left, exprs);
1279            split_conjunction_impl(right, exprs)
1280        }
1281        Expr::Alias(Alias { expr, .. }) => split_conjunction_impl(expr, exprs),
1282        other => {
1283            exprs.push(other);
1284            exprs
1285        }
1286    }
1287}
1288
1289/// Iterate parts in a conjunctive [`Expr`] such as `A AND B AND C` => `[A, B, C]`
1290///
1291/// See [`split_conjunction_owned`] for more details and an example.
1292pub fn iter_conjunction(expr: &Expr) -> impl Iterator<Item = &Expr> {
1293    let mut stack = vec![expr];
1294    std::iter::from_fn(move || {
1295        while let Some(expr) = stack.pop() {
1296            match expr {
1297                Expr::BinaryExpr(BinaryExpr {
1298                    right,
1299                    op: Operator::And,
1300                    left,
1301                }) => {
1302                    stack.push(right);
1303                    stack.push(left);
1304                }
1305                Expr::Alias(Alias { expr, .. }) => stack.push(expr),
1306                other => return Some(other),
1307            }
1308        }
1309        None
1310    })
1311}
1312
1313/// Iterate parts in a conjunctive [`Expr`] such as `A AND B AND C` => `[A, B, C]`
1314///
1315/// See [`split_conjunction_owned`] for more details and an example.
1316pub fn iter_conjunction_owned(expr: Expr) -> impl Iterator<Item = Expr> {
1317    let mut stack = vec![expr];
1318    std::iter::from_fn(move || {
1319        while let Some(expr) = stack.pop() {
1320            match expr {
1321                Expr::BinaryExpr(BinaryExpr {
1322                    right,
1323                    op: Operator::And,
1324                    left,
1325                }) => {
1326                    stack.push(*right);
1327                    stack.push(*left);
1328                }
1329                Expr::Alias(Alias { expr, .. }) => stack.push(*expr),
1330                other => return Some(other),
1331            }
1332        }
1333        None
1334    })
1335}
1336
1337/// Splits an owned conjunctive [`Expr`] such as `A AND B AND C` => `[A, B, C]`
1338///
1339/// This is often used to "split" filter expressions such as `col1 = 5
1340/// AND col2 = 10` into [`col1 = 5`, `col2 = 10`];
1341///
1342/// # Example
1343/// ```
1344/// # use datafusion_expr::{col, lit};
1345/// # use datafusion_expr::utils::split_conjunction_owned;
1346/// // a=1 AND b=2
1347/// let expr = col("a").eq(lit(1)).and(col("b").eq(lit(2)));
1348///
1349/// // [a=1, b=2]
1350/// let split = vec![col("a").eq(lit(1)), col("b").eq(lit(2))];
1351///
1352/// // use split_conjunction_owned to split them
1353/// assert_eq!(split_conjunction_owned(expr), split);
1354/// ```
1355pub fn split_conjunction_owned(expr: Expr) -> Vec<Expr> {
1356    split_binary_owned(expr, Operator::And)
1357}
1358
1359/// Splits an owned binary operator tree [`Expr`] such as `A <OP> B <OP> C` => `[A, B, C]`
1360///
1361/// This is often used to "split" expressions such as `col1 = 5
1362/// AND col2 = 10` into [`col1 = 5`, `col2 = 10`];
1363///
1364/// # Example
1365/// ```
1366/// # use datafusion_expr::{col, lit, Operator};
1367/// # use datafusion_expr::utils::split_binary_owned;
1368/// # use std::ops::Add;
1369/// // a=1 + b=2
1370/// let expr = col("a").eq(lit(1)).add(col("b").eq(lit(2)));
1371///
1372/// // [a=1, b=2]
1373/// let split = vec![col("a").eq(lit(1)), col("b").eq(lit(2))];
1374///
1375/// // use split_binary_owned to split them
1376/// assert_eq!(split_binary_owned(expr, Operator::Plus), split);
1377/// ```
1378pub fn split_binary_owned(expr: Expr, op: Operator) -> Vec<Expr> {
1379    split_binary_owned_impl(expr, op, vec![])
1380}
1381
1382fn split_binary_owned_impl(
1383    expr: Expr,
1384    operator: Operator,
1385    mut exprs: Vec<Expr>,
1386) -> Vec<Expr> {
1387    match expr {
1388        Expr::BinaryExpr(BinaryExpr { right, op, left }) if op == operator => {
1389            let exprs = split_binary_owned_impl(*left, operator, exprs);
1390            split_binary_owned_impl(*right, operator, exprs)
1391        }
1392        Expr::Alias(Alias { expr, .. }) => {
1393            split_binary_owned_impl(*expr, operator, exprs)
1394        }
1395        other => {
1396            exprs.push(other);
1397            exprs
1398        }
1399    }
1400}
1401
1402/// Splits an binary operator tree [`Expr`] such as `A <OP> B <OP> C` => `[A, B, C]`
1403///
1404/// See [`split_binary_owned`] for more details and an example.
1405pub fn split_binary(expr: &Expr, op: Operator) -> Vec<&Expr> {
1406    split_binary_impl(expr, op, vec![])
1407}
1408
1409fn split_binary_impl<'a>(
1410    expr: &'a Expr,
1411    operator: Operator,
1412    mut exprs: Vec<&'a Expr>,
1413) -> Vec<&'a Expr> {
1414    match expr {
1415        Expr::BinaryExpr(BinaryExpr { right, op, left }) if *op == operator => {
1416            let exprs = split_binary_impl(left, operator, exprs);
1417            split_binary_impl(right, operator, exprs)
1418        }
1419        Expr::Alias(Alias { expr, .. }) => split_binary_impl(expr, operator, exprs),
1420        other => {
1421            exprs.push(other);
1422            exprs
1423        }
1424    }
1425}
1426
1427/// Combines an array of filter expressions into a single filter
1428/// expression consisting of the input filter expressions joined with
1429/// logical AND.
1430///
1431/// Returns None if the filters array is empty.
1432///
1433/// # Example
1434/// ```
1435/// # use datafusion_expr::{col, lit};
1436/// # use datafusion_expr::utils::conjunction;
1437/// // a=1 AND b=2
1438/// let expr = col("a").eq(lit(1)).and(col("b").eq(lit(2)));
1439///
1440/// // [a=1, b=2]
1441/// let split = vec![col("a").eq(lit(1)), col("b").eq(lit(2))];
1442///
1443/// // use conjunction to join them together with `AND`
1444/// assert_eq!(conjunction(split), Some(expr));
1445/// ```
1446pub fn conjunction(filters: impl IntoIterator<Item = Expr>) -> Option<Expr> {
1447    filters.into_iter().reduce(Expr::and)
1448}
1449
1450/// Combines an array of filter expressions into a single filter
1451/// expression consisting of the input filter expressions joined with
1452/// logical OR.
1453///
1454/// Returns None if the filters array is empty.
1455///
1456/// # Example
1457/// ```
1458/// # use datafusion_expr::{col, lit};
1459/// # use datafusion_expr::utils::disjunction;
1460/// // a=1 OR b=2
1461/// let expr = col("a").eq(lit(1)).or(col("b").eq(lit(2)));
1462///
1463/// // [a=1, b=2]
1464/// let split = vec![col("a").eq(lit(1)), col("b").eq(lit(2))];
1465///
1466/// // use disjunction to join them together with `OR`
1467/// assert_eq!(disjunction(split), Some(expr));
1468/// ```
1469pub fn disjunction(filters: impl IntoIterator<Item = Expr>) -> Option<Expr> {
1470    filters.into_iter().reduce(Expr::or)
1471}
1472
1473/// Returns a new [LogicalPlan] that filters the output of  `plan` with a
1474/// [LogicalPlan::Filter] with all `predicates` ANDed.
1475///
1476/// # Example
1477/// Before:
1478/// ```text
1479/// plan
1480/// ```
1481///
1482/// After:
1483/// ```text
1484/// Filter(predicate)
1485///   plan
1486/// ```
1487pub fn add_filter(plan: LogicalPlan, predicates: &[&Expr]) -> Result<LogicalPlan> {
1488    // reduce filters to a single filter with an AND
1489    let predicate = predicates
1490        .iter()
1491        .skip(1)
1492        .fold(predicates[0].clone(), |acc, predicate| {
1493            and(acc, (*predicate).to_owned())
1494        });
1495
1496    Ok(LogicalPlan::Filter(Filter::try_new(
1497        predicate,
1498        Arc::new(plan),
1499    )?))
1500}
1501
1502/// Looks for correlating expressions: for example, a binary expression with one field from the subquery, and
1503/// one not in the subquery (closed upon from outer scope)
1504///
1505/// # Arguments
1506///
1507/// * `exprs` - List of expressions that may or may not be joins
1508///
1509/// # Return value
1510///
1511/// Tuple of (expressions containing joins, remaining non-join expressions)
1512#[deprecated(
1513    since = "56.0.0",
1514    note = "This decorrelation helper is intended for internal optimizer use and has no public replacement"
1515)]
1516pub fn find_join_exprs(exprs: Vec<&Expr>) -> Result<(Vec<Expr>, Vec<Expr>)> {
1517    let mut joins = vec![];
1518    let mut others = vec![];
1519    for filter in exprs.into_iter() {
1520        // If the expression contains correlated predicates, add it to join filters
1521        if filter.contains_outer() {
1522            if !matches!(filter, Expr::BinaryExpr(BinaryExpr{ left, op: Operator::Eq, right }) if left.eq(right))
1523            {
1524                joins.push(strip_outer_reference((*filter).clone()));
1525            }
1526        } else {
1527            others.push((*filter).clone());
1528        }
1529    }
1530
1531    Ok((joins, others))
1532}
1533
1534/// Returns the first (and only) element in a slice, or an error
1535///
1536/// # Arguments
1537///
1538/// * `slice` - The slice to extract from
1539///
1540/// # Return value
1541///
1542/// The first element, or an error
1543pub fn only_or_err<T>(slice: &[T]) -> Result<&T> {
1544    match slice {
1545        [it] => Ok(it),
1546        [] => plan_err!("No items found!"),
1547        _ => plan_err!("More than one item found!"),
1548    }
1549}
1550
1551/// merge inputs schema into a single schema.
1552///
1553/// This function merges schemas from multiple logical plan inputs using [`DFSchema::merge`].
1554/// Refer to that documentation for details on precedence and metadata handling.
1555pub fn merge_schema(inputs: &[&LogicalPlan]) -> DFSchema {
1556    if inputs.len() == 1 {
1557        inputs[0].schema().as_ref().clone()
1558    } else {
1559        inputs.iter().map(|input| input.schema()).fold(
1560            DFSchema::empty(),
1561            |mut lhs, rhs| {
1562                lhs.merge(rhs);
1563                lhs
1564            },
1565        )
1566    }
1567}
1568
1569/// Build state name. State is the intermediate state of the aggregate function.
1570pub fn format_state_name(name: &str, state_name: &str) -> String {
1571    format!("{name}[{state_name}]")
1572}
1573
1574/// Creates aggregate state fields for ordering expressions with unique names.
1575///
1576/// Each field is renamed using the aggregate name and its ordering position.
1577pub fn ordering_state_fields(
1578    name: &str,
1579    ordering_fields: &[FieldRef],
1580) -> impl Iterator<Item = FieldRef> {
1581    ordering_fields.iter().enumerate().map(|(idx, field)| {
1582        Arc::new(
1583            field
1584                .as_ref()
1585                .clone()
1586                .with_name(format_state_name(name, &format!("ordering_{idx}"))),
1587        )
1588    })
1589}
1590
1591/// Determine the set of [`Column`]s produced by the subquery.
1592pub fn collect_subquery_cols(
1593    exprs: &[Expr],
1594    subquery_schema: &DFSchema,
1595) -> Result<BTreeSet<Column>> {
1596    exprs.iter().try_fold(BTreeSet::new(), |mut cols, expr| {
1597        for col in expr.column_refs().into_iter() {
1598            if subquery_schema.has_column(col) {
1599                cols.insert(col.clone());
1600            }
1601        }
1602
1603        Result::<_>::Ok(cols)
1604    })
1605}
1606
1607/// Determine the subquery-side expressions a join filter compares,
1608/// stopping at the first subquery-referencing sub-expression rather than
1609/// descending to the bare columns inside of it.
1610///
1611/// `t1.a = t2.b` yields `t2.b`, matching [`collect_subquery_cols`]. But
1612/// `t1.a = CAST(t2.b AS INT)` yields `CAST(t2.b AS INT)` whole, not `t2.b`.
1613/// The two differ whenever the correlated predicate wraps the subquery's
1614/// column in an expression, in which case we need to evaluate the full
1615/// expression before grouping, so that two column values which compare
1616/// equal after the wrapping expression end up in the same group.
1617pub fn collect_subquery_join_exprs(
1618    exprs: &[Expr],
1619    subquery_schema: &DFSchema,
1620) -> Result<Vec<Expr>> {
1621    let mut result: Vec<Expr> = vec![];
1622    for expr in exprs {
1623        expr.apply(|e| {
1624            if e.column_refs()
1625                .into_iter()
1626                .all(|col| subquery_schema.has_column(col))
1627                && !e.column_refs().is_empty()
1628                && !result.contains(e)
1629            {
1630                result.push(e.clone());
1631                return Ok(TreeNodeRecursion::Jump);
1632            }
1633            Ok(TreeNodeRecursion::Continue)
1634        })?;
1635    }
1636    Ok(result)
1637}
1638
1639#[cfg(test)]
1640mod tests {
1641    use super::*;
1642    use crate::{
1643        Cast, ExprFunctionExt, WindowFunctionDefinition, col, cube,
1644        expr::WindowFunction,
1645        expr_vec_fmt, grouping_set, lit, rollup,
1646        test::function_stub::{max_udaf, min_udaf, sum_udaf},
1647    };
1648    use arrow::datatypes::{Metadata, UnionFields, UnionMode};
1649    use datafusion_expr_common::signature::Volatility;
1650
1651    #[test]
1652    fn passthrough_field_index_resolves_like_a_column_reference() -> Result<()> {
1653        let field = |name| Arc::new(Field::new(name, DataType::Int32, false));
1654        let schema = DFSchema::new_with_metadata(
1655            vec![
1656                (Some("a".into()), field("id")),
1657                (Some("b".into()), field("id")),
1658                (Some("b".into()), field("v")),
1659            ],
1660            Metadata::default(),
1661        )?;
1662        let index = |e: Expr| passthrough_field_index(&e, &schema);
1663
1664        assert_eq!(index(col("b.id")), Some(1));
1665        assert_eq!(index(col("v").alias("w")), Some(2));
1666        // ambiguous: `a.id` or `b.id`
1667        assert_eq!(index(col("id")), None);
1668        // computed, even though it is named `b.id`
1669        assert_eq!(index(crate::cast(col("b.id"), DataType::Int64)), None);
1670        Ok(())
1671    }
1672
1673    #[test]
1674    fn find_aggregate_exprs_dedups_in_order_of_appearance() {
1675        use crate::test::function_stub::{count, sum};
1676
1677        let exprs = [
1678            sum(col("a")) + count(col("b")),
1679            count(col("b")) * sum(col("c")),
1680            sum(col("a")) + sum(col("a")),
1681        ];
1682        assert_eq!(
1683            find_aggregate_exprs(&exprs),
1684            vec![sum(col("a")), count(col("b")), sum(col("c"))]
1685        );
1686    }
1687
1688    #[test]
1689    fn test_group_window_expr_by_sort_keys_empty_case() -> Result<()> {
1690        let result = group_window_expr_by_sort_keys(vec![])?;
1691        let expected: Vec<(WindowSortKey, Vec<Expr>)> = vec![];
1692        assert_eq!(expected, result);
1693        Ok(())
1694    }
1695
1696    #[test]
1697    fn test_group_window_expr_by_sort_keys_empty_window() -> Result<()> {
1698        let max1 = Expr::from(WindowFunction::new(
1699            WindowFunctionDefinition::AggregateUDF(max_udaf()),
1700            vec![col("name")],
1701        ));
1702        let max2 = Expr::from(WindowFunction::new(
1703            WindowFunctionDefinition::AggregateUDF(max_udaf()),
1704            vec![col("name")],
1705        ));
1706        let min3 = Expr::from(WindowFunction::new(
1707            WindowFunctionDefinition::AggregateUDF(min_udaf()),
1708            vec![col("name")],
1709        ));
1710        let sum4 = Expr::from(WindowFunction::new(
1711            WindowFunctionDefinition::AggregateUDF(sum_udaf()),
1712            vec![col("age")],
1713        ));
1714        let exprs = &[max1.clone(), max2.clone(), min3.clone(), sum4.clone()];
1715        let result = group_window_expr_by_sort_keys(exprs.to_vec())?;
1716        let key = vec![];
1717        let expected: Vec<(WindowSortKey, Vec<Expr>)> =
1718            vec![(key, vec![max1, max2, min3, sum4])];
1719        assert_eq!(expected, result);
1720        Ok(())
1721    }
1722
1723    #[test]
1724    fn test_group_window_expr_by_sort_keys_aliased_window_expr() -> Result<()> {
1725        let age_asc = Sort::new(col("age"), true, true);
1726        let max1 = Expr::from(WindowFunction::new(
1727            WindowFunctionDefinition::AggregateUDF(max_udaf()),
1728            vec![col("name")],
1729        ))
1730        .order_by(vec![age_asc.clone()])
1731        .build()
1732        .unwrap();
1733        // The same window function under an alias, as the Substrait consumer
1734        // produces when a window column's default name collides with an
1735        // input column. It must be grouped by the inner function's sort key
1736        // and kept aliased.
1737        let max1_aliased = max1.clone().alias("max_name");
1738
1739        let result =
1740            group_window_expr_by_sort_keys(vec![max1.clone(), max1_aliased.clone()])?;
1741
1742        let key = vec![(age_asc, false)];
1743        let expected: Vec<(WindowSortKey, Vec<Expr>)> =
1744            vec![(key, vec![max1, max1_aliased])];
1745        assert_eq!(expected, result);
1746        Ok(())
1747    }
1748    #[test]
1749    fn test_group_window_expr_by_sort_keys() -> Result<()> {
1750        let age_asc = Sort::new(col("age"), true, true);
1751        let name_desc = Sort::new(col("name"), false, true);
1752        let created_at_desc = Sort::new(col("created_at"), false, true);
1753        let max1 = Expr::from(WindowFunction::new(
1754            WindowFunctionDefinition::AggregateUDF(max_udaf()),
1755            vec![col("name")],
1756        ))
1757        .order_by(vec![age_asc.clone(), name_desc.clone()])
1758        .build()
1759        .unwrap();
1760        let max2 = Expr::from(WindowFunction::new(
1761            WindowFunctionDefinition::AggregateUDF(max_udaf()),
1762            vec![col("name")],
1763        ));
1764        let min3 = Expr::from(WindowFunction::new(
1765            WindowFunctionDefinition::AggregateUDF(min_udaf()),
1766            vec![col("name")],
1767        ))
1768        .order_by(vec![age_asc.clone(), name_desc.clone()])
1769        .build()
1770        .unwrap();
1771        let sum4 = Expr::from(WindowFunction::new(
1772            WindowFunctionDefinition::AggregateUDF(sum_udaf()),
1773            vec![col("age")],
1774        ))
1775        .order_by(vec![
1776            name_desc.clone(),
1777            age_asc.clone(),
1778            created_at_desc.clone(),
1779        ])
1780        .build()
1781        .unwrap();
1782        // FIXME use as_ref
1783        let exprs = &[max1.clone(), max2.clone(), min3.clone(), sum4.clone()];
1784        let result = group_window_expr_by_sort_keys(exprs.to_vec())?;
1785
1786        let key1 = vec![(age_asc.clone(), false), (name_desc.clone(), false)];
1787        let key2 = vec![];
1788        let key3 = vec![
1789            (name_desc, false),
1790            (age_asc, false),
1791            (created_at_desc, false),
1792        ];
1793
1794        let expected: Vec<(WindowSortKey, Vec<Expr>)> = vec![
1795            (key1, vec![max1, min3]),
1796            (key2, vec![max2]),
1797            (key3, vec![sum4]),
1798        ];
1799        assert_eq!(expected, result);
1800        Ok(())
1801    }
1802
1803    #[test]
1804    fn avoid_generate_duplicate_sort_keys() -> Result<()> {
1805        let asc_or_desc = [true, false];
1806        let nulls_first_or_last = [true, false];
1807        let partition_by = &[col("age"), col("name"), col("created_at")];
1808        for asc_ in asc_or_desc {
1809            for nulls_first_ in nulls_first_or_last {
1810                let order_by = &[
1811                    Sort {
1812                        expr: col("age"),
1813                        asc: asc_,
1814                        nulls_first: nulls_first_,
1815                    },
1816                    Sort {
1817                        expr: col("name"),
1818                        asc: asc_,
1819                        nulls_first: nulls_first_,
1820                    },
1821                ];
1822
1823                let expected = vec![
1824                    (
1825                        Sort {
1826                            expr: col("age"),
1827                            asc: asc_,
1828                            nulls_first: nulls_first_,
1829                        },
1830                        true,
1831                    ),
1832                    (
1833                        Sort {
1834                            expr: col("name"),
1835                            asc: asc_,
1836                            nulls_first: nulls_first_,
1837                        },
1838                        true,
1839                    ),
1840                    (
1841                        Sort {
1842                            expr: col("created_at"),
1843                            asc: true,
1844                            nulls_first: false,
1845                        },
1846                        true,
1847                    ),
1848                ];
1849                let result = generate_sort_key(partition_by, order_by)?;
1850                assert_eq!(expected, result);
1851            }
1852        }
1853        Ok(())
1854    }
1855
1856    #[test]
1857    fn test_enumerate_grouping_sets() -> Result<()> {
1858        let multi_cols = vec![col("col1"), col("col2"), col("col3")];
1859        let simple_col = col("simple_col");
1860        let cube = cube(multi_cols.clone());
1861        let rollup = rollup(multi_cols.clone());
1862        let grouping_set = grouping_set(vec![multi_cols]);
1863
1864        // 1. col
1865        let sets = enumerate_grouping_sets(vec![simple_col.clone()])?;
1866        let result = format!("[{}]", expr_vec_fmt!(sets));
1867        assert_eq!("[simple_col]", &result);
1868
1869        // 2. cube
1870        let sets = enumerate_grouping_sets(vec![cube.clone()])?;
1871        let result = format!("[{}]", expr_vec_fmt!(sets));
1872        assert_eq!("[CUBE (col1, col2, col3)]", &result);
1873
1874        // 3. rollup
1875        let sets = enumerate_grouping_sets(vec![rollup.clone()])?;
1876        let result = format!("[{}]", expr_vec_fmt!(sets));
1877        assert_eq!("[ROLLUP (col1, col2, col3)]", &result);
1878
1879        // 4. col + cube
1880        let sets = enumerate_grouping_sets(vec![simple_col.clone(), cube.clone()])?;
1881        let result = format!("[{}]", expr_vec_fmt!(sets));
1882        assert_eq!(
1883            "[GROUPING SETS (\
1884            (simple_col), \
1885            (simple_col, col1), \
1886            (simple_col, col2), \
1887            (simple_col, col1, col2), \
1888            (simple_col, col3), \
1889            (simple_col, col1, col3), \
1890            (simple_col, col2, col3), \
1891            (simple_col, col1, col2, col3))]",
1892            &result
1893        );
1894
1895        // 5. col + rollup
1896        let sets = enumerate_grouping_sets(vec![simple_col.clone(), rollup.clone()])?;
1897        let result = format!("[{}]", expr_vec_fmt!(sets));
1898        assert_eq!(
1899            "[GROUPING SETS (\
1900            (simple_col), \
1901            (simple_col, col1), \
1902            (simple_col, col1, col2), \
1903            (simple_col, col1, col2, col3))]",
1904            &result
1905        );
1906
1907        // 6. col + grouping_set
1908        let sets =
1909            enumerate_grouping_sets(vec![simple_col.clone(), grouping_set.clone()])?;
1910        let result = format!("[{}]", expr_vec_fmt!(sets));
1911        assert_eq!(
1912            "[GROUPING SETS (\
1913            (simple_col, col1, col2, col3))]",
1914            &result
1915        );
1916
1917        // 7. col + grouping_set + rollup
1918        let sets = enumerate_grouping_sets(vec![
1919            simple_col.clone(),
1920            grouping_set,
1921            rollup.clone(),
1922        ])?;
1923        let result = format!("[{}]", expr_vec_fmt!(sets));
1924        assert_eq!(
1925            "[GROUPING SETS (\
1926            (simple_col, col1, col2, col3), \
1927            (simple_col, col1, col2, col3, col1), \
1928            (simple_col, col1, col2, col3, col1, col2), \
1929            (simple_col, col1, col2, col3, col1, col2, col3))]",
1930            &result
1931        );
1932
1933        // 8. col + cube + rollup
1934        let sets = enumerate_grouping_sets(vec![simple_col, cube, rollup])?;
1935        let result = format!("[{}]", expr_vec_fmt!(sets));
1936        assert_eq!(
1937            "[GROUPING SETS (\
1938            (simple_col), \
1939            (simple_col, col1), \
1940            (simple_col, col1, col2), \
1941            (simple_col, col1, col2, col3), \
1942            (simple_col, col1), \
1943            (simple_col, col1, col1), \
1944            (simple_col, col1, col1, col2), \
1945            (simple_col, col1, col1, col2, col3), \
1946            (simple_col, col2), \
1947            (simple_col, col2, col1), \
1948            (simple_col, col2, col1, col2), \
1949            (simple_col, col2, col1, col2, col3), \
1950            (simple_col, col1, col2), \
1951            (simple_col, col1, col2, col1), \
1952            (simple_col, col1, col2, col1, col2), \
1953            (simple_col, col1, col2, col1, col2, col3), \
1954            (simple_col, col3), \
1955            (simple_col, col3, col1), \
1956            (simple_col, col3, col1, col2), \
1957            (simple_col, col3, col1, col2, col3), \
1958            (simple_col, col1, col3), \
1959            (simple_col, col1, col3, col1), \
1960            (simple_col, col1, col3, col1, col2), \
1961            (simple_col, col1, col3, col1, col2, col3), \
1962            (simple_col, col2, col3), \
1963            (simple_col, col2, col3, col1), \
1964            (simple_col, col2, col3, col1, col2), \
1965            (simple_col, col2, col3, col1, col2, col3), \
1966            (simple_col, col1, col2, col3), \
1967            (simple_col, col1, col2, col3, col1), \
1968            (simple_col, col1, col2, col3, col1, col2), \
1969            (simple_col, col1, col2, col3, col1, col2, col3))]",
1970            &result
1971        );
1972
1973        Ok(())
1974    }
1975    #[test]
1976    fn test_split_conjunction() {
1977        let expr = col("a");
1978        let result = split_conjunction(&expr);
1979        assert_eq!(result, vec![&expr]);
1980    }
1981
1982    #[test]
1983    fn test_split_conjunction_two() {
1984        let expr = col("a").eq(lit(5)).and(col("b"));
1985        let expr1 = col("a").eq(lit(5));
1986        let expr2 = col("b");
1987
1988        let result = split_conjunction(&expr);
1989        assert_eq!(result, vec![&expr1, &expr2]);
1990    }
1991
1992    #[test]
1993    fn test_split_conjunction_alias() {
1994        let expr = col("a").eq(lit(5)).and(col("b").alias("the_alias"));
1995        let expr1 = col("a").eq(lit(5));
1996        let expr2 = col("b"); // has no alias
1997
1998        let result = split_conjunction(&expr);
1999        assert_eq!(result, vec![&expr1, &expr2]);
2000    }
2001
2002    #[test]
2003    fn test_split_conjunction_or() {
2004        let expr = col("a").eq(lit(5)).or(col("b"));
2005        let result = split_conjunction(&expr);
2006        assert_eq!(result, vec![&expr]);
2007    }
2008
2009    #[test]
2010    fn test_split_binary_owned() {
2011        let expr = col("a");
2012        assert_eq!(split_binary_owned(expr.clone(), Operator::And), vec![expr]);
2013    }
2014
2015    #[test]
2016    fn test_split_binary_owned_two() {
2017        assert_eq!(
2018            split_binary_owned(col("a").eq(lit(5)).and(col("b")), Operator::And),
2019            vec![col("a").eq(lit(5)), col("b")]
2020        );
2021    }
2022
2023    #[test]
2024    fn test_split_binary_owned_different_op() {
2025        let expr = col("a").eq(lit(5)).or(col("b"));
2026        assert_eq!(
2027            // expr is connected by OR, but pass in AND
2028            split_binary_owned(expr.clone(), Operator::And),
2029            vec![expr]
2030        );
2031    }
2032
2033    #[test]
2034    fn test_split_conjunction_owned() {
2035        let expr = col("a");
2036        assert_eq!(split_conjunction_owned(expr.clone()), vec![expr]);
2037    }
2038
2039    #[test]
2040    fn test_split_conjunction_owned_two() {
2041        assert_eq!(
2042            split_conjunction_owned(col("a").eq(lit(5)).and(col("b"))),
2043            vec![col("a").eq(lit(5)), col("b")]
2044        );
2045    }
2046
2047    #[test]
2048    fn test_split_conjunction_owned_alias() {
2049        assert_eq!(
2050            split_conjunction_owned(col("a").eq(lit(5)).and(col("b").alias("the_alias"))),
2051            vec![
2052                col("a").eq(lit(5)),
2053                // no alias on b
2054                col("b"),
2055            ]
2056        );
2057    }
2058
2059    #[test]
2060    fn test_conjunction_empty() {
2061        assert_eq!(conjunction(vec![]), None);
2062    }
2063
2064    #[test]
2065    fn test_conjunction() {
2066        // `[A, B, C]`
2067        let expr = conjunction(vec![col("a"), col("b"), col("c")]);
2068
2069        // --> `(A AND B) AND C`
2070        assert_eq!(expr, Some(col("a").and(col("b")).and(col("c"))));
2071
2072        // which is different than `A AND (B AND C)`
2073        assert_ne!(expr, Some(col("a").and(col("b").and(col("c")))));
2074    }
2075
2076    #[test]
2077    fn test_disjunction_empty() {
2078        assert_eq!(disjunction(vec![]), None);
2079    }
2080
2081    #[test]
2082    fn test_disjunction() {
2083        // `[A, B, C]`
2084        let expr = disjunction(vec![col("a"), col("b"), col("c")]);
2085
2086        // --> `(A OR B) OR C`
2087        assert_eq!(expr, Some(col("a").or(col("b")).or(col("c"))));
2088
2089        // which is different than `A OR (B OR C)`
2090        assert_ne!(expr, Some(col("a").or(col("b").or(col("c")))));
2091    }
2092
2093    #[test]
2094    fn test_split_conjunction_owned_or() {
2095        let expr = col("a").eq(lit(5)).or(col("b"));
2096        assert_eq!(split_conjunction_owned(expr.clone()), vec![expr]);
2097    }
2098
2099    #[test]
2100    fn test_collect_expr() -> Result<()> {
2101        let mut accum: HashSet<Column> = HashSet::new();
2102        expr_to_columns(
2103            &Expr::Cast(Cast::new(Box::new(col("a")), DataType::Float64)),
2104            &mut accum,
2105        )?;
2106        expr_to_columns(
2107            &Expr::Cast(Cast::new(Box::new(col("a")), DataType::Float64)),
2108            &mut accum,
2109        )?;
2110        assert_eq!(1, accum.len());
2111        assert!(accum.contains(&Column::from_name("a")));
2112        Ok(())
2113    }
2114
2115    #[test]
2116    fn test_can_hash() {
2117        let union_fields: UnionFields = [
2118            (0, Arc::new(Field::new("A", DataType::Int32, true))),
2119            (1, Arc::new(Field::new("B", DataType::Float64, true))),
2120        ]
2121        .into_iter()
2122        .collect();
2123
2124        let union_type = DataType::Union(union_fields, UnionMode::Sparse);
2125        assert!(!can_hash(&union_type));
2126
2127        let list_union_type =
2128            DataType::List(Arc::new(Field::new("my_union", union_type, true)));
2129        assert!(!can_hash(&list_union_type));
2130    }
2131
2132    #[test]
2133    fn test_generate_signature_error_msg_with_parameter_names() {
2134        let sig = Signature::one_of(
2135            vec![
2136                TypeSignature::Exact(vec![DataType::Utf8, DataType::Int64]),
2137                TypeSignature::Exact(vec![
2138                    DataType::Utf8,
2139                    DataType::Int64,
2140                    DataType::Int64,
2141                ]),
2142            ],
2143            Volatility::Immutable,
2144        )
2145        .with_parameter_names(vec![
2146            "str".to_string(),
2147            "start_pos".to_string(),
2148            "length".to_string(),
2149        ])
2150        .expect("valid parameter names");
2151
2152        // Generate error message with only 1 argument provided
2153        let error_msg =
2154            generate_signature_error_message("substr", &sig, &[DataType::Utf8]);
2155
2156        assert!(
2157            error_msg.contains("str: Utf8, start_pos: Int64"),
2158            "Expected 'str: Utf8, start_pos: Int64' in error message, got: {error_msg}"
2159        );
2160        assert!(
2161            error_msg.contains("str: Utf8, start_pos: Int64, length: Int64"),
2162            "Expected 'str: Utf8, start_pos: Int64, length: Int64' in error message, got: {error_msg}"
2163        );
2164    }
2165
2166    #[test]
2167    fn test_generate_signature_error_msg_without_parameter_names() {
2168        let sig = Signature::one_of(
2169            vec![TypeSignature::Any(2), TypeSignature::Any(3)],
2170            Volatility::Immutable,
2171        );
2172
2173        let error_msg =
2174            generate_signature_error_message("my_func", &sig, &[DataType::Int32]);
2175
2176        assert!(
2177            error_msg.contains("Any, Any"),
2178            "Expected 'Any, Any' without parameter names, got: {error_msg}"
2179        );
2180    }
2181
2182    #[test]
2183    fn test_signature_error_msg_exact() {
2184        use insta::assert_snapshot;
2185
2186        let sig = Signature::one_of(
2187            vec![
2188                TypeSignature::Exact(vec![DataType::Float64, DataType::Int64]),
2189                TypeSignature::Exact(vec![DataType::Float32, DataType::Int64]),
2190                TypeSignature::Exact(vec![DataType::Float64]),
2191                TypeSignature::Exact(vec![DataType::Float32]),
2192            ],
2193            Volatility::Immutable,
2194        );
2195        let msg = generate_signature_error_message(
2196            "round",
2197            &sig,
2198            &[DataType::Float64, DataType::Float64],
2199        );
2200        assert_snapshot!(msg, @r"
2201        No function matches the given name and argument types 'round(Float64, Float64)'. You might need to add explicit type casts.
2202        	Candidate functions:
2203        	round(Float64, Int64)
2204        	round(Float32, Int64)
2205        	round(Float64)
2206        	round(Float32)
2207        ");
2208    }
2209
2210    #[test]
2211    fn test_signature_error_msg_coercible() {
2212        use datafusion_common::types::NativeType;
2213        use datafusion_expr_common::signature::{Coercion, TypeSignatureClass};
2214        use insta::assert_snapshot;
2215
2216        let sig = Signature::coercible(
2217            vec![
2218                Coercion::new_implicit(
2219                    TypeSignatureClass::Native(
2220                        datafusion_common::types::logical_float64(),
2221                    ),
2222                    vec![TypeSignatureClass::Numeric],
2223                    NativeType::Float64,
2224                ),
2225                Coercion::new_implicit(
2226                    TypeSignatureClass::Native(datafusion_common::types::logical_int64()),
2227                    vec![TypeSignatureClass::Integer],
2228                    NativeType::Int64,
2229                ),
2230            ],
2231            Volatility::Immutable,
2232        );
2233        let msg = generate_signature_error_message(
2234            "round",
2235            &sig,
2236            &[DataType::Utf8, DataType::Utf8],
2237        );
2238        assert_snapshot!(msg, @r"
2239        No function matches the given name and argument types 'round(Utf8, Utf8)'. You might need to add explicit type casts.
2240        	Candidate functions:
2241        	round(Float64, Int64)
2242        ");
2243    }
2244
2245    #[test]
2246    fn test_signature_error_msg_with_names_coercible() {
2247        use datafusion_common::types::NativeType;
2248        use datafusion_expr_common::signature::{Coercion, TypeSignatureClass};
2249        use insta::assert_snapshot;
2250
2251        let sig = Signature::coercible(
2252            vec![
2253                Coercion::new_exact(TypeSignatureClass::Native(
2254                    datafusion_common::types::logical_string(),
2255                )),
2256                Coercion::new_exact(TypeSignatureClass::Native(
2257                    datafusion_common::types::logical_int64(),
2258                )),
2259                Coercion::new_implicit(
2260                    TypeSignatureClass::Native(datafusion_common::types::logical_int64()),
2261                    vec![TypeSignatureClass::Integer],
2262                    NativeType::Int64,
2263                ),
2264            ],
2265            Volatility::Immutable,
2266        )
2267        .with_parameter_names(vec![
2268            "string".to_string(),
2269            "start_pos".to_string(),
2270            "length".to_string(),
2271        ])
2272        .expect("valid parameter names");
2273
2274        let msg = generate_signature_error_message("substr", &sig, &[DataType::Int32]);
2275        assert_snapshot!(msg, @r"
2276        No function matches the given name and argument types 'substr(Int32)'. You might need to add explicit type casts.
2277        	Candidate functions:
2278        	substr(string: String, start_pos: Int64, length: Int64)
2279        ");
2280    }
2281
2282    /// `sum(<args>) OVER ()`
2283    fn sum_over(args: Vec<Expr>) -> Expr {
2284        Expr::from(WindowFunction::new(
2285            WindowFunctionDefinition::AggregateUDF(sum_udaf()),
2286            args,
2287        ))
2288    }
2289
2290    #[test]
2291    fn test_check_aggregate_and_window_nesting_ok() -> Result<()> {
2292        use crate::test::function_stub::{count, sum};
2293
2294        let exprs = [
2295            // a plain aggregate, and one wrapped in a scalar expression
2296            sum(col("a")),
2297            count(col("a")) + lit(1),
2298            // a window function over a column, and over an aggregate
2299            sum_over(vec![col("a")]),
2300            sum_over(vec![sum(col("a"))]),
2301        ];
2302
2303        check_aggregate_and_window_nesting(exprs.iter())?;
2304        Ok(())
2305    }
2306
2307    #[test]
2308    fn test_check_aggregate_and_window_nesting_err() {
2309        use crate::test::function_stub::{count, sum};
2310        use insta::assert_snapshot;
2311
2312        // an aggregate directly inside an aggregate
2313        let err = check_aggregate_and_window_nesting([&sum(sum(col("a")))]).unwrap_err();
2314        assert_snapshot!(
2315            err.strip_backtrace(),
2316            @"Error during planning: Aggregate function calls cannot be nested: 'sum(a)' is nested inside 'sum(sum(a))'"
2317        );
2318
2319        // nested below another expression in the arguments
2320        let err = check_aggregate_and_window_nesting([&sum(col("a") + count(col("b")))])
2321            .unwrap_err();
2322        assert_snapshot!(
2323            err.strip_backtrace(),
2324            @"Error during planning: Aggregate function calls cannot be nested: 'COUNT(b)' is nested inside 'sum(a + COUNT(b))'"
2325        );
2326
2327        // nested in the FILTER of an aggregate
2328        let filtered = sum(col("a"))
2329            .filter(sum(col("b")).gt(lit(0)))
2330            .build()
2331            .unwrap();
2332        let err = check_aggregate_and_window_nesting([&filtered]).unwrap_err();
2333        assert_snapshot!(
2334            err.strip_backtrace(),
2335            @"Error during planning: Aggregate function calls cannot be nested: 'sum(b)' is nested inside 'sum(a) FILTER (WHERE sum(b) > Int32(0))'"
2336        );
2337
2338        // nested in the ORDER BY of an aggregate
2339        let ordered = sum(col("a"))
2340            .order_by(vec![Sort::new(sum(col("b")), true, false)])
2341            .build()
2342            .unwrap();
2343        let err = check_aggregate_and_window_nesting([&ordered]).unwrap_err();
2344        assert_snapshot!(
2345            err.strip_backtrace(),
2346            @"Error during planning: Aggregate function calls cannot be nested: 'sum(b)' is nested inside 'sum(a) ORDER BY [sum(b) ASC NULLS LAST]'"
2347        );
2348
2349        // a window function inside an aggregate
2350        let err = check_aggregate_and_window_nesting([&sum(sum_over(vec![col("a")]))])
2351            .unwrap_err();
2352        assert_snapshot!(
2353            err.strip_backtrace(),
2354            @"Error during planning: Aggregate function calls cannot contain window function calls: 'sum(a) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING' is nested inside 'sum(sum(a) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)'"
2355        );
2356
2357        // a window function inside a window function
2358        let err =
2359            check_aggregate_and_window_nesting([&sum_over(vec![sum_over(vec![col(
2360                "a",
2361            )])])])
2362            .unwrap_err();
2363        assert_snapshot!(
2364            err.strip_backtrace(),
2365            @"Error during planning: Window function calls cannot be nested: 'sum(a) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING' is nested inside 'sum(sum(a) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING'"
2366        );
2367    }
2368
2369    #[test]
2370    fn test_check_no_window_functions() -> Result<()> {
2371        use crate::test::function_stub::sum;
2372        use insta::assert_snapshot;
2373
2374        // columns, scalar expressions and aggregates are fine
2375        check_no_window_functions(&col("a"), "WHERE")?;
2376        check_no_window_functions(&(col("a") + lit(1)).gt(lit(0)), "WHERE")?;
2377        check_no_window_functions(&sum(col("a")).gt(lit(0)), "HAVING")?;
2378
2379        // a bare window call
2380        let err =
2381            check_no_window_functions(&sum_over(vec![col("a")]), "WHERE").unwrap_err();
2382        assert_snapshot!(
2383            err.strip_backtrace(),
2384            @"Error during planning: Window function calls are not allowed in WHERE: 'sum(a) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING'"
2385        );
2386        let diag = err.diagnostic().expect("diagnostic");
2387        assert_snapshot!(
2388            diag.message,
2389            @"Window function calls are not allowed in WHERE"
2390        );
2391        assert_snapshot!(
2392            diag.helps[0].message,
2393            @"Compute 'sum(a) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING' first, in a Window node or an inner query, and filter on its result"
2394        );
2395
2396        // a window call over an aggregate, nested below other expressions,
2397        // names the clause it was given
2398        let predicate = sum_over(vec![sum(col("a"))]).gt(lit(10)).and(col("b"));
2399        let err = check_no_window_functions(&predicate, "HAVING").unwrap_err();
2400        assert_snapshot!(
2401            err.strip_backtrace(),
2402            @"Error during planning: Window function calls are not allowed in HAVING: 'sum(sum(a)) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING'"
2403        );
2404
2405        Ok(())
2406    }
2407
2408    #[test]
2409    fn find_valid_equijoin_key_pair_inputs_of_different_widths() -> Result<()> {
2410        let schema = |name: &str, width: usize| {
2411            let fields = (0..width)
2412                .map(|i| Field::new(format!("c{i}"), DataType::Int32, false))
2413                .collect::<Vec<_>>();
2414            DFSchema::try_from_qualified_schema(name, &Schema::new(fields))
2415        };
2416        let narrow = schema("n", 1)?;
2417        let wide = schema("w", 3)?;
2418        let other = col("o.c0");
2419
2420        // The narrower input is checked first, so cover both orders
2421        for (left_schema, right_schema, left, right) in [
2422            (&narrow, &wide, col("n.c0"), col("w.c2")),
2423            (&wide, &narrow, col("w.c2"), col("n.c0")),
2424        ] {
2425            let find = |left_key: &Expr, right_key: &Expr| {
2426                find_valid_equijoin_key_pair(
2427                    left_key,
2428                    right_key,
2429                    left_schema,
2430                    right_schema,
2431                )
2432            };
2433            let expected = Some((left.clone(), right.clone()));
2434            assert_eq!(find(&left, &right)?, expected);
2435            assert_eq!(find(&right, &left)?, expected);
2436            assert_eq!(find(&left, &other)?, None);
2437            assert_eq!(find(&other, &right)?, None);
2438            assert_eq!(find(&(left.clone() + right.clone()), &right)?, None);
2439        }
2440        Ok(())
2441    }
2442}