Skip to main content

datafusion_sql/
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//! SQL Utility Functions
6
7use std::vec;
8
9use arrow::datatypes::{
10    DECIMAL_DEFAULT_SCALE, DECIMAL128_MAX_PRECISION, DECIMAL256_MAX_PRECISION, DataType,
11};
12use datafusion_common::tree_node::{
13    Transformed, TransformedResult, TreeNode, TreeNodeRecursion, TreeNodeRewriter,
14};
15use datafusion_common::{
16    Column, DFSchemaRef, Diagnostic, HashMap, HashSet, Result, ScalarValue,
17    assert_or_internal_err, exec_datafusion_err, exec_err, internal_err, plan_err,
18};
19use datafusion_expr::builder::get_struct_unnested_columns;
20use datafusion_expr::expr::{
21    Alias, GroupingSet, Unnest, WindowFunction, WindowFunctionParams,
22};
23use datafusion_expr::utils::{expr_as_column_expr, find_column_exprs};
24use datafusion_expr::{
25    ColumnUnnestList, Expr, ExprSchemable, LogicalPlan, SortExpr, col, expr_vec_fmt,
26};
27
28use indexmap::IndexMap;
29use sqlparser::ast::{Ident, Value};
30
31/// Make a best-effort attempt at resolving all columns in the expression tree
32pub(crate) fn resolve_columns(expr: &Expr, plan: &LogicalPlan) -> Result<Expr> {
33    expr.clone()
34        .transform_up(|nested_expr| {
35            match nested_expr {
36                Expr::Column(col) => {
37                    let (qualifier, field) =
38                        plan.schema().qualified_field_from_column(&col)?;
39                    Ok(Transformed::yes(Expr::Column(Column::from((
40                        qualifier, field,
41                    )))))
42                }
43                _ => {
44                    // keep recursing
45                    Ok(Transformed::no(nested_expr))
46                }
47            }
48        })
49        .data()
50}
51
52/// Rebuilds an `Expr` as a projection on top of a collection of `Expr`'s.
53///
54/// For example, the expression `a + b < 1` would require, as input, the 2
55/// individual columns, `a` and `b`. But, if the base expressions already
56/// contain the `a + b` result, then that may be used in lieu of the `a` and
57/// `b` columns.
58///
59/// This is useful in the context of a query like:
60///
61/// SELECT a + b < 1 ... GROUP BY a + b
62///
63/// where post-aggregation, `a + b` need not be a projection against the
64/// individual columns `a` and `b`, but rather it is a projection against the
65/// `a + b` found in the GROUP BY.
66pub(crate) fn rebase_expr(
67    expr: &Expr,
68    base_exprs: &[Expr],
69    plan: &LogicalPlan,
70) -> Result<Expr> {
71    expr.clone()
72        .transform_down(|nested_expr| {
73            if base_exprs.contains(&nested_expr) {
74                Ok(Transformed::yes(expr_as_column_expr(&nested_expr, plan)?))
75            } else {
76                Ok(Transformed::no(nested_expr))
77            }
78        })
79        .data()
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub(crate) enum CheckColumnsMustReferenceAggregatePurpose {
84    Projection,
85    Having,
86    Qualify,
87    OrderBy,
88    DistinctOn,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub(crate) enum CheckColumnsSatisfyExprsPurpose {
93    Aggregate(CheckColumnsMustReferenceAggregatePurpose),
94}
95
96impl CheckColumnsSatisfyExprsPurpose {
97    fn message_prefix(&self) -> &'static str {
98        match self {
99            Self::Aggregate(CheckColumnsMustReferenceAggregatePurpose::Projection) => {
100                "Column in SELECT must be in GROUP BY or an aggregate function"
101            }
102            Self::Aggregate(CheckColumnsMustReferenceAggregatePurpose::Having) => {
103                "Column in HAVING must be in GROUP BY or an aggregate function"
104            }
105            Self::Aggregate(CheckColumnsMustReferenceAggregatePurpose::Qualify) => {
106                "Column in QUALIFY must be in GROUP BY or an aggregate function"
107            }
108            Self::Aggregate(CheckColumnsMustReferenceAggregatePurpose::OrderBy) => {
109                "Column in ORDER BY must be in GROUP BY or an aggregate function"
110            }
111            Self::Aggregate(CheckColumnsMustReferenceAggregatePurpose::DistinctOn) => {
112                "Column in DISTINCT ON must be in GROUP BY or an aggregate function"
113            }
114        }
115    }
116
117    fn diagnostic_message(&self, expr: &Expr) -> String {
118        format!(
119            "'{expr}' must appear in GROUP BY clause because it's not an aggregate expression"
120        )
121    }
122}
123
124/// Determines if the set of `Expr`'s are a valid projection on the input
125/// `Expr::Column`'s.
126pub(crate) fn check_columns_satisfy_exprs(
127    columns: &[Expr],
128    exprs: &[Expr],
129    purpose: CheckColumnsSatisfyExprsPurpose,
130) -> Result<()> {
131    columns.iter().try_for_each(|c| match c {
132        Expr::Column(_) => Ok(()),
133        _ => internal_err!("Expr::Column are required"),
134    })?;
135    let column_exprs = find_column_exprs(exprs);
136    for e in &column_exprs {
137        match e {
138            Expr::GroupingSet(GroupingSet::Rollup(exprs)) => {
139                for e in exprs {
140                    check_column_satisfies_expr(columns, e, purpose)?;
141                }
142            }
143            Expr::GroupingSet(GroupingSet::Cube(exprs)) => {
144                for e in exprs {
145                    check_column_satisfies_expr(columns, e, purpose)?;
146                }
147            }
148            Expr::GroupingSet(GroupingSet::GroupingSets(lists_of_exprs)) => {
149                for exprs in lists_of_exprs {
150                    for e in exprs {
151                        check_column_satisfies_expr(columns, e, purpose)?;
152                    }
153                }
154            }
155            _ => check_column_satisfies_expr(columns, e, purpose)?,
156        }
157    }
158    Ok(())
159}
160
161fn check_column_satisfies_expr(
162    columns: &[Expr],
163    expr: &Expr,
164    purpose: CheckColumnsSatisfyExprsPurpose,
165) -> Result<()> {
166    if !columns.contains(expr) {
167        let diagnostic = Diagnostic::new_error(
168            purpose.diagnostic_message(expr),
169            expr.spans().and_then(|spans| spans.first()),
170        )
171        .with_help(format!("Either add '{expr}' to GROUP BY clause, or use an aggregate function like ANY_VALUE({expr})"), None);
172
173        return plan_err!(
174            "{}: While expanding wildcard, column \"{}\" must appear in the GROUP BY clause or must be part of an aggregate function, currently only \"{}\" appears in the SELECT clause satisfies this requirement",
175            purpose.message_prefix(),
176            expr,
177            expr_vec_fmt!(columns);
178            diagnostic=diagnostic
179        );
180    }
181    Ok(())
182}
183
184/// Returns mapping of each alias (`String`) to the expression (`Expr`) it is
185/// aliasing.
186pub(crate) fn extract_aliases(exprs: &[Expr]) -> HashMap<String, Expr> {
187    exprs
188        .iter()
189        .filter_map(|expr| match expr {
190            Expr::Alias(Alias { expr, name, .. }) => Some((name.clone(), *expr.clone())),
191            _ => None,
192        })
193        .collect::<HashMap<String, Expr>>()
194}
195
196/// If `expr` is a bare unqualified `Column` whose name matches a SELECT
197/// alias, swap it for the alias's underlying expression. Nested occurrences
198/// are left alone: PostgreSQL only resolves a top-level identifier as an
199/// output alias in clauses like ORDER BY and DISTINCT ON.
200pub(crate) fn substitute_top_level_alias(
201    expr: Expr,
202    aliases: &HashMap<String, Expr>,
203) -> Expr {
204    if let Expr::Column(col) = &expr
205        && col.relation.is_none()
206        && let Some(underlying) = aliases.get(&col.name)
207    {
208        return underlying.clone();
209    }
210
211    expr
212}
213
214/// Applies [`substitute_top_level_alias`] to each sort expression.
215pub(crate) fn substitute_top_level_aliases_in_sorts(
216    sort_exprs: Vec<SortExpr>,
217    aliases: &HashMap<String, Expr>,
218) -> Vec<SortExpr> {
219    if aliases.is_empty() {
220        return sort_exprs;
221    }
222
223    sort_exprs
224        .into_iter()
225        .map(|sort_expr| {
226            sort_expr
227                .with_expr(substitute_top_level_alias(sort_expr.expr.clone(), aliases))
228        })
229        .collect()
230}
231
232/// Given an expression that's literal int encoding position, lookup the corresponding expression
233/// in the select_exprs list, if the index is within the bounds and it is indeed a position literal,
234/// otherwise, returns planning error.
235/// If input expression is not an int literal, returns expression as-is.
236pub(crate) fn resolve_positions_to_exprs(
237    expr: Expr,
238    select_exprs: &[Expr],
239) -> Result<Expr> {
240    match expr {
241        // sql_expr_to_logical_expr maps number to i64
242        // https://github.com/apache/datafusion/blob/8d175c759e17190980f270b5894348dc4cff9bbf/datafusion/src/sql/planner.rs#L882-L887
243        Expr::Literal(ScalarValue::Int64(Some(position)), _)
244            if position > 0_i64 && position <= select_exprs.len() as i64 =>
245        {
246            let index = (position - 1) as usize;
247            let select_expr = &select_exprs[index];
248            Ok(match select_expr {
249                Expr::Alias(Alias { expr, .. }) => *expr.clone(),
250                _ => select_expr.clone(),
251            })
252        }
253        Expr::Literal(ScalarValue::Int64(Some(position)), _) => plan_err!(
254            "Cannot find column with position {} in SELECT clause. Valid columns: 1 to {}",
255            position,
256            select_exprs.len()
257        ),
258        _ => Ok(expr),
259    }
260}
261
262/// Returns true if `expr` references (as a bare unqualified column) any
263/// SELECT alias whose underlying expression is volatile.
264///
265/// Such references must not be dereferenced to the underlying expression:
266/// every copy of a volatile expression is evaluated independently, so the
267/// rewritten clause would test a different value than the one the query
268/// returns. See <https://github.com/apache/datafusion/issues/7976>.
269pub(crate) fn references_volatile_alias(
270    expr: &Expr,
271    aliases: &HashMap<String, Expr>,
272) -> Result<bool> {
273    expr.exists(|nested_expr| {
274        Ok(matches!(
275            nested_expr,
276            Expr::Column(c)
277                if c.relation.is_none()
278                    && aliases.get(&c.name).is_some_and(Expr::is_volatile)
279        ))
280    })
281}
282
283/// Rebuilds an `Expr` with columns that refer to aliases replaced by the
284/// alias' underlying `Expr`.
285pub(crate) fn resolve_aliases_to_exprs(
286    expr: Expr,
287    aliases: &HashMap<String, Expr>,
288) -> Result<Expr> {
289    expr.transform_up(|nested_expr| match nested_expr {
290        Expr::Column(c) if c.relation.is_none() => {
291            if let Some(aliased_expr) = aliases.get(&c.name) {
292                Ok(Transformed::yes(aliased_expr.clone()))
293            } else {
294                Ok(Transformed::no(Expr::Column(c)))
295            }
296        }
297        _ => Ok(Transformed::no(nested_expr)),
298    })
299    .data()
300}
301
302/// Given a slice of window expressions sharing the same sort key, find their common partition
303/// keys.
304pub fn window_expr_common_partition_keys(window_exprs: &[Expr]) -> Result<&[Expr]> {
305    let all_partition_keys = window_exprs
306        .iter()
307        .map(|expr| match expr {
308            Expr::WindowFunction(window_fun) => {
309                let WindowFunction {
310                    params: WindowFunctionParams { partition_by, .. },
311                    ..
312                } = window_fun.as_ref();
313                Ok(partition_by)
314            }
315            Expr::Alias(Alias { expr, .. }) => match expr.as_ref() {
316                Expr::WindowFunction(window_fun) => {
317                    let WindowFunction {
318                        params: WindowFunctionParams { partition_by, .. },
319                        ..
320                    } = window_fun.as_ref();
321                    Ok(partition_by)
322                }
323                expr => exec_err!("Impossibly got non-window expr {expr:?}"),
324            },
325            expr => exec_err!("Impossibly got non-window expr {expr:?}"),
326        })
327        .collect::<Result<Vec<_>>>()?;
328    let result = all_partition_keys
329        .iter()
330        .min_by_key(|s| s.len())
331        .ok_or_else(|| exec_datafusion_err!("No window expressions found"))?;
332    Ok(result)
333}
334
335/// Returns a validated `DataType` for the specified precision and
336/// scale
337pub(crate) fn make_decimal_type(
338    precision: Option<u64>,
339    scale: Option<u64>,
340) -> Result<DataType> {
341    // postgres like behavior
342    let (precision, scale) = match (precision, scale) {
343        (Some(p), Some(s)) => (p as u8, s as i8),
344        (Some(p), None) => (p as u8, 0),
345        (None, Some(_)) => {
346            return plan_err!("Cannot specify only scale for decimal data type");
347        }
348        (None, None) => (DECIMAL128_MAX_PRECISION, DECIMAL_DEFAULT_SCALE),
349    };
350
351    if precision == 0
352        || precision > DECIMAL256_MAX_PRECISION
353        || scale.unsigned_abs() > precision
354    {
355        plan_err!(
356            "Decimal(precision = {precision}, scale = {scale}) should satisfy `0 < precision <= 76`, and `scale <= precision`."
357        )
358    } else if precision > DECIMAL128_MAX_PRECISION
359        && precision <= DECIMAL256_MAX_PRECISION
360    {
361        Ok(DataType::Decimal256(precision, scale))
362    } else {
363        Ok(DataType::Decimal128(precision, scale))
364    }
365}
366
367/// Normalize an owned identifier to a lowercase string, unless the identifier is quoted.
368pub(crate) fn normalize_ident(id: Ident) -> String {
369    match id.quote_style {
370        Some(_) => id.value,
371        None => id.value.to_ascii_lowercase(),
372    }
373}
374
375pub(crate) fn value_to_string(value: &Value) -> Option<String> {
376    match value {
377        Value::SingleQuotedString(s) => Some(s.to_string()),
378        Value::DollarQuotedString(s) => Some(s.to_string()),
379        Value::Number(_, _) | Value::Boolean(_) => Some(value.to_string()),
380        Value::UnicodeStringLiteral(s) => Some(s.to_string()),
381        Value::EscapedStringLiteral(s) => Some(s.to_string()),
382        Value::QuoteDelimitedStringLiteral(s)
383        | Value::NationalQuoteDelimitedStringLiteral(s) => Some(s.value.to_string()),
384        Value::DoubleQuotedString(_)
385        | Value::NationalStringLiteral(_)
386        | Value::SingleQuotedByteStringLiteral(_)
387        | Value::DoubleQuotedByteStringLiteral(_)
388        | Value::TripleSingleQuotedString(_)
389        | Value::TripleDoubleQuotedString(_)
390        | Value::TripleSingleQuotedByteStringLiteral(_)
391        | Value::TripleDoubleQuotedByteStringLiteral(_)
392        | Value::SingleQuotedRawStringLiteral(_)
393        | Value::DoubleQuotedRawStringLiteral(_)
394        | Value::TripleSingleQuotedRawStringLiteral(_)
395        | Value::TripleDoubleQuotedRawStringLiteral(_)
396        | Value::HexStringLiteral(_)
397        | Value::Null
398        | Value::Placeholder(_) => None,
399    }
400}
401
402pub(crate) fn rewrite_recursive_unnests_bottom_up(
403    input: &LogicalPlan,
404    unnest_placeholder_columns: &mut IndexMap<Column, Option<Vec<ColumnUnnestList>>>,
405    inner_projection_exprs: &mut DedupedProjection,
406    original_exprs: &[Expr],
407) -> Result<Vec<Expr>> {
408    Ok(original_exprs
409        .iter()
410        .map(|expr| {
411            rewrite_recursive_unnest_bottom_up(
412                input,
413                unnest_placeholder_columns,
414                inner_projection_exprs,
415                expr,
416            )
417        })
418        .collect::<Result<Vec<_>>>()?
419        .into_iter()
420        .flatten()
421        .collect::<Vec<_>>())
422}
423
424pub const UNNEST_PLACEHOLDER: &str = "__unnest_placeholder";
425
426/*
427This is only useful when used with transform down up
428A full example of how the transformation works:
429 */
430struct RecursiveUnnestRewriter<'a> {
431    input_schema: &'a DFSchemaRef,
432    root_expr: &'a Expr,
433    // Useful to detect which child expr is a part of/ not a part of unnest operation
434    top_most_unnest: Option<Unnest>,
435    consecutive_unnest: Vec<Option<Unnest>>,
436    inner_projection_exprs: &'a mut DedupedProjection,
437    columns_unnestings: &'a mut IndexMap<Column, Option<Vec<ColumnUnnestList>>>,
438    transformed_root_exprs: Option<Vec<Expr>>,
439}
440impl RecursiveUnnestRewriter<'_> {
441    /// This struct stores the history of expr
442    /// during its tree-traversal with a notation of
443    /// \[None,**Unnest(exprA)**,**Unnest(exprB)**,None,None\]
444    /// then this function will returns \[**Unnest(exprA)**,**Unnest(exprB)**\]
445    ///
446    /// The first item will be the inner most expr
447    fn get_latest_consecutive_unnest(&self) -> Vec<Unnest> {
448        self.consecutive_unnest
449            .iter()
450            .rev()
451            .skip_while(|item| item.is_none())
452            .map_while(|item| item.clone())
453            .collect()
454    }
455
456    /// Check if the current expression is at the root level for struct unnest purposes.
457    /// This is true if:
458    /// 1. The expression IS the root expression, OR
459    /// 2. The root expression is an Alias wrapping this expression
460    ///
461    /// This allows `unnest(struct_col) AS alias` to work, where the alias is simply
462    /// ignored for struct unnest (matching DuckDB behavior).
463    fn is_at_struct_allowed_root(&self, expr: &Expr) -> bool {
464        if expr == self.root_expr {
465            return true;
466        }
467        // Allow struct unnest when root is an alias wrapping the unnest
468        if let Expr::Alias(Alias { expr: inner, .. }) = self.root_expr {
469            return inner.as_ref() == expr;
470        }
471        false
472    }
473
474    fn transform(
475        &mut self,
476        level: usize,
477        alias_name: String,
478        expr_in_unnest: &Expr,
479        struct_allowed: bool,
480    ) -> Result<Vec<Expr>> {
481        let inner_expr_name = expr_in_unnest.schema_name().to_string();
482
483        // Full context, we are trying to plan the execution as InnerProjection->Unnest->OuterProjection
484        // inside unnest execution, each column inside the inner projection
485        // will be transformed into new columns. Thus we need to keep track of these placeholding column names
486        let placeholder_name = format!("{UNNEST_PLACEHOLDER}({inner_expr_name})");
487        let post_unnest_name =
488            format!("{UNNEST_PLACEHOLDER}({inner_expr_name},depth={level})");
489        // This is due to the fact that unnest transformation should keep the original
490        // column name as is, to comply with group by and order by
491        let placeholder_column = Column::from_name(placeholder_name.clone());
492        let field = expr_in_unnest.to_field(self.input_schema)?.1;
493        let data_type = field.data_type();
494
495        match data_type {
496            DataType::Struct(inner_fields) => {
497                assert_or_internal_err!(
498                    struct_allowed,
499                    "unnest on struct can only be applied at the root level of select expression"
500                );
501                self.inner_projection_exprs
502                    .push(expr_in_unnest.clone().alias(placeholder_name.clone()));
503                self.columns_unnestings
504                    .insert(Column::from_name(placeholder_name.clone()), None);
505                Ok(get_struct_unnested_columns(&placeholder_name, inner_fields)
506                    .into_iter()
507                    .map(Expr::Column)
508                    .collect())
509            }
510            DataType::List(_)
511            | DataType::FixedSizeList(_, _)
512            | DataType::LargeList(_)
513            | DataType::ListView(_)
514            | DataType::LargeListView(_) => {
515                self.inner_projection_exprs
516                    .push(expr_in_unnest.clone().alias(placeholder_name.clone()));
517
518                let post_unnest_expr = col(post_unnest_name.clone()).alias(alias_name);
519                let list_unnesting = self
520                    .columns_unnestings
521                    .entry(placeholder_column)
522                    .or_insert(Some(vec![]));
523                let unnesting = ColumnUnnestList {
524                    output_column: Column::from_name(post_unnest_name),
525                    depth: level,
526                };
527                let list_unnestings = list_unnesting.as_mut().unwrap();
528                if !list_unnestings.contains(&unnesting) {
529                    list_unnestings.push(unnesting);
530                }
531                Ok(vec![post_unnest_expr])
532            }
533            _ => {
534                internal_err!("unnest on non-list or struct type is not supported")
535            }
536        }
537    }
538}
539
540impl TreeNodeRewriter for RecursiveUnnestRewriter<'_> {
541    type Node = Expr;
542
543    /// This downward traversal needs to keep track of:
544    /// - Whether or not some unnest expr has been visited from the top until the current node
545    /// - If some unnest expr has been visited, maintain a stack of such information, this
546    ///   is used to detect if some recursive unnest expr exists (e.g **unnest(unnest(unnest(3d column))))**
547    fn f_down(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
548        if let Expr::Unnest(ref unnest_expr) = expr {
549            let field = unnest_expr.expr.to_field(self.input_schema)?.1;
550            let data_type = field.data_type();
551            self.consecutive_unnest.push(Some(unnest_expr.clone()));
552            // if expr inside unnest is a struct, do not consider
553            // the next unnest as consecutive unnest (if any)
554            // meaning unnest(unnest(struct_arr_col)) can't
555            // be interpreted as unnest(struct_arr_col, depth:=2)
556            // but has to be split into multiple unnest logical plan instead
557            // a.k.a:
558            // - unnest(struct_col)
559            //      unnest(struct_arr_col) as struct_col
560
561            if let DataType::Struct(_) = data_type {
562                self.consecutive_unnest.push(None);
563            }
564            if self.top_most_unnest.is_none() {
565                self.top_most_unnest = Some(unnest_expr.clone());
566            }
567        } else {
568            self.consecutive_unnest.push(None);
569        }
570        Ok(Transformed::no(expr))
571    }
572
573    /// The rewriting only happens when the traversal has reached the top-most unnest expr
574    /// within a sequence of consecutive unnest exprs node
575    ///
576    /// For example an expr of **unnest(unnest(column1)) + unnest(unnest(unnest(column2)))**
577    /// ```text
578    ///                         ┌──────────────────┐
579    ///                         │    binaryexpr    │
580    ///                         │                  │
581    ///                         └──────────────────┘
582    ///                f_down  / /            │ │
583    ///                       / / f_up        │ │
584    ///                      / /        f_down│ │f_up
585    ///                  unnest               │ │
586    ///                                       │ │
587    ///       f_down  / / f_up(rewriting)     │ │
588    ///              / /
589    ///             / /                      unnest
590    ///         unnest
591    ///                           f_down  / / f_up(rewriting)
592    /// f_down / /f_up                   / /
593    ///       / /                       / /
594    ///      / /                    unnest
595    ///   column1
596    ///                     f_down / /f_up
597    ///                           / /
598    ///                          / /
599    ///                       column2
600    /// ```
601    fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
602        if let Expr::Unnest(ref traversing_unnest) = expr {
603            if traversing_unnest == self.top_most_unnest.as_ref().unwrap() {
604                self.top_most_unnest = None;
605            }
606            // Find inside consecutive_unnest, the sequence of continuous unnest exprs
607
608            // Get the latest consecutive unnest exprs
609            // and check if current upward traversal is the returning to the root expr
610            // for example given a expr `unnest(unnest(col))` then the traversal happens like:
611            // down(unnest) -> down(unnest) -> down(col) -> up(col) -> up(unnest) -> up(unnest)
612            // the result of such traversal is unnest(col, depth:=2)
613            let unnest_stack = self.get_latest_consecutive_unnest();
614
615            // This traversal has reached the top most unnest again
616            // e.g Unnest(top) -> Unnest(2nd) -> Column(bottom)
617            // -> Unnest(2nd) -> Unnest(top) a.k.a here
618            // Thus
619            // Unnest(Unnest(some_col)) is rewritten into Unnest(some_col, depth:=2)
620            if traversing_unnest == unnest_stack.last().unwrap() {
621                let most_inner = unnest_stack.first().unwrap();
622                let inner_expr = most_inner.expr.as_ref();
623                // unnest(unnest(struct_arr_col)) is not allow to be done recursively
624                // it needs to be split into multiple unnest logical plan
625                // unnest(struct_arr)
626                //  unnest(struct_arr_col) as struct_arr
627                // instead of unnest(struct_arr_col, depth = 2)
628
629                let unnest_recursion = unnest_stack.len();
630                let struct_allowed =
631                    self.is_at_struct_allowed_root(&expr) && unnest_recursion == 1;
632
633                let mut transformed_exprs = self.transform(
634                    unnest_recursion,
635                    expr.schema_name().to_string(),
636                    inner_expr,
637                    struct_allowed,
638                )?;
639                // Only set transformed_root_exprs for struct unnest (which returns multiple expressions).
640                // For list unnest (single expression), we let the normal rewrite handle the alias.
641                if struct_allowed && transformed_exprs.len() > 1 {
642                    self.transformed_root_exprs = Some(transformed_exprs.clone());
643                }
644                return Ok(Transformed::new(
645                    transformed_exprs.swap_remove(0),
646                    true,
647                    TreeNodeRecursion::Continue,
648                ));
649            }
650        } else {
651            self.consecutive_unnest.push(None);
652        }
653
654        // For column exprs that are not descendants of any unnest node
655        // retain their projection
656        // e.g given expr tree unnest(col_a) + col_b, we have to retain projection of col_b
657        // this condition can be checked by maintaining an Option<top most unnest>
658        if matches!(&expr, Expr::Column(_)) && self.top_most_unnest.is_none() {
659            self.inner_projection_exprs.push(expr.clone());
660        }
661
662        Ok(Transformed::no(expr))
663    }
664}
665
666/// An inner projection under construction that drops any expression whose
667/// [`Expr::schema_name`] is already present, so the finished projection has
668/// unique field names.
669///
670/// The unnest rewrite references inner projection fields *by schema name* (see
671/// [`rewrite_recursive_unnest_bottom_up`]), so the deduplication has to be by
672/// schema name too. Each pushed expression is rendered once and its name
673/// cached, making an `n` expression projection cost `n` renders rather than
674/// the `O(n^2)` renders a pairwise comparison would need.
675#[derive(Debug, Default)]
676pub(crate) struct DedupedProjection {
677    exprs: Vec<Expr>,
678    names: HashSet<String>,
679}
680
681impl DedupedProjection {
682    /// Pushes `expr` unless an expression with the same schema name is already
683    /// present.
684    fn push(&mut self, expr: Expr) {
685        if self.names.insert(expr.schema_name().to_string()) {
686            self.exprs.push(expr);
687        }
688    }
689
690    /// Like [`Self::push`], but returns the schema name of `expr`, which the
691    /// caller needs in order to reference the field from the outer projection.
692    fn push_returning_name(&mut self, expr: Expr) -> String {
693        let name = expr.schema_name().to_string();
694        if self.names.insert(name.clone()) {
695            self.exprs.push(expr);
696        }
697        name
698    }
699
700    /// The expressions pushed so far, in push order. Only the tests need to
701    /// inspect a projection while it is still being built; `select.rs` takes
702    /// the finished `Vec` via [`Self::into_exprs`].
703    #[cfg(test)]
704    fn exprs(&self) -> &[Expr] {
705        &self.exprs
706    }
707
708    pub(crate) fn into_exprs(self) -> Vec<Expr> {
709        self.exprs
710    }
711}
712/// The context is we want to rewrite unnest() into InnerProjection->Unnest->OuterProjection
713/// Given an expression which contains unnest expr as one of its children,
714/// Try transform depends on unnest type
715/// - For list column: unnest(col) with type list -> unnest(col) with type list::item
716/// - For struct column: unnest(struct(field1, field2)) -> unnest(struct).field1, unnest(struct).field2
717///
718/// The transformed exprs will be used in the outer projection
719/// If along the path from root to bottom, there are multiple unnest expressions, the transformation
720/// is done only for the bottom expression
721pub(crate) fn rewrite_recursive_unnest_bottom_up(
722    input: &LogicalPlan,
723    unnest_placeholder_columns: &mut IndexMap<Column, Option<Vec<ColumnUnnestList>>>,
724    inner_projection_exprs: &mut DedupedProjection,
725    original_expr: &Expr,
726) -> Result<Vec<Expr>> {
727    let mut rewriter = RecursiveUnnestRewriter {
728        input_schema: input.schema(),
729        root_expr: original_expr,
730        top_most_unnest: None,
731        consecutive_unnest: vec![],
732        inner_projection_exprs,
733        columns_unnestings: unnest_placeholder_columns,
734        transformed_root_exprs: None,
735    };
736
737    // This transformation is only done for list unnest
738    // struct unnest is done at the root level, and at the later stage
739    // because the syntax of TreeNode only support transform into 1 Expr, while
740    // Unnest struct will be transformed into multiple Exprs
741    // TODO: This can be resolved after this issue is resolved: https://github.com/apache/datafusion/issues/10102
742    //
743    // The transformation looks like:
744    // - unnest(array_col) will be transformed into Column("unnest_place_holder(array_col)")
745    // - unnest(array_col) + 1 will be transformed into Column("unnest_place_holder(array_col) + 1")
746    let Transformed {
747        data: transformed_expr,
748        transformed,
749        tnr: _,
750    } = original_expr.clone().rewrite(&mut rewriter)?;
751
752    if !transformed {
753        // TODO: remove the next line after `Expr::Wildcard` is removed
754        #[expect(deprecated)]
755        if matches!(&transformed_expr, Expr::Column(_))
756            || matches!(&transformed_expr, Expr::Wildcard { .. })
757        {
758            inner_projection_exprs.push(transformed_expr.clone());
759            Ok(vec![transformed_expr])
760        } else {
761            // We need to evaluate the expr in the inner projection,
762            // outer projection just select its name
763            let column_name =
764                inner_projection_exprs.push_returning_name(transformed_expr);
765            Ok(vec![Expr::Column(Column::from_name(column_name))])
766        }
767    } else {
768        if let Some(transformed_root_exprs) = rewriter.transformed_root_exprs {
769            return Ok(transformed_root_exprs);
770        }
771        Ok(vec![transformed_expr])
772    }
773}
774
775#[cfg(test)]
776mod tests {
777    use std::{ops::Add, sync::Arc};
778
779    use arrow::datatypes::{DataType as ArrowDataType, Field, Fields, Schema};
780    use datafusion_common::{Column, DFSchema, Result};
781    use datafusion_expr::{
782        ColumnUnnestList, EmptyRelation, LogicalPlan, cast, col, lit, try_cast, unnest,
783    };
784    use datafusion_functions::core::expr_ext::FieldAccessor;
785    use datafusion_functions_aggregate::expr_fn::count;
786
787    use crate::utils::{
788        DedupedProjection, resolve_positions_to_exprs, rewrite_recursive_unnest_bottom_up,
789    };
790    use indexmap::IndexMap;
791
792    /// [`DedupedProjection`] deduplicates on [`Expr::schema_name`], which
793    /// hides `CAST`/`TRY_CAST` at *every* depth and hides the expression behind
794    /// an alias entirely.
795    #[test]
796    fn test_deduped_projection() {
797        let mut projection = DedupedProjection::default();
798        projection.push(col("a"));
799        projection.push(col("a"));
800        projection.push(col("t.a"));
801        projection.push(col("x").alias("n"));
802        // same alias name as the previous alias, different inner expr
803        projection.push(col("y").alias("n"));
804        // a cast renders as its input, which is already present
805        projection.push(cast(col("a"), ArrowDataType::Int64));
806        projection.push(try_cast(col("a"), ArrowDataType::Int64));
807        projection.push(col("a").add(lit(1)));
808        projection.push(col("a").add(lit(1)));
809        // casts are hidden at every depth, so these render as `a + Int32(1)`
810        // too and must not be pushed again
811        projection.push(cast(col("a"), ArrowDataType::Int64).add(lit(1)));
812        projection.push(col("a").add(cast(lit(1), ArrowDataType::Int64)));
813        projection.push(try_cast(col("a"), ArrowDataType::Int64).add(lit(1)));
814        projection.push(col("a").add(lit(2)));
815
816        let names: Vec<String> = projection
817            .exprs()
818            .iter()
819            .map(|e| e.schema_name().to_string())
820            .collect();
821        assert_eq!(names, vec!["a", "t.a", "n", "a + Int32(1)", "a + Int32(2)"]);
822    }
823
824    /// The name a caller gets back from `push_returning_name` must be the
825    /// schema name of the pushed expression, whether or not it was retained,
826    /// since the outer projection references the inner field by that name.
827    #[test]
828    fn test_deduped_projection_push_returning_name() {
829        let mut projection = DedupedProjection::default();
830        assert_eq!(
831            projection.push_returning_name(col("a").add(lit(1))),
832            "a + Int32(1)"
833        );
834        // dropped as a duplicate, but the name is still the one to reference
835        assert_eq!(
836            projection
837                .push_returning_name(cast(col("a"), ArrowDataType::Int64).add(lit(1))),
838            "a + Int32(1)"
839        );
840        assert_eq!(projection.exprs().len(), 1);
841    }
842
843    fn column_unnests_eq(
844        l: Vec<&str>,
845        r: &IndexMap<Column, Option<Vec<ColumnUnnestList>>>,
846    ) {
847        let r_formatted: Vec<String> = r
848            .iter()
849            .map(|i| match i.1 {
850                None => format!("{}", i.0),
851                Some(vec) => format!(
852                    "{}=>[{}]",
853                    i.0,
854                    vec.iter()
855                        .map(|i| format!("{i}"))
856                        .collect::<Vec<String>>()
857                        .join(", ")
858                ),
859            })
860            .collect();
861        let l_formatted: Vec<String> = l.iter().map(|i| (*i).to_string()).collect();
862        assert_eq!(l_formatted, r_formatted);
863    }
864
865    #[test]
866    fn test_transform_bottom_unnest_recursive() -> Result<()> {
867        let schema = Schema::new(vec![
868            Field::new(
869                "3d_col",
870                ArrowDataType::List(Arc::new(Field::new(
871                    "2d_col",
872                    ArrowDataType::List(Arc::new(Field::new(
873                        "elements",
874                        ArrowDataType::Int64,
875                        true,
876                    ))),
877                    true,
878                ))),
879                true,
880            ),
881            Field::new("i64_col", ArrowDataType::Int64, true),
882        ]);
883
884        let dfschema = DFSchema::try_from(schema)?;
885
886        let input = LogicalPlan::EmptyRelation(EmptyRelation {
887            produce_one_row: false,
888            schema: Arc::new(dfschema),
889        });
890
891        let mut unnest_placeholder_columns = IndexMap::new();
892        let mut inner_projection_exprs = DedupedProjection::default();
893
894        // unnest(unnest(3d_col)) + unnest(unnest(3d_col))
895        let original_expr = unnest(unnest(col("3d_col")))
896            .add(unnest(unnest(col("3d_col"))))
897            .add(col("i64_col"));
898        let transformed_exprs = rewrite_recursive_unnest_bottom_up(
899            &input,
900            &mut unnest_placeholder_columns,
901            &mut inner_projection_exprs,
902            &original_expr,
903        )?;
904        // Only the bottom most unnest exprs are transformed
905        assert_eq!(
906            transformed_exprs,
907            vec![
908                col("__unnest_placeholder(3d_col,depth=2)")
909                    .alias("UNNEST(UNNEST(3d_col))")
910                    .add(
911                        col("__unnest_placeholder(3d_col,depth=2)")
912                            .alias("UNNEST(UNNEST(3d_col))")
913                    )
914                    .add(col("i64_col"))
915            ]
916        );
917        column_unnests_eq(
918            vec![
919                "__unnest_placeholder(3d_col)=>[__unnest_placeholder(3d_col,depth=2)|depth=2]",
920            ],
921            &unnest_placeholder_columns,
922        );
923
924        // Still reference struct_col in original schema but with alias,
925        // to avoid colliding with the projection on the column itself if any
926        assert_eq!(
927            inner_projection_exprs.exprs().to_vec(),
928            vec![
929                col("3d_col").alias("__unnest_placeholder(3d_col)"),
930                col("i64_col")
931            ]
932        );
933
934        // unnest(3d_col) as 2d_col
935        let original_expr_2 = unnest(col("3d_col")).alias("2d_col");
936        let transformed_exprs = rewrite_recursive_unnest_bottom_up(
937            &input,
938            &mut unnest_placeholder_columns,
939            &mut inner_projection_exprs,
940            &original_expr_2,
941        )?;
942
943        assert_eq!(
944            transformed_exprs,
945            vec![
946                (col("__unnest_placeholder(3d_col,depth=1)").alias("UNNEST(3d_col)"))
947                    .alias("2d_col")
948            ]
949        );
950        column_unnests_eq(
951            vec![
952                "__unnest_placeholder(3d_col)=>[__unnest_placeholder(3d_col,depth=2)|depth=2, __unnest_placeholder(3d_col,depth=1)|depth=1]",
953            ],
954            &unnest_placeholder_columns,
955        );
956        // Still reference struct_col in original schema but with alias,
957        // to avoid colliding with the projection on the column itself if any
958        assert_eq!(
959            inner_projection_exprs.exprs().to_vec(),
960            vec![
961                col("3d_col").alias("__unnest_placeholder(3d_col)"),
962                col("i64_col")
963            ]
964        );
965
966        Ok(())
967    }
968
969    #[test]
970    fn test_transform_bottom_unnest() -> Result<()> {
971        let schema = Schema::new(vec![
972            Field::new(
973                "struct_col",
974                ArrowDataType::Struct(Fields::from(vec![
975                    Field::new("field1", ArrowDataType::Int32, false),
976                    Field::new("field2", ArrowDataType::Int32, false),
977                ])),
978                false,
979            ),
980            Field::new(
981                "array_col",
982                ArrowDataType::List(Arc::new(Field::new_list_field(
983                    ArrowDataType::Int64,
984                    true,
985                ))),
986                true,
987            ),
988            Field::new("int_col", ArrowDataType::Int32, false),
989        ]);
990
991        let dfschema = DFSchema::try_from(schema)?;
992
993        let input = LogicalPlan::EmptyRelation(EmptyRelation {
994            produce_one_row: false,
995            schema: Arc::new(dfschema),
996        });
997
998        let mut unnest_placeholder_columns = IndexMap::new();
999        let mut inner_projection_exprs = DedupedProjection::default();
1000
1001        // unnest(struct_col)
1002        let original_expr = unnest(col("struct_col"));
1003        let transformed_exprs = rewrite_recursive_unnest_bottom_up(
1004            &input,
1005            &mut unnest_placeholder_columns,
1006            &mut inner_projection_exprs,
1007            &original_expr,
1008        )?;
1009        assert_eq!(
1010            transformed_exprs,
1011            vec![
1012                col("__unnest_placeholder(struct_col).field1"),
1013                col("__unnest_placeholder(struct_col).field2"),
1014            ]
1015        );
1016        column_unnests_eq(
1017            vec!["__unnest_placeholder(struct_col)"],
1018            &unnest_placeholder_columns,
1019        );
1020        // Still reference struct_col in original schema but with alias,
1021        // to avoid colliding with the projection on the column itself if any
1022        assert_eq!(
1023            inner_projection_exprs.exprs().to_vec(),
1024            vec![col("struct_col").alias("__unnest_placeholder(struct_col)"),]
1025        );
1026
1027        // unnest(array_col) + 1
1028        let original_expr = unnest(col("array_col")).add(lit(1i64));
1029        let transformed_exprs = rewrite_recursive_unnest_bottom_up(
1030            &input,
1031            &mut unnest_placeholder_columns,
1032            &mut inner_projection_exprs,
1033            &original_expr,
1034        )?;
1035        column_unnests_eq(
1036            vec![
1037                "__unnest_placeholder(struct_col)",
1038                "__unnest_placeholder(array_col)=>[__unnest_placeholder(array_col,depth=1)|depth=1]",
1039            ],
1040            &unnest_placeholder_columns,
1041        );
1042        // Only transform the unnest children
1043        assert_eq!(
1044            transformed_exprs,
1045            vec![
1046                col("__unnest_placeholder(array_col,depth=1)")
1047                    .alias("UNNEST(array_col)")
1048                    .add(lit(1i64))
1049            ]
1050        );
1051
1052        // Keep appending to the current vector
1053        // Still reference array_col in original schema but with alias,
1054        // to avoid colliding with the projection on the column itself if any
1055        assert_eq!(
1056            inner_projection_exprs.exprs().to_vec(),
1057            vec![
1058                col("struct_col").alias("__unnest_placeholder(struct_col)"),
1059                col("array_col").alias("__unnest_placeholder(array_col)")
1060            ]
1061        );
1062
1063        Ok(())
1064    }
1065
1066    // Unnest -> field access -> unnest
1067    #[test]
1068    fn test_transform_non_consecutive_unnests() -> Result<()> {
1069        // List of struct
1070        // [struct{'subfield1':list(i64), 'subfield2':list(utf8)}]
1071        let schema = Schema::new(vec![
1072            Field::new(
1073                "struct_list",
1074                ArrowDataType::List(Arc::new(Field::new(
1075                    "element",
1076                    ArrowDataType::Struct(Fields::from(vec![
1077                        Field::new(
1078                            // list of i64
1079                            "subfield1",
1080                            ArrowDataType::List(Arc::new(Field::new(
1081                                "i64_element",
1082                                ArrowDataType::Int64,
1083                                true,
1084                            ))),
1085                            true,
1086                        ),
1087                        Field::new(
1088                            // list of utf8
1089                            "subfield2",
1090                            ArrowDataType::List(Arc::new(Field::new(
1091                                "utf8_element",
1092                                ArrowDataType::Utf8,
1093                                true,
1094                            ))),
1095                            true,
1096                        ),
1097                    ])),
1098                    true,
1099                ))),
1100                true,
1101            ),
1102            Field::new("int_col", ArrowDataType::Int32, false),
1103        ]);
1104
1105        let dfschema = DFSchema::try_from(schema)?;
1106
1107        let input = LogicalPlan::EmptyRelation(EmptyRelation {
1108            produce_one_row: false,
1109            schema: Arc::new(dfschema),
1110        });
1111
1112        let mut unnest_placeholder_columns = IndexMap::new();
1113        let mut inner_projection_exprs = DedupedProjection::default();
1114
1115        // An expr with multiple unnest
1116        let select_expr1 = unnest(unnest(col("struct_list")).field("subfield1"));
1117        let transformed_exprs = rewrite_recursive_unnest_bottom_up(
1118            &input,
1119            &mut unnest_placeholder_columns,
1120            &mut inner_projection_exprs,
1121            &select_expr1,
1122        )?;
1123        // Only the inner most/ bottom most unnest is transformed
1124        assert_eq!(
1125            transformed_exprs,
1126            vec![unnest(
1127                col("__unnest_placeholder(struct_list,depth=1)")
1128                    .alias("UNNEST(struct_list)")
1129                    .field("subfield1")
1130            )]
1131        );
1132
1133        column_unnests_eq(
1134            vec![
1135                "__unnest_placeholder(struct_list)=>[__unnest_placeholder(struct_list,depth=1)|depth=1]",
1136            ],
1137            &unnest_placeholder_columns,
1138        );
1139
1140        assert_eq!(
1141            inner_projection_exprs.exprs().to_vec(),
1142            vec![col("struct_list").alias("__unnest_placeholder(struct_list)")]
1143        );
1144
1145        // continue rewrite another expr in select
1146        let select_expr2 = unnest(unnest(col("struct_list")).field("subfield2"));
1147        let transformed_exprs = rewrite_recursive_unnest_bottom_up(
1148            &input,
1149            &mut unnest_placeholder_columns,
1150            &mut inner_projection_exprs,
1151            &select_expr2,
1152        )?;
1153        // Only the inner most/ bottom most unnest is transformed
1154        assert_eq!(
1155            transformed_exprs,
1156            vec![unnest(
1157                col("__unnest_placeholder(struct_list,depth=1)")
1158                    .alias("UNNEST(struct_list)")
1159                    .field("subfield2")
1160            )]
1161        );
1162
1163        // unnest place holder columns remain the same
1164        // because expr1 and expr2 derive from the same unnest result
1165        column_unnests_eq(
1166            vec![
1167                "__unnest_placeholder(struct_list)=>[__unnest_placeholder(struct_list,depth=1)|depth=1]",
1168            ],
1169            &unnest_placeholder_columns,
1170        );
1171
1172        assert_eq!(
1173            inner_projection_exprs.exprs().to_vec(),
1174            vec![col("struct_list").alias("__unnest_placeholder(struct_list)")]
1175        );
1176
1177        Ok(())
1178    }
1179
1180    #[test]
1181    fn test_resolve_positions_to_exprs() -> Result<()> {
1182        let select_exprs = vec![col("c1"), col("c2"), count(lit(1))];
1183
1184        // Assert 1 resolved as first column in select list
1185        let resolved = resolve_positions_to_exprs(lit(1i64), &select_exprs)?;
1186        assert_eq!(resolved, col("c1"));
1187
1188        // Assert error if index out of select clause bounds
1189        let resolved = resolve_positions_to_exprs(lit(-1i64), &select_exprs);
1190        assert!(resolved.is_err_and(|e| e.message().contains(
1191            "Cannot find column with position -1 in SELECT clause. Valid columns: 1 to 3"
1192        )));
1193
1194        let resolved = resolve_positions_to_exprs(lit(5i64), &select_exprs);
1195        assert!(resolved.is_err_and(|e| e.message().contains(
1196            "Cannot find column with position 5 in SELECT clause. Valid columns: 1 to 3"
1197        )));
1198
1199        // Assert expression returned as-is
1200        let resolved = resolve_positions_to_exprs(lit("text"), &select_exprs)?;
1201        assert_eq!(resolved, lit("text"));
1202
1203        let resolved = resolve_positions_to_exprs(col("fake"), &select_exprs)?;
1204        assert_eq!(resolved, col("fake"));
1205
1206        Ok(())
1207    }
1208}