Skip to main content

datafusion_sql/unparser/
plan.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use super::{
6    Unparser,
7    ast::{
8        BuilderError, DerivedRelationBuilder, QueryBuilder, RelationBuilder,
9        SelectBuilder, TableRelationBuilder, TableWithJoinsBuilder,
10    },
11    rewrite::{
12        TableAliasRewriter, inject_column_aliases_into_subquery, normalize_union_schema,
13        rewrite_plan_for_sort_on_non_projected_fields,
14        subquery_alias_inner_query_and_columns,
15    },
16    utils::{
17        find_agg_node_within_select, find_unnest_node_within_select,
18        find_window_nodes_within_select, try_transform_to_simple_table_scan_with_filters,
19        unproject_sort_expr, unproject_unnest_expr,
20        unproject_unnest_expr_as_flatten_value, unproject_window_exprs,
21    },
22};
23use crate::unparser::utils::{find_unnest_node_until_relation, unproject_agg_exprs};
24use crate::unparser::{
25    ast::FlattenRelationBuilder, ast::UnnestRelationBuilder, rewrite::rewrite_qualify,
26};
27use crate::unparser::{
28    extension_unparser::{UnparseToStatementResult, UnparseWithinStatementResult},
29    utils::filter_depends_on_input_alias,
30};
31use crate::utils::UNNEST_PLACEHOLDER;
32use datafusion_common::{
33    Column, DFSchema, DataFusionError, Result, ScalarValue, TableReference,
34    assert_or_internal_err, internal_datafusion_err, internal_err, not_impl_err,
35    tree_node::{Transformed, TransformedResult, TreeNode, TreeNodeRecursion},
36    utils::combine_limit,
37};
38use datafusion_expr::expr::{OUTER_REFERENCE_COLUMN_PREFIX, UNNEST_COLUMN_PREFIX};
39use datafusion_expr::{
40    Aggregate, AsOfJoin, BinaryExpr, Distinct, Expr, FetchType, JoinConstraint, JoinType,
41    LogicalPlan, LogicalPlanBuilder, Operator, Projection, SkipType, Sort, SortExpr,
42    TableScan, Unnest, UserDefinedLogicalNode, Window, expr::Alias,
43};
44use sqlparser::ast::{self, Ident, OrderByKind, SetExpr, TableAliasColumnDef};
45use std::{collections::HashSet, sync::Arc, vec};
46
47/// Convert a DataFusion [`LogicalPlan`] to [`ast::Statement`]
48///
49/// This function is the opposite of [`SqlToRel::sql_statement_to_plan`] and can
50/// be used to, among other things, to convert `LogicalPlan`s to SQL strings.
51///
52/// # Errors
53///
54/// This function returns an error if the plan cannot be converted to SQL.
55///
56/// # See Also
57///
58/// * [`expr_to_sql`] for converting [`Expr`], a single expression to SQL
59///
60/// # Example
61/// ```
62/// use arrow::datatypes::{DataType, Field, Schema};
63/// use datafusion_expr::{col, logical_plan::table_scan};
64/// use datafusion_sql::unparser::plan_to_sql;
65/// let schema = Schema::new(vec![
66///     Field::new("id", DataType::Utf8, false),
67///     Field::new("value", DataType::Utf8, false),
68/// ]);
69/// // Scan 'table' and select columns 'id' and 'value'
70/// let plan = table_scan(Some("table"), &schema, None)
71///     .unwrap()
72///     .project(vec![col("id"), col("value")])
73///     .unwrap()
74///     .build()
75///     .unwrap();
76/// // convert to AST
77/// let sql = plan_to_sql(&plan).unwrap();
78/// // use the Display impl to convert to SQL text
79/// assert_eq!(
80///     sql.to_string(),
81///     "SELECT \"table\".id, \"table\".\"value\" FROM \"table\""
82/// )
83/// ```
84///
85/// [`SqlToRel::sql_statement_to_plan`]: crate::planner::SqlToRel::sql_statement_to_plan
86/// [`expr_to_sql`]: crate::unparser::expr_to_sql
87pub fn plan_to_sql(plan: &LogicalPlan) -> Result<ast::Statement> {
88    let unparser = Unparser::default();
89    unparser.plan_to_sql(plan)
90}
91
92/// Aggregate-expression scope for one rendered SELECT block.
93///
94/// When an aggregate's input is itself emitted as a derived subquery (a
95/// projection sits between the aggregate and its relation), the input columns
96/// are only reachable by that derived table's output names. Base-table
97/// qualifiers like `t.col` name a relation that is out of scope above the
98/// boundary, so emitting them produces SQL a strict engine rejects.
99///
100/// Every clause that renders an aggregate expression (SELECT / GROUP BY /
101/// HAVING / QUALIFY / ORDER BY) has to apply the same rule. Detect the
102/// boundary once here and reuse it, so the clauses can't drift apart (which is
103/// how earlier fixes left some clauses correct and others not).
104struct UnparserAggScope<'a> {
105    agg: &'a Aggregate,
106    /// `agg.input` renders as a derived projection, so out-of-scope qualifiers
107    /// must be stripped from expressions in this scope.
108    input_is_derived_projection: bool,
109}
110
111impl<'a> UnparserAggScope<'a> {
112    fn new(agg: &'a Aggregate) -> Self {
113        Self {
114            agg,
115            input_is_derived_projection: Unparser::contains_projection_before_relation(
116                agg.input.as_ref(),
117            ),
118        }
119    }
120
121    /// Prepare a projected column or predicate that still references the
122    /// aggregate by its output columns: unproject it back onto the aggregate
123    /// (and `windows`) expressions, then normalize it for this scope.
124    fn prepare(&self, expr: Expr, windows: Option<&[&Window]>) -> Result<Expr> {
125        self.normalize(unproject_agg_exprs(expr, self.agg, windows)?)
126    }
127
128    /// Normalize an expression that is already in aggregate form (group / aggr
129    /// exprs, or an unprojected sort expr): strip the qualifiers that fall out
130    /// of scope once the input is a derived projection. No-op otherwise.
131    fn normalize(&self, expr: Expr) -> Result<Expr> {
132        if self.input_is_derived_projection {
133            Unparser::strip_column_qualifiers_for_schema(
134                expr,
135                self.agg.input.schema().as_ref(),
136            )
137        } else {
138            Ok(expr)
139        }
140    }
141
142    /// Unproject a sort expression onto this aggregate, then normalize it so
143    /// ORDER BY uses the same scope as the other clauses.
144    fn prepare_sort_expr(
145        &self,
146        sort_expr: SortExpr,
147        input: &LogicalPlan,
148    ) -> Result<SortExpr> {
149        let mut sort_expr = unproject_sort_expr(sort_expr, Some(self.agg), input)?;
150        sort_expr.expr = self.normalize(sort_expr.expr)?;
151        Ok(sort_expr)
152    }
153}
154
155#[derive(Clone, Copy)]
156struct DerivedInputScope<'a> {
157    alias: &'static str,
158    schema: &'a DFSchema,
159}
160
161impl Unparser<'_> {
162    pub fn plan_to_sql(&self, plan: &LogicalPlan) -> Result<ast::Statement> {
163        let mut plan = normalize_union_schema(plan)?;
164        if !self.dialect.supports_qualify() {
165            plan = rewrite_qualify(plan)?;
166        }
167
168        match plan {
169            LogicalPlan::Projection(_)
170            | LogicalPlan::Filter(_)
171            | LogicalPlan::Window(_)
172            | LogicalPlan::Aggregate(_)
173            | LogicalPlan::Sort(_)
174            | LogicalPlan::Join(_)
175            | LogicalPlan::AsOfJoin(_)
176            | LogicalPlan::Repartition(_)
177            | LogicalPlan::Union(_)
178            | LogicalPlan::TableScan(_)
179            | LogicalPlan::EmptyRelation(_)
180            | LogicalPlan::Subquery(_)
181            | LogicalPlan::SubqueryAlias(_)
182            | LogicalPlan::Limit(_)
183            | LogicalPlan::Statement(_)
184            | LogicalPlan::Values(_)
185            | LogicalPlan::Distinct(_) => self.select_to_sql_statement(&plan),
186            LogicalPlan::Dml(_) => self.dml_to_sql(&plan),
187            LogicalPlan::Extension(extension) => {
188                self.extension_to_statement(extension.node.as_ref())
189            }
190            LogicalPlan::Explain(_)
191            | LogicalPlan::Analyze(_)
192            | LogicalPlan::Ddl(_)
193            | LogicalPlan::Copy(_)
194            | LogicalPlan::Show(_)
195            | LogicalPlan::RecursiveQuery(_)
196            | LogicalPlan::Unnest(_) => not_impl_err!("Unsupported plan: {plan:?}"),
197            LogicalPlan::MaterializedCte(_) => {
198                not_impl_err!("Unparsing a MATERIALIZED CTE is not supported: {plan:?}")
199            }
200        }
201    }
202
203    /// Try to unparse a [UserDefinedLogicalNode] to a SQL statement.
204    /// If multiple unparsers are registered for the same [UserDefinedLogicalNode],
205    /// the first unparsing result will be returned.
206    fn extension_to_statement(
207        &self,
208        node: &dyn UserDefinedLogicalNode,
209    ) -> Result<ast::Statement> {
210        let mut statement = None;
211        for unparser in &self.extension_unparsers {
212            match unparser.unparse_to_statement(node, self)? {
213                UnparseToStatementResult::Modified(stmt) => {
214                    statement = Some(stmt);
215                    break;
216                }
217                UnparseToStatementResult::Unmodified => {}
218            }
219        }
220        if let Some(statement) = statement {
221            Ok(statement)
222        } else {
223            not_impl_err!("Unsupported extension node: {node:?}")
224        }
225    }
226
227    /// Try to unparse a [UserDefinedLogicalNode] to a SQL statement.
228    /// If multiple unparsers are registered for the same [UserDefinedLogicalNode],
229    /// the first unparser supporting the node will be used.
230    fn extension_to_sql(
231        &self,
232        node: &dyn UserDefinedLogicalNode,
233        query: &mut Option<&mut QueryBuilder>,
234        select: &mut Option<&mut SelectBuilder>,
235        relation: &mut Option<&mut RelationBuilder>,
236    ) -> Result<()> {
237        for unparser in &self.extension_unparsers {
238            match unparser.unparse(node, self, query, select, relation)? {
239                UnparseWithinStatementResult::Modified => return Ok(()),
240                UnparseWithinStatementResult::Unmodified => {}
241            }
242        }
243        not_impl_err!("Unsupported extension node: {node:?}")
244    }
245
246    fn select_to_sql_statement(&self, plan: &LogicalPlan) -> Result<ast::Statement> {
247        let mut query_builder = Some(QueryBuilder::default());
248
249        let body = self.select_to_sql_expr(plan, &mut query_builder)?;
250
251        let query = query_builder.unwrap().body(Box::new(body)).build()?;
252
253        Ok(ast::Statement::Query(Box::new(query)))
254    }
255
256    fn select_to_sql_expr(
257        &self,
258        plan: &LogicalPlan,
259        query: &mut Option<QueryBuilder>,
260    ) -> Result<SetExpr> {
261        let mut select_builder = SelectBuilder::default();
262        select_builder.push_from(TableWithJoinsBuilder::default());
263        let mut relation_builder = RelationBuilder::default();
264        self.select_to_sql_recursively(
265            plan,
266            query,
267            &mut select_builder,
268            &mut relation_builder,
269        )?;
270
271        // If we were able to construct a full body (i.e. UNION ALL), return it
272        if let Some(body) = query.as_mut().and_then(|q| q.take_body()) {
273            return Ok(*body);
274        }
275
276        // If no projection is set, add a wildcard projection to the select
277        // which will be translated to `SELECT *` in the SQL statement
278        if !select_builder.already_projected() {
279            select_builder.projection(vec![ast::SelectItem::Wildcard(
280                ast::WildcardAdditionalOptions::default(),
281            )]);
282        }
283
284        let mut twj = select_builder.pop_from().unwrap();
285        twj.relation(relation_builder);
286        select_builder.push_from(twj);
287
288        Ok(SetExpr::Select(Box::new(select_builder.build()?)))
289    }
290
291    /// Reconstructs a SELECT SQL statement from a logical plan by
292    /// unprojecting column expressions found in a [Projection] node. This
293    /// requires scanning the plan tree for relevant Aggregate and Window
294    /// nodes and matching column expressions to the appropriate agg or
295    /// window expressions.
296    ///
297    /// `fully_absorbed` reports whether the Projection arm was able to
298    /// absorb every `Sort`/`Limit` node between this Projection and the
299    /// Aggregate/Window into the current SELECT. When `false`, the
300    /// Aggregate/Window will end up in a derived subquery, so we fall
301    /// back to passthrough column references that resolve against that
302    /// subquery's output instead of unprojecting onto the original
303    /// aggregate expressions.
304    ///
305    /// Returns `true` if an Aggregate node was found and claimed for this
306    /// SELECT.
307    fn reconstruct_select_statement(
308        &self,
309        plan: &LogicalPlan,
310        p: &Projection,
311        select: &mut SelectBuilder,
312        fully_absorbed: bool,
313    ) -> Result<bool> {
314        let mut exprs = p.expr.clone();
315
316        // If an Unnest node is found within the select, find and unproject the unnest column
317        let flatten_alias = select.current_flatten_alias();
318        if let Some(unnest) = find_unnest_node_within_select(plan) {
319            if let Some(ref alias) = flatten_alias {
320                exprs = exprs
321                    .into_iter()
322                    .map(|e| unproject_unnest_expr_as_flatten_value(e, unnest, alias))
323                    .collect::<Result<Vec<_>>>()?;
324            } else {
325                exprs = exprs
326                    .into_iter()
327                    .map(|e| unproject_unnest_expr(e, unnest))
328                    .collect::<Result<Vec<_>>>()?;
329            }
330        }
331
332        // Rewrite column references that point to FLATTEN table aliases:
333        // in Snowflake, FLATTEN output is accessed via .VALUE, not the
334        // original column name.
335        if !select.flatten_table_aliases_empty() {
336            exprs = exprs
337                .into_iter()
338                .map(|e| {
339                    e.transform(|expr| {
340                        if let Expr::Column(ref col) = expr
341                            && let Some(ref relation) = col.relation
342                            && select.is_flatten_table_alias(relation.table())
343                        {
344                            return Ok(Transformed::yes(Expr::Column(Column::new(
345                                Some(relation.clone()),
346                                "VALUE",
347                            ))));
348                        }
349                        Ok(Transformed::no(expr))
350                    })
351                    .map(|t| t.data)
352                })
353                .collect::<Result<Vec<_>>>()?;
354        }
355
356        // When some Sort/Limit nodes between this Projection and the
357        // Aggregate/Window couldn't be absorbed into the current SELECT,
358        // the Aggregate/Window will live inside a derived subquery. In
359        // that case we use the passthrough projection path — column refs
360        // resolve against the derived subquery's output columns instead
361        // of being unprojected onto the original aggregate/window
362        // expressions.
363        let agg = if fully_absorbed {
364            find_agg_node_within_select(plan, true)
365        } else {
366            None
367        };
368        let window = if fully_absorbed {
369            find_window_nodes_within_select(plan, None, true)
370        } else {
371            None
372        };
373        match (agg, window) {
374            (Some(agg), window) => {
375                let window_option = window.as_deref();
376                let unparser_agg_scope = UnparserAggScope::new(agg);
377                let items = exprs
378                    .into_iter()
379                    .map(|proj_expr| {
380                        let unproj =
381                            unparser_agg_scope.prepare(proj_expr, window_option)?;
382                        self.select_item_to_sql(&unproj)
383                    })
384                    .collect::<Result<Vec<_>>>()?;
385
386                select.projection(items);
387                select.group_by(ast::GroupByExpr::Expressions(
388                    agg.group_expr
389                        .iter()
390                        .cloned()
391                        .map(|expr| {
392                            self.expr_to_sql(&unparser_agg_scope.normalize(expr)?)
393                        })
394                        .collect::<Result<Vec<_>>>()?,
395                    vec![],
396                ));
397                Ok(true)
398            }
399            (None, Some(window)) => {
400                let items = exprs
401                    .into_iter()
402                    .map(|proj_expr| {
403                        let unproj = unproject_window_exprs(proj_expr, &window)?;
404                        self.select_item_to_sql(&unproj)
405                    })
406                    .collect::<Result<Vec<_>>>()?;
407
408                select.projection(items);
409                Ok(false)
410            }
411            _ => {
412                let items = exprs
413                    .iter()
414                    .map(|e| {
415                        // After unproject_unnest_expr_as_flatten_value, an
416                        // internal UNNEST display-name alias may still wrap
417                        // the rewritten _unnest.VALUE column. Replace it
418                        // with the bare FLATTEN VALUE select item.
419                        if let Some(ref alias) = flatten_alias
420                            && Self::has_internal_unnest_alias(e)
421                        {
422                            return Ok(self.build_flatten_value_select_item(alias, None));
423                        }
424                        self.select_item_to_sql(e)
425                    })
426                    .collect::<Result<Vec<_>>>()?;
427                select.projection(items);
428                Ok(false)
429            }
430        }
431    }
432
433    fn contains_projection_before_relation(plan: &LogicalPlan) -> bool {
434        match plan {
435            LogicalPlan::Projection(_) => true,
436            LogicalPlan::TableScan(_)
437            | LogicalPlan::Subquery(_)
438            | LogicalPlan::SubqueryAlias(_)
439            | LogicalPlan::Join(_)
440            | LogicalPlan::EmptyRelation(_)
441            | LogicalPlan::Values(_) => false,
442            _ => {
443                let inputs = plan.inputs();
444                matches!(
445                    inputs.as_slice(),
446                    [input] if Self::contains_projection_before_relation(input)
447                )
448            }
449        }
450    }
451
452    /// Return the alias recursion would assign when `plan` must become a
453    /// derived relation below an already rendered projection.
454    fn derived_input_alias(plan: &LogicalPlan) -> Option<&'static str> {
455        match plan {
456            LogicalPlan::Projection(_) => Some("derived_projection"),
457            LogicalPlan::Limit(_) => Some("derived_limit"),
458            LogicalPlan::Sort(_) => Some("derived_sort"),
459            LogicalPlan::Distinct(_) => Some("derived_distinct"),
460            LogicalPlan::Filter(filter) => {
461                Self::derived_input_alias(filter.input.as_ref())
462            }
463            LogicalPlan::Repartition(repartition) => {
464                Self::derived_input_alias(repartition.input.as_ref())
465            }
466            _ => None,
467        }
468    }
469
470    fn derived_input_scope<'a>(
471        plan: &'a LogicalPlan,
472        select: &SelectBuilder,
473    ) -> Option<DerivedInputScope<'a>> {
474        if select.inside_subquery_alias() {
475            return None;
476        }
477
478        if select.already_projected()
479            && find_unnest_node_within_select(plan).is_none()
480            && let Some(alias) = Self::derived_input_alias(plan)
481        {
482            return Some(DerivedInputScope {
483                alias,
484                schema: plan.schema().as_ref(),
485            });
486        }
487
488        match plan {
489            LogicalPlan::Projection(projection) => {
490                let alias = Self::derived_input_alias(projection.input.as_ref())?;
491                let qualified_projection = projection.expr.iter().any(|expr| {
492                    expr.column_refs()
493                        .iter()
494                        .any(|column| column.relation.is_some())
495                });
496                let mut input_names =
497                    HashSet::with_capacity(projection.input.schema().fields().len());
498                let unique_input_names = projection
499                    .input
500                    .schema()
501                    .fields()
502                    .iter()
503                    .all(|field| input_names.insert(field.name()));
504
505                (qualified_projection
506                    && unique_input_names
507                    && find_unnest_node_within_select(plan).is_none())
508                .then_some(DerivedInputScope {
509                    alias,
510                    schema: projection.input.schema().as_ref(),
511                })
512            }
513            // when a filter references aliases from its input, we add a subquery around it to
514            // prevent invalid references, so we need to keep track of it here
515            LogicalPlan::Filter(filter) if filter_depends_on_input_alias(filter) => {
516                Some(DerivedInputScope {
517                    alias: "derived_projection",
518                    schema: filter.input.schema().as_ref(),
519                })
520            }
521            LogicalPlan::Filter(filter) => {
522                Self::derived_input_scope(filter.input.as_ref(), select)
523            }
524            LogicalPlan::Limit(limit) => {
525                Self::derived_input_scope(limit.input.as_ref(), select)
526            }
527            LogicalPlan::Sort(sort) => {
528                Self::derived_input_scope(sort.input.as_ref(), select)
529            }
530            LogicalPlan::Repartition(repartition) => {
531                Self::derived_input_scope(repartition.input.as_ref(), select)
532            }
533            _ => None,
534        }
535    }
536
537    fn rebase_derived_input_expr(
538        &self,
539        expr: Expr,
540        scope: Option<DerivedInputScope<'_>>,
541    ) -> Result<Expr> {
542        let Some(scope) = scope else {
543            return Ok(expr);
544        };
545        if self.dialect.requires_derived_table_alias() {
546            let mut alias_rewriter = TableAliasRewriter {
547                table_schema: scope.schema,
548                alias_name: TableReference::bare(scope.alias),
549                rewrite_unqualified: false,
550            };
551            expr.rewrite(&mut alias_rewriter).data()
552        } else {
553            Self::strip_column_qualifiers_for_schema(expr, scope.schema)
554        }
555    }
556
557    fn contains_aggregate_before_relation(plan: &LogicalPlan) -> bool {
558        match plan {
559            LogicalPlan::Aggregate(_) => true,
560            LogicalPlan::TableScan(_)
561            | LogicalPlan::Subquery(_)
562            | LogicalPlan::SubqueryAlias(_)
563            | LogicalPlan::Join(_)
564            | LogicalPlan::EmptyRelation(_)
565            | LogicalPlan::Values(_) => false,
566            _ => {
567                let inputs = plan.inputs();
568                matches!(
569                    inputs.as_slice(),
570                    [input] if Self::contains_aggregate_before_relation(input)
571                )
572            }
573        }
574    }
575
576    /// Unproject a sort expression; normalize it when the sort is above an
577    /// aggregate, otherwise just unproject (no scope to normalize against).
578    fn unproject_sort_expr_in_scope(
579        sort_expr: SortExpr,
580        agg: Option<&Aggregate>,
581        input: &LogicalPlan,
582    ) -> Result<SortExpr> {
583        match agg {
584            Some(agg) => UnparserAggScope::new(agg).prepare_sort_expr(sort_expr, input),
585            None => unproject_sort_expr(sort_expr, None, input),
586        }
587    }
588
589    fn derive(
590        &self,
591        plan: &LogicalPlan,
592        relation: &mut RelationBuilder,
593        alias: Option<ast::TableAlias>,
594        lateral: bool,
595    ) -> Result<()> {
596        let preserve_names = matches!(plan, LogicalPlan::Projection(_))
597            && alias.as_ref().is_none_or(|alias| alias.columns.is_empty());
598        let mut derived_builder = DerivedRelationBuilder::default();
599        if preserve_names {
600            derived_builder.projection_names(
601                plan.schema()
602                    .fields()
603                    .iter()
604                    .map(|field| self.column_alias_to_sql(field.name()))
605                    .collect::<Result<Vec<_>>>()?,
606            );
607        }
608        derived_builder.lateral(lateral).alias(alias).subquery({
609            let inner_statement = self.plan_to_sql(plan)?;
610            if let ast::Statement::Query(inner_query) = inner_statement {
611                inner_query
612            } else {
613                return internal_err!(
614                    "Subquery must be a Query, but found {inner_statement:?}"
615                );
616            }
617        });
618        relation.derived(derived_builder);
619
620        Ok(())
621    }
622
623    fn derive_with_dialect_alias(
624        &self,
625        alias: &str,
626        plan: &LogicalPlan,
627        relation: &mut RelationBuilder,
628        lateral: bool,
629        columns: Vec<Ident>,
630    ) -> Result<()> {
631        if self.dialect.requires_derived_table_alias() || !columns.is_empty() {
632            self.derive(
633                plan,
634                relation,
635                Some(self.new_table_alias(alias.to_string(), columns)),
636                lateral,
637            )
638        } else {
639            self.derive(plan, relation, None, lateral)
640        }
641    }
642
643    /// Projection unparsing when [`super::dialect::Dialect::unnest_as_lateral_flatten`] is enabled:
644    /// Snowflake-style `LATERAL FLATTEN` for unnest (not other dialect spellings).
645    ///
646    /// [`Self::peel_to_unnest_with_modifiers`] walks through any intermediate
647    /// Limit/Sort nodes (the optimizer can insert these between the Projection
648    /// and the Unnest), applies their modifiers to the query, and returns the
649    /// Unnest plus the [`LogicalPlan`] ref to recurse into. This bypasses the
650    /// normal Limit/Sort handlers which would wrap the subtree in a derived
651    /// subquery.
652    ///
653    /// SELECT rendering is delegated to [`Self::reconstruct_select_statement`],
654    /// which rewrites placeholder columns to `alias."VALUE"` via
655    /// [`unproject_unnest_expr_as_flatten_value`].
656    ///
657    /// Returns `Ok(true)` when this path fully handled the projection.
658    fn try_projection_unnest_as_lateral_flatten(
659        &self,
660        plan: &LogicalPlan,
661        p: &Projection,
662        query: &mut Option<QueryBuilder>,
663        select: &mut SelectBuilder,
664        relation: &mut RelationBuilder,
665        unnest_input_type: Option<&UnnestInputType>,
666    ) -> Result<bool> {
667        // unnest_as_lateral_flatten: Snowflake LATERAL FLATTEN
668        //
669        // Generate the alias up front so that peel_to_unnest_with_modifiers
670        // can rewrite ORDER BY placeholder columns to alias.VALUE.
671        if self.dialect.unnest_as_lateral_flatten() && unnest_input_type.is_some() {
672            let flatten_alias_name = if !select.already_projected() {
673                select.next_flatten_alias()
674            } else {
675                select
676                    .current_flatten_alias()
677                    .unwrap_or_else(|| select.next_flatten_alias())
678            };
679
680            if let Some((unnest, unnest_plan)) = self.peel_to_unnest_with_modifiers(
681                p.input.as_ref(),
682                query,
683                Some(&flatten_alias_name),
684            )? && let Some(mut flatten) =
685                self.try_unnest_to_lateral_flatten_sql(unnest)?
686            {
687                let inner_projection = Self::peel_to_inner_projection(
688                    unnest.input.as_ref(),
689                )
690                .ok_or_else(|| {
691                    internal_datafusion_err!(
692                        "Unnest input is not a Projection: {:?}",
693                        unnest.input
694                    )
695                })?;
696
697                flatten.alias(Some(ast::TableAlias {
698                    name: Ident::with_quote('"', &flatten_alias_name),
699                    columns: vec![],
700                    explicit: true,
701                    at: None,
702                }));
703
704                if !select.already_projected() {
705                    self.reconstruct_select_statement(plan, p, select, true)?;
706                }
707
708                if matches!(
709                    inner_projection.input.as_ref(),
710                    LogicalPlan::EmptyRelation(_)
711                ) {
712                    relation.flatten(flatten);
713                    self.select_to_sql_recursively(unnest_plan, query, select, relation)?;
714                    return Ok(true);
715                }
716
717                self.select_to_sql_recursively(unnest_plan, query, select, relation)?;
718
719                let flatten_factor = flatten.build().map_err(|e| {
720                    internal_datafusion_err!("Failed to build FLATTEN: {e}")
721                })?;
722                let cross_join = ast::Join {
723                    relation: flatten_factor,
724                    global: false,
725                    join_operator: ast::JoinOperator::CrossJoin(
726                        ast::JoinConstraint::None,
727                    ),
728                };
729                if let Some(mut from) = select.pop_from() {
730                    from.push_join(cross_join);
731                    select.push_from(from);
732                } else {
733                    let mut twj = TableWithJoinsBuilder::default();
734                    twj.push_join(cross_join);
735                    select.push_from(twj);
736                }
737
738                return Ok(true);
739            }
740        }
741
742        Ok(false)
743    }
744
745    fn project_window_output(
746        &self,
747        window_expr: &[Expr],
748        select: &mut SelectBuilder,
749        agg: Option<&Aggregate>,
750    ) -> Result<()> {
751        let mut items = if select.already_projected() {
752            select.pop_projections()
753        } else {
754            vec![ast::SelectItem::Wildcard(
755                ast::WildcardAdditionalOptions::default(),
756            )]
757        };
758
759        items.extend(
760            window_expr
761                .iter()
762                .map(|expr| {
763                    // No normalization: this agg branch is only reachable from a
764                    // hand-built plan. SQL wraps windows in a projection, which
765                    // reconstruct_select_statement handles (and normalizes).
766                    let expr = if let Some(agg) = agg {
767                        unproject_agg_exprs(expr.clone(), agg, None)?
768                    } else {
769                        expr.clone()
770                    };
771                    self.select_item_to_sql(&expr)
772                })
773                .collect::<Result<Vec<_>>>()?,
774        );
775        select.projection(items);
776
777        Ok(())
778    }
779
780    fn window_input_requires_derived_subquery(plan: &LogicalPlan) -> bool {
781        // These operators either produce a SELECT list or apply SQL clauses
782        // that are evaluated after window functions in a single SELECT block.
783        // Keep them below the Window node by emitting a derived table.
784        matches!(
785            plan,
786            LogicalPlan::Projection(_)
787                | LogicalPlan::Distinct(_)
788                | LogicalPlan::Limit(_)
789                | LogicalPlan::Sort(_)
790                | LogicalPlan::Union(_)
791        )
792    }
793
794    fn window_to_sql_with_derived_input(
795        &self,
796        window: &Window,
797        select: &mut SelectBuilder,
798        relation: &mut RelationBuilder,
799    ) -> Result<()> {
800        let input_alias = "derived_window_input";
801        self.derive(
802            window.input.as_ref(),
803            relation,
804            Some(self.new_table_alias(input_alias.to_string(), vec![])),
805            false,
806        )?;
807
808        let input_schema = window.input.schema();
809        let mut alias_rewriter = TableAliasRewriter {
810            table_schema: input_schema.as_ref(),
811            alias_name: TableReference::bare(input_alias),
812            rewrite_unqualified: true,
813        };
814        let window_expr = window
815            .window_expr
816            .iter()
817            .map(|expr| expr.clone().rewrite(&mut alias_rewriter).data())
818            .collect::<Result<Vec<_>>>()?;
819
820        self.project_window_output(&window_expr, select, None)
821    }
822
823    fn extract_join_input_table_scan_filters(
824        plan: &Arc<LogicalPlan>,
825        table_scan_filters: &mut Vec<Expr>,
826    ) -> Result<Arc<LogicalPlan>> {
827        match try_transform_to_simple_table_scan_with_filters(plan)? {
828            Some((plan, filters)) => {
829                table_scan_filters.extend(filters);
830                Ok(Arc::new(plan))
831            }
832            None => Ok(Arc::clone(plan)),
833        }
834    }
835
836    #[cfg_attr(feature = "recursive_protection", recursive::recursive)]
837    fn select_to_sql_recursively(
838        &self,
839        plan: &LogicalPlan,
840        query: &mut Option<QueryBuilder>,
841        select: &mut SelectBuilder,
842        relation: &mut RelationBuilder,
843    ) -> Result<()> {
844        match plan {
845            LogicalPlan::TableScan(scan) => {
846                if let Some(unparsed_table_scan) = self.unparse_table_scan_pushdown(
847                    plan,
848                    None,
849                    select.already_projected(),
850                )? {
851                    return self.select_to_sql_recursively(
852                        &unparsed_table_scan,
853                        query,
854                        select,
855                        relation,
856                    );
857                }
858                let mut builder = TableRelationBuilder::default();
859                let mut table_parts = vec![];
860                if let Some(catalog_name) = scan.table_name.catalog() {
861                    table_parts
862                        .push(self.new_ident_quoted_if_needs(catalog_name.to_string()));
863                }
864                if let Some(schema_name) = scan.table_name.schema() {
865                    table_parts
866                        .push(self.new_ident_quoted_if_needs(schema_name.to_string()));
867                }
868                table_parts.push(
869                    self.new_ident_quoted_if_needs(scan.table_name.table().to_string()),
870                );
871                builder.name(ast::ObjectName::from(table_parts));
872                relation.table(builder);
873
874                Ok(())
875            }
876            LogicalPlan::Projection(p) => {
877                if let Some(new_plan) = rewrite_plan_for_sort_on_non_projected_fields(p) {
878                    return self
879                        .select_to_sql_recursively(&new_plan, query, select, relation);
880                }
881
882                // Projection can be top-level plan for unnest relation.
883                // The projection generated by the `RecursiveUnnestRewriter`
884                // will have at least one expression referencing an unnest
885                // placeholder column.
886                let unnest_input_type: Option<UnnestInputType> =
887                    p.expr.iter().find_map(Self::find_unnest_placeholder);
888
889                // --- UNNEST table factor path (BigQuery, etc.) ---
890                // Only fires for a single bare-placeholder projection.
891                // Uses peel_to_unnest_with_modifiers (rather than matching
892                // p.input directly) to handle Limit/Sort between Projection
893                // and Unnest.
894                if self.dialect.unnest_as_table_factor()
895                    && p.expr.len() == 1
896                    && Self::is_bare_unnest_placeholder(&p.expr[0])
897                    && let Some((unnest, unnest_plan)) =
898                        self.peel_to_unnest_with_modifiers(p.input.as_ref(), query, None)?
899                    && let Some(unnest_relation) =
900                        self.try_unnest_to_table_factor_sql(unnest)?
901                {
902                    relation.unnest(unnest_relation);
903                    return self.select_to_sql_recursively(
904                        unnest_plan,
905                        query,
906                        select,
907                        relation,
908                    );
909                }
910
911                if self.try_projection_unnest_as_lateral_flatten(
912                    plan,
913                    p,
914                    query,
915                    select,
916                    relation,
917                    unnest_input_type.as_ref(),
918                )? {
919                    return Ok(());
920                }
921
922                // If it's a unnest projection, we should provide the table column alias
923                // to provide a column name for the unnest relation.
924                let columns = if unnest_input_type.is_some() {
925                    p.expr
926                        .iter()
927                        .map(|e| {
928                            self.new_ident_quoted_if_needs(e.schema_name().to_string())
929                        })
930                        .collect()
931                } else {
932                    vec![]
933                };
934                // Projection can be top-level plan for derived table
935                if select.already_projected() {
936                    return self.derive_with_dialect_alias(
937                        "derived_projection",
938                        plan,
939                        relation,
940                        unnest_input_type.is_some_and(|t| {
941                            matches!(t, UnnestInputType::OuterReference)
942                        }),
943                        columns,
944                    );
945                }
946
947                if let Some(scope) = Self::derived_input_scope(plan, select) {
948                    // The input is about to enter a new SQL scope. Preserve that
949                    // boundary explicitly and make the outer expressions resolve
950                    // against the relation that will actually be visible there.
951                    let requires_alias = self.dialect.requires_derived_table_alias();
952                    let alias = requires_alias
953                        .then(|| self.new_table_alias(scope.alias.to_string(), vec![]));
954                    self.derive(p.input.as_ref(), relation, alias, false)?;
955
956                    let items = p
957                        .expr
958                        .iter()
959                        .cloned()
960                        .map(|expr| self.rebase_derived_input_expr(expr, Some(scope)))
961                        .map(|expr| self.select_item_to_sql(&expr?))
962                        .collect::<Result<Vec<_>>>()?;
963                    select.projection(items);
964                    return Ok(());
965                }
966                // For Snowflake FLATTEN: when the outer Projection has
967                // UNNEST(...) display-name columns (from SELECT * / SELECT
968                // UNNEST(...)), generate a flatten alias now so that
969                // reconstruct_select_statement and the downstream Unnest
970                // handler both use the same alias.
971                if self.dialect.unnest_as_lateral_flatten()
972                    && p.expr.iter().any(Self::has_internal_unnest_alias)
973                {
974                    select.next_flatten_alias();
975                }
976                // Pre-register FLATTEN table aliases from SubqueryAlias
977                // nodes in the plan tree so that
978                // reconstruct_select_statement can rewrite column
979                // references (e.g. a.col → a.VALUE) before the
980                // SubqueryAlias handler runs.
981                if self.dialect.unnest_as_lateral_flatten() {
982                    Self::collect_flatten_aliases(p.input.as_ref(), select);
983                }
984                // Walk down through consecutive Sort/Limit nodes, greedily
985                // absorbing what can be folded into the SELECT we're
986                // building around the Aggregate. A single SQL SELECT can
987                // carry at most one `ORDER BY` (applied before `LIMIT`),
988                // so the safe shape between us and the Aggregate is
989                // `Limit* Sort?` (outer→inner). We stop at the first node
990                // that would violate this; that node becomes the
991                // subquery boundary, and recursion (seeing
992                // `already_projected = true`) wraps it in a derived
993                // relation. If we walk all the way to a non-Sort/non-Limit
994                // terminator, the entire chain folds into one SELECT.
995                //
996                // Stacked Sorts with nothing between them collapse to the
997                // outermost — the same simplification `EnforceSorting`
998                // applies on the physical side — but only when no Limit
999                // has been absorbed since the previous Sort, since the
1000                // inner Sort would otherwise be determining which rows
1001                // the Limit keeps.
1002                //
1003                // The fold is collected here without touching `query`
1004                // (apart from non-literal direct Limits, which don't
1005                // depend on projection form). Once we know whether every
1006                // Sort/Limit was absorbed we can pick the right
1007                // projection form and emit `ORDER BY` with or without
1008                // unprojection.
1009                let mut cur = p.input.as_ref();
1010                let mut absorbed_sort: Option<&Sort> = None;
1011                let mut combined_skip: usize = 0;
1012                let mut combined_fetch: Option<usize> = None;
1013                let mut have_combined_limit = false;
1014                let mut have_direct_limit = false;
1015                let mut have_order_by = false;
1016                loop {
1017                    match cur {
1018                        LogicalPlan::Limit(limit) => {
1019                            if have_order_by {
1020                                // Limit-below-Sort: `ORDER BY … LIMIT N`
1021                                // would apply the sort first, but the
1022                                // logical plan applies the Limit first.
1023                                break;
1024                            }
1025                            let skip_lit = limit.get_skip_type()?;
1026                            let fetch_lit = limit.get_fetch_type()?;
1027                            match (skip_lit, fetch_lit) {
1028                                (SkipType::Literal(s), FetchType::Literal(f)) => {
1029                                    if have_direct_limit {
1030                                        break;
1031                                    }
1032                                    if have_combined_limit {
1033                                        // outer = already-accumulated;
1034                                        // inner = this Limit. Same merge
1035                                        // rule as the optimizer.
1036                                        let (cs, cf) = combine_limit(
1037                                            combined_skip,
1038                                            combined_fetch,
1039                                            s,
1040                                            f,
1041                                        );
1042                                        combined_skip = cs;
1043                                        combined_fetch = cf;
1044                                    } else {
1045                                        combined_skip = s;
1046                                        combined_fetch = f;
1047                                        have_combined_limit = true;
1048                                    }
1049                                }
1050                                _ => {
1051                                    if have_combined_limit || have_direct_limit {
1052                                        // Cannot safely merge a
1053                                        // non-literal Limit with a prior
1054                                        // one; let recursion handle it.
1055                                        break;
1056                                    }
1057                                    let Some(query_ref) = query.as_mut() else {
1058                                        return internal_err!(
1059                                            "Limit operator only valid in a statement context."
1060                                        );
1061                                    };
1062                                    if let Some(fetch) = &limit.fetch {
1063                                        query_ref.limit(Some(self.expr_to_sql(fetch)?));
1064                                    }
1065                                    if let Some(skip) = &limit.skip {
1066                                        query_ref.offset(Some(ast::Offset {
1067                                            rows: ast::OffsetRows::None,
1068                                            value: self.expr_to_sql(skip)?,
1069                                        }));
1070                                    }
1071                                    have_direct_limit = true;
1072                                }
1073                            }
1074                            cur = limit.input.as_ref();
1075                        }
1076                        LogicalPlan::Sort(sort) if sort.fetch.is_some() => {
1077                            // `Sort { fetch }` is logically
1078                            // `Limit(fetch) -> Sort`. Try to absorb the
1079                            // virtual Limit first; only if that succeeds
1080                            // do we absorb the Sort. Otherwise we'd
1081                            // silently drop the fetch.
1082                            let fetch = sort.fetch.expect("guarded above");
1083                            if have_order_by {
1084                                // The virtual Limit would sit below an
1085                                // already-absorbed outer Sort.
1086                                break;
1087                            }
1088                            if have_direct_limit {
1089                                // Cannot combine a literal fetch with a
1090                                // non-literal direct Limit; let the
1091                                // derived subquery preserve both.
1092                                break;
1093                            }
1094                            if have_combined_limit {
1095                                let (cs, cf) = combine_limit(
1096                                    combined_skip,
1097                                    combined_fetch,
1098                                    0,
1099                                    Some(fetch),
1100                                );
1101                                combined_skip = cs;
1102                                combined_fetch = cf;
1103                            } else {
1104                                combined_skip = 0;
1105                                combined_fetch = Some(fetch);
1106                                have_combined_limit = true;
1107                            }
1108                            // Now the Sort itself. We know
1109                            // `!have_order_by` from the check above.
1110                            absorbed_sort = Some(sort);
1111                            have_order_by = true;
1112                            cur = sort.input.as_ref();
1113                        }
1114                        LogicalPlan::Sort(sort) => {
1115                            // Sort without `fetch`.
1116                            if have_order_by {
1117                                // Outer Sort already absorbed; the inner
1118                                // Sort is reordered by it and is
1119                                // conventionally dropped, matching
1120                                // `EnforceSorting` on the physical side.
1121                                cur = sort.input.as_ref();
1122                                continue;
1123                            }
1124                            absorbed_sort = Some(sort);
1125                            have_order_by = true;
1126                            cur = sort.input.as_ref();
1127                        }
1128                        _ => break,
1129                    }
1130                }
1131
1132                // `fully_absorbed` is the bottom-up algorithm's "walked
1133                // all the way to the terminator without stopping": the
1134                // Aggregate/Window will live in the same SELECT as this
1135                // Projection, so we can unproject sort exprs and let
1136                // `reconstruct_select_statement` claim it.
1137                let fully_absorbed =
1138                    !matches!(cur, LogicalPlan::Limit(_) | LogicalPlan::Sort(_));
1139                let found_agg =
1140                    self.reconstruct_select_statement(plan, p, select, fully_absorbed)?;
1141
1142                // Whether to bother emitting the absorbed clauses: only
1143                // if there's an Aggregate either claimed in this SELECT
1144                // or about to live in a derived subquery below us. If
1145                // there's nothing aggregate-like to fold over, fall
1146                // through and let the normal recursion handle the
1147                // Projection's input.
1148                let agg_below =
1149                    !fully_absorbed && find_agg_node_within_select(plan, true).is_some();
1150                if !(found_agg || agg_below) {
1151                    return self.select_to_sql_recursively(
1152                        p.input.as_ref(),
1153                        query,
1154                        select,
1155                        relation,
1156                    );
1157                }
1158
1159                if let Some(sort) = absorbed_sort {
1160                    let Some(query_ref) = query.as_mut() else {
1161                        return internal_err!(
1162                            "Sort operator only valid in a statement context."
1163                        );
1164                    };
1165                    let sort_exprs: Vec<SortExpr> = if fully_absorbed {
1166                        let agg =
1167                            find_agg_node_within_select(plan, select.already_projected());
1168                        sort.expr
1169                            .iter()
1170                            .map(|sort_expr| {
1171                                Self::unproject_sort_expr_in_scope(
1172                                    sort_expr.clone(),
1173                                    agg,
1174                                    sort.input.as_ref(),
1175                                )
1176                            })
1177                            .collect::<Result<Vec<_>>>()?
1178                    } else {
1179                        sort.expr.clone()
1180                    };
1181                    query_ref.order_by(self.sorts_to_sql(&sort_exprs)?);
1182                }
1183                if have_combined_limit {
1184                    let Some(query_ref) = query.as_mut() else {
1185                        return internal_err!(
1186                            "Limit operator only valid in a statement context."
1187                        );
1188                    };
1189                    if let Some(fetch) = combined_fetch {
1190                        query_ref.limit(Some(ast::Expr::value(ast::Value::Number(
1191                            fetch.to_string(),
1192                            false,
1193                        ))));
1194                    }
1195                    if combined_skip > 0 {
1196                        query_ref.offset(Some(ast::Offset {
1197                            rows: ast::OffsetRows::None,
1198                            value: ast::Expr::value(ast::Value::Number(
1199                                combined_skip.to_string(),
1200                                false,
1201                            )),
1202                        }));
1203                    }
1204                }
1205
1206                self.select_to_sql_recursively(cur, query, select, relation)
1207            }
1208            LogicalPlan::Filter(filter) => {
1209                let derived_input_scope = Self::derived_input_scope(plan, select);
1210                let window = find_window_nodes_within_select(
1211                    plan,
1212                    None,
1213                    select.already_projected(),
1214                );
1215                let agg = find_agg_node_within_select(plan, select.already_projected());
1216
1217                if let (Some(window), true) =
1218                    (window.as_deref(), self.dialect.supports_qualify())
1219                {
1220                    let mut unprojected =
1221                        unproject_window_exprs(filter.predicate.clone(), window)?;
1222                    if let Some(agg) = agg {
1223                        unprojected =
1224                            UnparserAggScope::new(agg).prepare(unprojected, None)?;
1225                    }
1226                    unprojected =
1227                        self.rebase_derived_input_expr(unprojected, derived_input_scope)?;
1228                    let filter_expr = self.expr_to_sql(&unprojected)?;
1229                    select.qualify(Some(filter_expr));
1230                } else if let Some(agg) = agg {
1231                    let mut unprojected = UnparserAggScope::new(agg)
1232                        .prepare(filter.predicate.clone(), None)?;
1233                    unprojected =
1234                        self.rebase_derived_input_expr(unprojected, derived_input_scope)?;
1235                    let filter_expr = self.expr_to_sql(&unprojected)?;
1236                    select.having(Some(filter_expr));
1237                } else {
1238                    let predicate = self.rebase_derived_input_expr(
1239                        filter.predicate.clone(),
1240                        derived_input_scope,
1241                    )?;
1242                    let filter_expr = self.expr_to_sql(&predicate)?;
1243                    select.selection(Some(filter_expr));
1244                }
1245
1246                // if the inner plan aliases columns used by the filter, we need to convert to a
1247                // subquery to prevent invalid references
1248                if filter_depends_on_input_alias(filter) {
1249                    return self.derive_with_dialect_alias(
1250                        "derived_projection",
1251                        &filter.input,
1252                        relation,
1253                        false,
1254                        vec![],
1255                    );
1256                }
1257
1258                self.select_to_sql_recursively(
1259                    filter.input.as_ref(),
1260                    query,
1261                    select,
1262                    relation,
1263                )
1264            }
1265            LogicalPlan::Limit(limit) => {
1266                // Limit can be top-level plan for derived table
1267                if select.already_projected() {
1268                    return self.derive_with_dialect_alias(
1269                        "derived_limit",
1270                        plan,
1271                        relation,
1272                        false,
1273                        vec![],
1274                    );
1275                }
1276                if let Some(fetch) = &limit.fetch {
1277                    let Some(query) = query.as_mut() else {
1278                        return internal_err!(
1279                            "Limit operator only valid in a statement context."
1280                        );
1281                    };
1282                    query.limit(Some(self.expr_to_sql(fetch)?));
1283                }
1284
1285                if let Some(skip) = &limit.skip {
1286                    let Some(query) = query.as_mut() else {
1287                        return internal_err!(
1288                            "Offset operator only valid in a statement context."
1289                        );
1290                    };
1291
1292                    query.offset(Some(ast::Offset {
1293                        rows: ast::OffsetRows::None,
1294                        value: self.expr_to_sql(skip)?,
1295                    }));
1296                }
1297
1298                self.select_to_sql_recursively(
1299                    limit.input.as_ref(),
1300                    query,
1301                    select,
1302                    relation,
1303                )
1304            }
1305            LogicalPlan::Sort(sort) => {
1306                // Sort can be top-level plan for derived table
1307                if select.already_projected() {
1308                    return self.derive_with_dialect_alias(
1309                        "derived_sort",
1310                        plan,
1311                        relation,
1312                        false,
1313                        vec![],
1314                    );
1315                }
1316
1317                let Some(query_ref) = query else {
1318                    return internal_err!(
1319                        "Sort operator only valid in a statement context."
1320                    );
1321                };
1322
1323                if let Some(fetch) = sort.fetch {
1324                    query_ref.limit(Some(ast::Expr::value(ast::Value::Number(
1325                        fetch.to_string(),
1326                        false,
1327                    ))));
1328                }
1329
1330                let derived_input_scope = Self::derived_input_scope(plan, select);
1331                let agg = find_agg_node_within_select(plan, select.already_projected());
1332                // unproject sort expressions
1333                let sort_exprs: Vec<SortExpr> = sort
1334                    .expr
1335                    .iter()
1336                    .map(|sort_expr| {
1337                        let sort_expr = Self::unproject_sort_expr_in_scope(
1338                            sort_expr.clone(),
1339                            agg,
1340                            sort.input.as_ref(),
1341                        )?;
1342                        Ok(SortExpr {
1343                            expr: self.rebase_derived_input_expr(
1344                                sort_expr.expr,
1345                                derived_input_scope,
1346                            )?,
1347                            ..sort_expr
1348                        })
1349                    })
1350                    .collect::<Result<Vec<_>>>()?;
1351
1352                query_ref.order_by(self.sorts_to_sql(&sort_exprs)?);
1353
1354                self.select_to_sql_recursively(
1355                    sort.input.as_ref(),
1356                    query,
1357                    select,
1358                    relation,
1359                )
1360            }
1361            LogicalPlan::Aggregate(agg) => {
1362                // Aggregation can be already handled in the projection case
1363                if !select.already_projected() {
1364                    let unparser_agg_scope = UnparserAggScope::new(agg);
1365                    // The query returns aggregate and group expressions. If that weren't the case,
1366                    // the aggregate would have been placed inside a projection, making the check above^ false
1367                    let exprs: Vec<_> = agg
1368                        .aggr_expr
1369                        .iter()
1370                        .chain(agg.group_expr.iter())
1371                        .cloned()
1372                        .map(|expr| {
1373                            self.select_item_to_sql(&unparser_agg_scope.normalize(expr)?)
1374                        })
1375                        .collect::<Result<Vec<_>>>()?;
1376                    select.projection(exprs);
1377
1378                    select.group_by(ast::GroupByExpr::Expressions(
1379                        agg.group_expr
1380                            .iter()
1381                            .cloned()
1382                            .map(|expr| {
1383                                self.expr_to_sql(&unparser_agg_scope.normalize(expr)?)
1384                            })
1385                            .collect::<Result<Vec<_>>>()?,
1386                        vec![],
1387                    ));
1388                } else if Self::contains_aggregate_before_relation(agg.input.as_ref()) {
1389                    return self.derive_with_dialect_alias(
1390                        "derived_aggregate",
1391                        agg.input.as_ref(),
1392                        relation,
1393                        false,
1394                        vec![],
1395                    );
1396                }
1397
1398                self.select_to_sql_recursively(
1399                    agg.input.as_ref(),
1400                    query,
1401                    select,
1402                    relation,
1403                )
1404            }
1405            LogicalPlan::Distinct(distinct) => {
1406                // Distinct can be top-level plan for derived table
1407                if select.already_projected() {
1408                    return self.derive_with_dialect_alias(
1409                        "derived_distinct",
1410                        plan,
1411                        relation,
1412                        false,
1413                        vec![],
1414                    );
1415                }
1416
1417                // If this distinct is the parent of a Union and we're in a query context,
1418                // then we need to unparse as a `UNION` rather than a `UNION ALL`.
1419                if let Distinct::All(input) = distinct
1420                    && matches!(input.as_ref(), LogicalPlan::Union(_))
1421                    && let Some(query_mut) = query.as_mut()
1422                {
1423                    query_mut.distinct_union();
1424                    return self.select_to_sql_recursively(
1425                        input.as_ref(),
1426                        query,
1427                        select,
1428                        relation,
1429                    );
1430                }
1431
1432                let (select_distinct, input) = match distinct {
1433                    Distinct::All(input) => (ast::Distinct::Distinct, input.as_ref()),
1434                    Distinct::On(on) => {
1435                        let exprs = on
1436                            .on_expr
1437                            .iter()
1438                            .map(|e| self.expr_to_sql(e))
1439                            .collect::<Result<Vec<_>>>()?;
1440                        let items = on
1441                            .select_expr
1442                            .iter()
1443                            .map(|e| self.select_item_to_sql(e))
1444                            .collect::<Result<Vec<_>>>()?;
1445                        if let Some(sort_expr) = &on.sort_expr {
1446                            if let Some(query_ref) = query {
1447                                query_ref.order_by(self.sorts_to_sql(sort_expr)?);
1448                            } else {
1449                                return internal_err!(
1450                                    "Sort operator only valid in a statement context."
1451                                );
1452                            }
1453                        }
1454                        select.projection(items);
1455                        (ast::Distinct::On(exprs), on.input.as_ref())
1456                    }
1457                };
1458                select.distinct(Some(select_distinct));
1459                self.select_to_sql_recursively(input, query, select, relation)
1460            }
1461            LogicalPlan::Join(join) => {
1462                let mut table_scan_filters = vec![];
1463                let (left_plan, right_plan) = match join.join_type {
1464                    JoinType::RightSemi | JoinType::RightAnti => {
1465                        (&join.right, &join.left)
1466                    }
1467                    _ => (&join.left, &join.right),
1468                };
1469                // If there's an outer projection plan, it will already set up the projection.
1470                // In that case, we don't need to worry about setting up the projection here.
1471                // The outer projection plan will handle projecting the correct columns.
1472                let already_projected = select.already_projected();
1473
1474                let left_plan = Self::extract_join_input_table_scan_filters(
1475                    left_plan,
1476                    &mut table_scan_filters,
1477                )?;
1478                let left_plan = if already_projected {
1479                    Self::unwrap_qualified_passthrough_join_projection(left_plan)
1480                } else {
1481                    left_plan
1482                };
1483
1484                self.select_to_sql_recursively(
1485                    left_plan.as_ref(),
1486                    query,
1487                    select,
1488                    relation,
1489                )?;
1490
1491                let left_projection: Option<Vec<ast::SelectItem>> = if !already_projected
1492                {
1493                    Some(select.pop_projections())
1494                } else {
1495                    None
1496                };
1497
1498                let right_plan = Self::extract_join_input_table_scan_filters(
1499                    right_plan,
1500                    &mut table_scan_filters,
1501                )?;
1502
1503                let mut right_relation = RelationBuilder::default();
1504                if already_projected
1505                    && let Some(nested_relation) =
1506                        self.join_input_to_nested_relation(right_plan.as_ref(), query)?
1507                {
1508                    right_relation = nested_relation;
1509                } else {
1510                    self.select_to_sql_recursively(
1511                        right_plan.as_ref(),
1512                        query,
1513                        select,
1514                        &mut right_relation,
1515                    )?;
1516                }
1517
1518                let (join_filters, where_filters) = Self::split_join_on_and_where_filters(
1519                    join.join_type,
1520                    join.filter.as_ref(),
1521                    table_scan_filters,
1522                );
1523                for filter in where_filters {
1524                    let filter_expr = self.expr_to_sql(&filter)?;
1525                    select.selection(Some(filter_expr));
1526                }
1527
1528                let join_constraint = self.join_constraint_to_sql(
1529                    join.join_constraint,
1530                    &join.on,
1531                    join_filters.as_ref(),
1532                )?;
1533
1534                let right_projection: Option<Vec<ast::SelectItem>> = if !already_projected
1535                {
1536                    Some(select.pop_projections())
1537                } else {
1538                    None
1539                };
1540
1541                match join.join_type {
1542                    JoinType::LeftSemi
1543                    | JoinType::LeftAnti
1544                    | JoinType::LeftMark
1545                    | JoinType::RightSemi
1546                    | JoinType::RightAnti
1547                    | JoinType::RightMark => {
1548                        let mut query_builder = QueryBuilder::default();
1549                        let mut from = TableWithJoinsBuilder::default();
1550                        let mut exists_select: SelectBuilder = SelectBuilder::default();
1551                        from.relation(right_relation);
1552                        exists_select.push_from(from);
1553                        if let Some(filter) = &join.filter {
1554                            exists_select.selection(Some(self.expr_to_sql(filter)?));
1555                        }
1556                        for (left, right) in &join.on {
1557                            exists_select.selection(Some(
1558                                self.expr_to_sql(&left.clone().eq(right.clone()))?,
1559                            ));
1560                        }
1561                        exists_select.projection(vec![ast::SelectItem::UnnamedExpr(
1562                            ast::Expr::value(ast::Value::Number("1".to_string(), false)),
1563                        )]);
1564                        query_builder.body(Box::new(SetExpr::Select(Box::new(
1565                            exists_select.build()?,
1566                        ))));
1567
1568                        let negated = match join.join_type {
1569                            JoinType::LeftSemi
1570                            | JoinType::RightSemi
1571                            | JoinType::LeftMark
1572                            | JoinType::RightMark => false,
1573                            JoinType::LeftAnti | JoinType::RightAnti => true,
1574                            _ => unreachable!(),
1575                        };
1576                        let exists_expr = ast::Expr::Exists {
1577                            subquery: Box::new(query_builder.build()?),
1578                            negated,
1579                        };
1580
1581                        match join.join_type {
1582                            JoinType::LeftMark | JoinType::RightMark => {
1583                                let source_schema =
1584                                    if join.join_type == JoinType::LeftMark {
1585                                        right_plan.schema()
1586                                    } else {
1587                                        left_plan.schema()
1588                                    };
1589                                let (table_ref, _) = source_schema.qualified_field(0);
1590                                let column = self.col_to_sql(&Column::new(
1591                                    table_ref.cloned(),
1592                                    "mark",
1593                                ))?;
1594                                select.replace_mark(&column, &exists_expr);
1595                            }
1596                            _ => {
1597                                select.selection(Some(exists_expr));
1598                            }
1599                        }
1600                        if let Some(projection) = left_projection {
1601                            select.projection(projection);
1602                        }
1603                    }
1604                    JoinType::Inner
1605                    | JoinType::Left
1606                    | JoinType::Right
1607                    | JoinType::Full => {
1608                        let Ok(Some(relation)) = right_relation.build() else {
1609                            return internal_err!("Failed to build right relation");
1610                        };
1611                        let ast_join = ast::Join {
1612                            relation,
1613                            global: false,
1614                            join_operator: self
1615                                .join_operator_to_sql(join.join_type, join_constraint)?,
1616                        };
1617                        let mut from = select.pop_from().unwrap();
1618                        from.push_join(ast_join);
1619                        select.push_from(from);
1620                        if !already_projected {
1621                            let Some(left_projection) = left_projection else {
1622                                return internal_err!("Left projection is missing");
1623                            };
1624
1625                            let Some(right_projection) = right_projection else {
1626                                return internal_err!("Right projection is missing");
1627                            };
1628
1629                            let projection = left_projection
1630                                .into_iter()
1631                                .chain(right_projection)
1632                                .collect();
1633                            select.projection(projection);
1634                        }
1635                    }
1636                }
1637
1638                Ok(())
1639            }
1640            LogicalPlan::AsOfJoin(join) => {
1641                self.asof_join_to_sql(join, query, select, relation)
1642            }
1643            LogicalPlan::SubqueryAlias(plan_alias) => {
1644                let (plan, mut columns) =
1645                    subquery_alias_inner_query_and_columns(plan_alias);
1646                let unparsed_table_scan = self.unparse_table_scan_pushdown(
1647                    plan,
1648                    Some(plan_alias.alias.clone()),
1649                    select.already_projected(),
1650                )?;
1651
1652                // If the (possibly rewritten) inner plan builds its own
1653                // SELECT clauses (e.g. Aggregate adds GROUP BY, Window adds
1654                // OVER, etc.) and unparse_table_scan_pushdown couldn't reduce it,
1655                // we must emit a derived subquery: (SELECT ...) AS alias.
1656                // Without this, the recursive handler would merge those clauses
1657                // into the outer SELECT, losing the subquery structure entirely.
1658                // Also, do not add a table alias past a Filter, as otherwise the predicates might
1659                // refer to invalid tables.
1660                if (unparsed_table_scan.is_none()
1661                    && Self::requires_derived_subquery(plan))
1662                    || matches!(plan, LogicalPlan::Filter(_))
1663                {
1664                    // When the dialect does not support column aliases in
1665                    // table aliases (e.g. SQLite), inject the aliases into
1666                    // the inner projection before wrapping as a derived
1667                    // subquery.
1668                    if !columns.is_empty()
1669                        && !self.dialect.supports_column_alias_in_table_alias()
1670                    {
1671                        let Ok(rewritten_plan) =
1672                            inject_column_aliases_into_subquery(plan.clone(), columns)
1673                        else {
1674                            return internal_err!(
1675                                "Failed to transform SubqueryAlias plan"
1676                            );
1677                        };
1678                        return self.derive(
1679                            &rewritten_plan,
1680                            relation,
1681                            Some(self.new_table_alias(
1682                                plan_alias.alias.table().to_string(),
1683                                vec![],
1684                            )),
1685                            false,
1686                        );
1687                    }
1688                    return self.derive(
1689                        plan,
1690                        relation,
1691                        Some(self.new_table_alias(
1692                            plan_alias.alias.table().to_string(),
1693                            columns,
1694                        )),
1695                        false,
1696                    );
1697                }
1698
1699                // if the child plan is a TableScan with pushdown operations, we don't need to
1700                // create an additional subquery for it
1701                if !select.already_projected() && unparsed_table_scan.is_none() {
1702                    select.projection(vec![ast::SelectItem::Wildcard(
1703                        ast::WildcardAdditionalOptions::default(),
1704                    )]);
1705                }
1706                let plan = unparsed_table_scan.unwrap_or_else(|| plan.clone());
1707                select.enter_subquery_alias();
1708                let recursive_result = if !columns.is_empty()
1709                    && !self.dialect.supports_column_alias_in_table_alias()
1710                {
1711                    // Instead of specifying column aliases as part of the outer table, inject them directly into the inner projection
1712                    let rewritten_plan =
1713                        match inject_column_aliases_into_subquery(plan, columns) {
1714                            Ok(p) => p,
1715                            Err(e) => {
1716                                return internal_err!(
1717                                    "Failed to transform SubqueryAlias plan: {e}"
1718                                );
1719                            }
1720                        };
1721
1722                    columns = vec![];
1723
1724                    self.select_to_sql_recursively(
1725                        &rewritten_plan,
1726                        query,
1727                        select,
1728                        relation,
1729                    )
1730                } else {
1731                    self.select_to_sql_recursively(&plan, query, select, relation)
1732                };
1733                select.exit_subquery_alias();
1734                recursive_result?;
1735
1736                relation.alias(Some(
1737                    self.new_table_alias(plan_alias.alias.table().to_string(), columns),
1738                ));
1739
1740                // If this SubqueryAlias wraps a FLATTEN (Snowflake unnest),
1741                // register the alias so the outer Projection can rewrite
1742                // column references to use VALUE.
1743                if self.dialect.unnest_as_lateral_flatten()
1744                    && find_unnest_node_until_relation(plan_alias.input.as_ref())
1745                        .is_some()
1746                {
1747                    select.add_flatten_table_alias(plan_alias.alias.table().to_string());
1748                }
1749
1750                Ok(())
1751            }
1752            LogicalPlan::Union(union) => {
1753                // Covers cases where the UNION is a subquery and the projection is at the top level
1754                if select.already_projected() {
1755                    return self.derive_with_dialect_alias(
1756                        "derived_union",
1757                        plan,
1758                        relation,
1759                        false,
1760                        vec![],
1761                    );
1762                }
1763
1764                let input_exprs: Vec<SetExpr> = union
1765                    .inputs
1766                    .iter()
1767                    .map(|input| self.select_to_sql_expr(input, query))
1768                    .collect::<Result<Vec<_>>>()?;
1769
1770                assert_or_internal_err!(
1771                    input_exprs.len() >= 2,
1772                    "UNION operator requires at least 2 inputs"
1773                );
1774
1775                let set_quantifier =
1776                    if query.as_ref().is_some_and(|q| q.is_distinct_union()) {
1777                        // Setting the SetQuantifier to None will unparse as a `UNION`
1778                        // rather than a `UNION ALL`.
1779                        ast::SetQuantifier::None
1780                    } else {
1781                        ast::SetQuantifier::All
1782                    };
1783
1784                // Build the union expression tree bottom-up by reversing the order
1785                // note that we are also swapping left and right inputs because of the rev
1786                let union_expr = input_exprs
1787                    .into_iter()
1788                    .rev()
1789                    .reduce(|a, b| SetExpr::SetOperation {
1790                        op: ast::SetOperator::Union,
1791                        set_quantifier,
1792                        left: Box::new(b),
1793                        right: Box::new(a),
1794                    })
1795                    .unwrap();
1796
1797                let Some(query) = query.as_mut() else {
1798                    return internal_err!(
1799                        "UNION ALL operator only valid in a statement context"
1800                    );
1801                };
1802                query.body(Box::new(union_expr));
1803
1804                Ok(())
1805            }
1806            LogicalPlan::Window(window) => {
1807                // Window nodes are usually handled simultaneously with Projection
1808                // nodes, where projected columns are unprojected back into their
1809                // corresponding window expressions. Manually built plans can have
1810                // Window nodes without an enclosing Projection, so in that case
1811                // the Window node itself must contribute its output expressions.
1812                let project_window_output = !select.already_projected();
1813                if project_window_output
1814                    && Self::window_input_requires_derived_subquery(window.input.as_ref())
1815                {
1816                    return self
1817                        .window_to_sql_with_derived_input(window, select, relation);
1818                }
1819
1820                let agg = if project_window_output {
1821                    find_agg_node_within_select(plan, false)
1822                } else {
1823                    None
1824                };
1825
1826                self.select_to_sql_recursively(
1827                    window.input.as_ref(),
1828                    query,
1829                    select,
1830                    relation,
1831                )?;
1832
1833                if project_window_output {
1834                    self.project_window_output(&window.window_expr, select, agg)?;
1835                }
1836
1837                Ok(())
1838            }
1839            LogicalPlan::EmptyRelation(_) => {
1840                // An EmptyRelation could be behind an UNNEST node. If the dialect supports UNNEST as a table factor,
1841                // a TableRelationBuilder will be created for the UNNEST node first.
1842                if !relation.has_relation() {
1843                    relation.empty();
1844                }
1845                Ok(())
1846            }
1847            LogicalPlan::Extension(extension) => {
1848                let mut query = query.as_mut();
1849                self.extension_to_sql(
1850                    extension.node.as_ref(),
1851                    &mut query,
1852                    &mut Some(select),
1853                    &mut Some(relation),
1854                )
1855            }
1856            LogicalPlan::Unnest(unnest) => {
1857                if !unnest.struct_type_columns.is_empty() {
1858                    if self.dialect.unnest_as_lateral_flatten() {
1859                        return not_impl_err!(
1860                            "Snowflake FLATTEN cannot unparse struct unnest: \
1861                             DataFusion expands struct fields into columns (horizontal), \
1862                             but Snowflake FLATTEN expands them into rows (vertical). \
1863                             Columns: {:?}",
1864                            unnest.struct_type_columns
1865                        );
1866                    }
1867                    return internal_err!(
1868                        "Struct type columns are not currently supported in UNNEST: {:?}",
1869                        unnest.struct_type_columns
1870                    );
1871                }
1872
1873                // For Snowflake FLATTEN: if the relation hasn't been set yet
1874                // (UNNEST was in SELECT clause, not FROM clause), set the FLATTEN
1875                // relation here so the FROM clause is emitted.
1876                if self.dialect.unnest_as_lateral_flatten()
1877                    && !relation.has_relation()
1878                    && let Some(mut flatten_relation) =
1879                        self.try_unnest_to_lateral_flatten_sql(unnest)?
1880                {
1881                    // Use the alias already generated by the Projection
1882                    // handler so SELECT items and the FLATTEN relation
1883                    // reference the same name.
1884                    if let Some(alias) = select.current_flatten_alias() {
1885                        flatten_relation.alias(Some(ast::TableAlias {
1886                            name: Ident::with_quote('"', &alias),
1887                            columns: vec![],
1888                            explicit: true,
1889                            at: None,
1890                        }));
1891                    }
1892                    relation.flatten(flatten_relation);
1893                }
1894
1895                // In the case of UNNEST, the Unnest node is followed by a duplicate Projection node that we should skip.
1896                // Otherwise, there will be a duplicate SELECT clause.
1897                // | Projection: table.col1, UNNEST(table.col2)
1898                // |   Unnest: UNNEST(table.col2)
1899                // |     Projection: table.col1, table.col2 AS UNNEST(table.col2)
1900                // |       Filter: table.col3 = Int64(3)
1901                // |         TableScan: table projection=None
1902                if let Some(p) = Self::peel_to_inner_projection(unnest.input.as_ref()) {
1903                    // Skip the inner Projection (synthetic rewriter node)
1904                    // and continue with its input.
1905                    self.select_to_sql_recursively(&p.input, query, select, relation)
1906                } else {
1907                    internal_err!("Unnest input is not a Projection: {unnest:?}")
1908                }
1909            }
1910            LogicalPlan::Subquery(subquery)
1911                if find_unnest_node_until_relation(subquery.subquery.as_ref())
1912                    .is_some() =>
1913            {
1914                if self.dialect.unnest_as_table_factor()
1915                    || self.dialect.unnest_as_lateral_flatten()
1916                {
1917                    self.select_to_sql_recursively(
1918                        subquery.subquery.as_ref(),
1919                        query,
1920                        select,
1921                        relation,
1922                    )
1923                } else {
1924                    self.derive_with_dialect_alias(
1925                        "derived_unnest",
1926                        subquery.subquery.as_ref(),
1927                        relation,
1928                        true,
1929                        vec![],
1930                    )
1931                }
1932            }
1933            _ => {
1934                not_impl_err!("Unsupported operator: {plan:?}")
1935            }
1936        }
1937    }
1938
1939    // Keep ASOF-specific locals out of the recursive plan unparser's stack frame.
1940    #[inline(never)]
1941    fn asof_join_to_sql(
1942        &self,
1943        join: &AsOfJoin,
1944        query: &mut Option<QueryBuilder>,
1945        select: &mut SelectBuilder,
1946        relation: &mut RelationBuilder,
1947    ) -> Result<()> {
1948        let already_projected = select.already_projected();
1949        let left_plan =
1950            Self::unwrap_qualified_passthrough_join_projection(Arc::clone(&join.left));
1951        let inline_left_join = matches!(
1952            left_plan.as_ref(),
1953            LogicalPlan::Join(_) | LogicalPlan::AsOfJoin(_)
1954        );
1955        let left_projection = if already_projected {
1956            None
1957        } else if inline_left_join {
1958            self.select_to_sql_recursively(left_plan.as_ref(), query, select, relation)?;
1959            select.pop_projections();
1960            Some(self.derived_input_projection(join.left.as_ref(), None)?)
1961        } else if Self::asof_input_requires_derived(join.left.as_ref()) {
1962            let qualifier = self.derive_asof_input(join.left.as_ref(), relation)?;
1963            Some(self.derived_input_projection(join.left.as_ref(), qualifier.as_ref())?)
1964        } else {
1965            self.select_to_sql_recursively(join.left.as_ref(), query, select, relation)?;
1966            Some(select.pop_projections())
1967        };
1968        if already_projected {
1969            if inline_left_join {
1970                self.select_to_sql_recursively(
1971                    left_plan.as_ref(),
1972                    query,
1973                    select,
1974                    relation,
1975                )?;
1976            } else if Self::asof_input_requires_derived(join.left.as_ref()) {
1977                self.derive_asof_input(join.left.as_ref(), relation)?;
1978            } else {
1979                self.select_to_sql_recursively(
1980                    join.left.as_ref(),
1981                    query,
1982                    select,
1983                    relation,
1984                )?;
1985            }
1986        }
1987
1988        let mut right_relation = RelationBuilder::default();
1989        let nested_right =
1990            self.join_input_to_nested_relation(join.right.as_ref(), query)?;
1991        let right_projection = if already_projected {
1992            if let Some(nested_right) = nested_right {
1993                right_relation = nested_right;
1994            } else if Self::asof_input_requires_derived(join.right.as_ref()) {
1995                self.derive_asof_input(join.right.as_ref(), &mut right_relation)?;
1996            } else {
1997                self.select_to_sql_recursively(
1998                    join.right.as_ref(),
1999                    query,
2000                    select,
2001                    &mut right_relation,
2002                )?;
2003            }
2004            None
2005        } else if let Some(nested_right) = nested_right {
2006            right_relation = nested_right;
2007            Some(self.derived_input_projection(join.right.as_ref(), None)?)
2008        } else if Self::asof_input_requires_derived(join.right.as_ref()) {
2009            let qualifier =
2010                self.derive_asof_input(join.right.as_ref(), &mut right_relation)?;
2011            Some(self.derived_input_projection(join.right.as_ref(), qualifier.as_ref())?)
2012        } else {
2013            self.select_to_sql_recursively(
2014                join.right.as_ref(),
2015                query,
2016                select,
2017                &mut right_relation,
2018            )?;
2019            Some(select.pop_projections())
2020        };
2021        let Ok(Some(relation)) = right_relation.build() else {
2022            return internal_err!("Failed to build ASOF right relation");
2023        };
2024        let constraint =
2025            self.join_constraint_to_sql(join.join_constraint, &join.on, None)?;
2026        let match_condition = self.expr_to_sql(&Expr::BinaryExpr(BinaryExpr::new(
2027            Box::new(join.match_condition.left.clone()),
2028            join.match_condition.op,
2029            Box::new(join.match_condition.right.clone()),
2030        )))?;
2031        let ast_join = ast::Join {
2032            relation,
2033            global: false,
2034            join_operator: ast::JoinOperator::AsOf {
2035                match_condition,
2036                constraint,
2037            },
2038        };
2039        let mut from = select
2040            .pop_from()
2041            .ok_or_else(|| internal_datafusion_err!("ASOF left relation is missing"))?;
2042        from.push_join(ast_join);
2043        select.push_from(from);
2044
2045        if !already_projected {
2046            let left_projection = left_projection.ok_or_else(|| {
2047                internal_datafusion_err!("ASOF left projection is missing")
2048            })?;
2049            let right_projection = right_projection.ok_or_else(|| {
2050                internal_datafusion_err!("ASOF right projection is missing")
2051            })?;
2052            select.projection(
2053                left_projection
2054                    .into_iter()
2055                    .chain(right_projection)
2056                    .collect(),
2057            );
2058        }
2059        Ok(())
2060    }
2061
2062    /// Walk through transparent nodes (SubqueryAlias) to find the inner
2063    /// Projection that feeds an Unnest node.
2064    ///
2065    /// The inner Projection is created atomically by the
2066    /// `RecursiveUnnestRewriter` and contains the array expression that the
2067    /// Unnest operates on. A `SubqueryAlias` (e.g. from a virtual/passthrough
2068    /// table) may wrap the Projection.
2069    fn peel_to_inner_projection(plan: &LogicalPlan) -> Option<&Projection> {
2070        match plan {
2071            LogicalPlan::Projection(p) => Some(p),
2072            LogicalPlan::SubqueryAlias(alias) => {
2073                Self::peel_to_inner_projection(alias.input.as_ref())
2074            }
2075            _ => None,
2076        }
2077    }
2078
2079    /// Walk through transparent nodes (Limit, Sort) between the outer
2080    /// Projection and the Unnest, applying their SQL modifiers (LIMIT,
2081    /// OFFSET, ORDER BY) to the query builder. Returns the `Unnest` node
2082    /// and a reference to the enclosing `LogicalPlan` for recursion, or
2083    /// `Ok(None)` if no Unnest is found.
2084    ///
2085    /// By processing Limit/Sort inline and then recursing into the Unnest
2086    /// plan directly, we bypass the normal Limit/Sort handlers which would
2087    /// create unwanted derived subqueries (since `already_projected` is
2088    /// set at the point this is called).
2089    fn peel_to_unnest_with_modifiers<'a>(
2090        &self,
2091        plan: &'a LogicalPlan,
2092        query: &mut Option<QueryBuilder>,
2093        flatten_alias: Option<&str>,
2094    ) -> Result<Option<(&'a Unnest, &'a LogicalPlan)>> {
2095        match plan {
2096            LogicalPlan::Unnest(unnest) => Ok(Some((unnest, plan))),
2097            LogicalPlan::Limit(limit) => {
2098                if let Some(fetch) = &limit.fetch
2099                    && let Some(q) = query.as_mut()
2100                {
2101                    q.limit(Some(self.expr_to_sql(fetch)?));
2102                }
2103                if let Some(skip) = &limit.skip
2104                    && let Some(q) = query.as_mut()
2105                {
2106                    q.offset(Some(ast::Offset {
2107                        rows: ast::OffsetRows::None,
2108                        value: self.expr_to_sql(skip)?,
2109                    }));
2110                }
2111                self.peel_to_unnest_with_modifiers(
2112                    limit.input.as_ref(),
2113                    query,
2114                    flatten_alias,
2115                )
2116            }
2117            LogicalPlan::Sort(sort) => {
2118                let Some(query_ref) = query.as_mut() else {
2119                    return internal_err!(
2120                        "Sort between Projection and Unnest requires a statement context."
2121                    );
2122                };
2123                if let Some(fetch) = sort.fetch {
2124                    query_ref.limit(Some(ast::Expr::value(ast::Value::Number(
2125                        fetch.to_string(),
2126                        false,
2127                    ))));
2128                }
2129                // When a flatten_alias is provided, rewrite
2130                // __unnest_placeholder(...) columns in sort expressions to
2131                // alias.VALUE so ORDER BY references the FLATTEN output.
2132                let unnest_node = match sort.input.as_ref() {
2133                    LogicalPlan::Unnest(u) => Some(u),
2134                    _ => find_unnest_node_within_select(sort.input.as_ref()),
2135                };
2136                let sort_exprs = if let Some(alias) = flatten_alias
2137                    && let Some(unnest) = unnest_node
2138                {
2139                    sort.expr
2140                        .iter()
2141                        .map(|s| {
2142                            let rewritten = unproject_unnest_expr_as_flatten_value(
2143                                s.expr.clone(),
2144                                unnest,
2145                                alias,
2146                            )?;
2147                            Ok(SortExpr {
2148                                expr: rewritten,
2149                                ..s.clone()
2150                            })
2151                        })
2152                        .collect::<Result<Vec<_>>>()?
2153                } else {
2154                    sort.expr.clone()
2155                };
2156                query_ref.order_by(self.sorts_to_sql(&sort_exprs)?);
2157                self.peel_to_unnest_with_modifiers(
2158                    sort.input.as_ref(),
2159                    query,
2160                    flatten_alias,
2161                )
2162            }
2163            _ => Ok(None),
2164        }
2165    }
2166
2167    /// Search an expression tree for an unnest placeholder column reference.
2168    ///
2169    /// Returns the [`UnnestInputType`] if any sub-expression is a column
2170    /// whose name starts with `__unnest_placeholder`. The placeholder may
2171    /// be at the top level (bare), inside a function call, or one of several
2172    /// expressions — this function finds it regardless.
2173    fn find_unnest_placeholder(expr: &Expr) -> Option<UnnestInputType> {
2174        let mut result = None;
2175        let _ = expr.apply(|e| {
2176            if let Some(t) = Self::classify_placeholder_column(e) {
2177                result = Some(t);
2178                return Ok(TreeNodeRecursion::Stop);
2179            }
2180            Ok(TreeNodeRecursion::Continue)
2181        });
2182        result
2183    }
2184
2185    /// Returns true if `expr` is a placeholder column, optionally wrapped
2186    /// in a single alias (the rewriter's internal `UNNEST(...)` name).
2187    /// Does NOT match when a user alias wraps the internal alias
2188    /// (e.g. `Alias("c1", Alias("UNNEST(...)", Column(placeholder)))`),
2189    /// so the table-factor path correctly falls through to
2190    /// `reconstruct_select_statement` which preserves user aliases.
2191    fn is_bare_unnest_placeholder(expr: &Expr) -> bool {
2192        // Peel at most one alias layer (the rewriter's internal name).
2193        let inner = match expr {
2194            Expr::Alias(Alias { expr, .. }) => expr.as_ref(),
2195            other => other,
2196        };
2197        Self::classify_placeholder_column(inner).is_some()
2198    }
2199
2200    /// If `expr` is a `Column` whose name starts with `__unnest_placeholder`,
2201    /// classify it as [`UnnestInputType::OuterReference`] or
2202    /// [`UnnestInputType::Scalar`].
2203    fn classify_placeholder_column(expr: &Expr) -> Option<UnnestInputType> {
2204        if let Expr::Column(Column { name, .. }) = expr
2205            && let Some(prefix) = name.strip_prefix(UNNEST_PLACEHOLDER)
2206        {
2207            if prefix.starts_with(&format!("({OUTER_REFERENCE_COLUMN_PREFIX}(")) {
2208                return Some(UnnestInputType::OuterReference);
2209            }
2210            return Some(UnnestInputType::Scalar);
2211        }
2212        None
2213    }
2214
2215    /// Check whether an expression carries an internal `UNNEST(...)` display
2216    /// name as its column name or outermost alias. After
2217    /// [`unproject_unnest_expr_as_flatten_value`] rewrites the placeholder
2218    /// column to `_unnest.VALUE`, the internal alias may still linger
2219    /// (e.g. `Alias("UNNEST(make_array(...))", Column("_unnest.VALUE"))`).
2220    /// Callers use this to replace the expression with a clean
2221    /// `_unnest."VALUE"` select item.
2222    fn has_internal_unnest_alias(expr: &Expr) -> bool {
2223        match expr {
2224            Expr::Column(col) => {
2225                col.name.starts_with(&format!("{UNNEST_COLUMN_PREFIX}("))
2226            }
2227            Expr::Alias(Alias { name, .. }) => {
2228                name.starts_with(&format!("{UNNEST_COLUMN_PREFIX}("))
2229            }
2230            _ => false,
2231        }
2232    }
2233
2234    /// Walk the plan tree and register any SubqueryAlias that wraps an
2235    /// unnest as a FLATTEN table alias on the SelectBuilder. This allows
2236    /// `reconstruct_select_statement` to rewrite column references (e.g.
2237    /// `a.col` → `a.VALUE`) before the SubqueryAlias handler runs.
2238    /// Returns true if a plan tree contains an Unnest node, searching
2239    /// through Projection, Subquery, and SubqueryAlias wrappers.
2240    fn contains_unnest(plan: &LogicalPlan) -> bool {
2241        match plan {
2242            LogicalPlan::Unnest(_) => true,
2243            LogicalPlan::Projection(p) => Self::contains_unnest(&p.input),
2244            LogicalPlan::Subquery(s) => Self::contains_unnest(&s.subquery),
2245            LogicalPlan::SubqueryAlias(a) => Self::contains_unnest(&a.input),
2246            _ => false,
2247        }
2248    }
2249
2250    fn collect_flatten_aliases(plan: &LogicalPlan, select: &mut SelectBuilder) {
2251        match plan {
2252            LogicalPlan::SubqueryAlias(alias)
2253                if Self::contains_unnest(alias.input.as_ref()) =>
2254            {
2255                select.add_flatten_table_alias(alias.alias.table().to_string());
2256            }
2257            LogicalPlan::Join(join) => {
2258                Self::collect_flatten_aliases(&join.left, select);
2259                Self::collect_flatten_aliases(&join.right, select);
2260            }
2261            _ => {}
2262        }
2263    }
2264
2265    fn try_unnest_to_table_factor_sql(
2266        &self,
2267        unnest: &Unnest,
2268    ) -> Result<Option<UnnestRelationBuilder>> {
2269        let mut unnest_relation = UnnestRelationBuilder::default();
2270        let LogicalPlan::Projection(projection) = unnest.input.as_ref() else {
2271            return Ok(None);
2272        };
2273
2274        if !matches!(projection.input.as_ref(), LogicalPlan::EmptyRelation(_)) {
2275            // It may be possible that UNNEST is used as a source for the query.
2276            // However, at this point, we don't yet know if it is just a single expression
2277            // from another source or if it's from UNNEST.
2278            //
2279            // Unnest(Projection(EmptyRelation)) denotes a case with `UNNEST([...])`,
2280            // which is normally safe to unnest as a table factor.
2281            // However, in the future, more comprehensive checks can be added here.
2282            return Ok(None);
2283        }
2284
2285        let exprs = projection
2286            .expr
2287            .iter()
2288            .map(|e| self.expr_to_sql(e))
2289            .collect::<Result<Vec<_>>>()?;
2290        unnest_relation.array_exprs(exprs);
2291
2292        Ok(Some(unnest_relation))
2293    }
2294
2295    /// Build a `SELECT alias."VALUE"` item for Snowflake FLATTEN output.
2296    fn build_flatten_value_select_item(
2297        &self,
2298        flatten_alias: &str,
2299        user_alias: Option<&str>,
2300    ) -> ast::SelectItem {
2301        let compound = ast::Expr::CompoundIdentifier(vec![
2302            self.new_ident_quoted_if_needs(flatten_alias.to_string()),
2303            Ident::with_quote('"', "VALUE"),
2304        ]);
2305        match user_alias {
2306            Some(alias) => ast::SelectItem::ExprWithAlias {
2307                expr: compound,
2308                alias: self.new_ident_quoted_if_needs(alias.to_string()),
2309            },
2310            None => ast::SelectItem::UnnamedExpr(compound),
2311        }
2312    }
2313
2314    /// Convert an `Unnest` logical plan node to a `LATERAL FLATTEN(INPUT => expr, ...)`
2315    /// table factor for Snowflake-style SQL output.
2316    fn try_unnest_to_lateral_flatten_sql(
2317        &self,
2318        unnest: &Unnest,
2319    ) -> Result<Option<FlattenRelationBuilder>> {
2320        let Some(projection) = Self::peel_to_inner_projection(unnest.input.as_ref())
2321        else {
2322            return Ok(None);
2323        };
2324
2325        // For now, handle the simple case of a single expression to flatten.
2326        // Multi-expression would require multiple LATERAL FLATTEN calls chained together.
2327        let Some(first_expr) = projection.expr.first() else {
2328            return Ok(None);
2329        };
2330
2331        let input_expr = self.expr_to_sql(first_expr)?;
2332
2333        let mut flatten = FlattenRelationBuilder::default();
2334        flatten.input_expr(input_expr);
2335        flatten.outer(unnest.options.preserve_nulls());
2336
2337        Ok(Some(flatten))
2338    }
2339
2340    fn is_scan_with_pushdown(scan: &TableScan) -> bool {
2341        scan.projection.is_some()
2342            || !scan.filters.is_empty()
2343            || scan.fetch.is_some()
2344            || scan.skip.is_some()
2345    }
2346
2347    /// Returns true if a plan, when used as the direct child of a SubqueryAlias,
2348    /// must be emitted as a derived subquery `(SELECT ...) AS alias`.
2349    ///
2350    /// Plans like Aggregate or Window build their own SELECT clauses (GROUP BY,
2351    /// window functions).
2352    fn requires_derived_subquery(plan: &LogicalPlan) -> bool {
2353        matches!(
2354            plan,
2355            LogicalPlan::Aggregate(_)
2356                | LogicalPlan::Window(_)
2357                | LogicalPlan::Sort(_)
2358                | LogicalPlan::Limit(_)
2359                | LogicalPlan::Union(_)
2360        )
2361    }
2362
2363    fn asof_input_requires_derived(plan: &LogicalPlan) -> bool {
2364        let simple_scan =
2365            |scan: &TableScan| scan.filters.is_empty() && scan.fetch.is_none();
2366        match plan {
2367            LogicalPlan::TableScan(scan) => !simple_scan(scan),
2368            LogicalPlan::SubqueryAlias(alias) => {
2369                !matches!(alias.input.as_ref(), LogicalPlan::TableScan(scan) if simple_scan(scan))
2370            }
2371            _ => true,
2372        }
2373    }
2374
2375    fn derive_asof_input(
2376        &self,
2377        plan: &LogicalPlan,
2378        relation: &mut RelationBuilder,
2379    ) -> Result<Option<TableReference>> {
2380        if let LogicalPlan::SubqueryAlias(alias) = plan {
2381            let (inner, columns) = subquery_alias_inner_query_and_columns(alias);
2382            let table_alias = alias.alias.clone();
2383            if !columns.is_empty() && !self.dialect.supports_column_alias_in_table_alias()
2384            {
2385                let rewritten =
2386                    inject_column_aliases_into_subquery(inner.clone(), columns)?;
2387                self.derive(
2388                    &rewritten,
2389                    relation,
2390                    Some(self.new_table_alias(table_alias.table().to_string(), vec![])),
2391                    false,
2392                )?;
2393            } else {
2394                self.derive(
2395                    inner,
2396                    relation,
2397                    Some(self.new_table_alias(table_alias.table().to_string(), columns)),
2398                    false,
2399                )?;
2400            }
2401            return Ok(Some(table_alias));
2402        }
2403
2404        let qualifier = plan
2405            .schema()
2406            .iter()
2407            .find_map(|(qualifier, _)| qualifier.cloned());
2408        let alias = qualifier
2409            .as_ref()
2410            .map(|qualifier| self.new_table_alias(qualifier.table().to_string(), vec![]));
2411        self.derive(plan, relation, alias, false)?;
2412        Ok(qualifier)
2413    }
2414
2415    fn derived_input_projection(
2416        &self,
2417        plan: &LogicalPlan,
2418        qualifier: Option<&TableReference>,
2419    ) -> Result<Vec<ast::SelectItem>> {
2420        plan.schema()
2421            .iter()
2422            .map(|(field_qualifier, field)| {
2423                self.select_item_to_sql(&Expr::Column(Column::new(
2424                    qualifier.cloned().or_else(|| field_qualifier.cloned()),
2425                    field.name(),
2426                )))
2427            })
2428            .collect()
2429    }
2430
2431    fn is_qualified_passthrough_projection(projection: &Projection) -> bool {
2432        projection
2433            .expr
2434            .iter()
2435            .all(|expr| matches!(expr, Expr::Column(column) if column.relation.is_some()))
2436    }
2437
2438    fn unwrap_qualified_passthrough_join_projection(
2439        plan: Arc<LogicalPlan>,
2440    ) -> Arc<LogicalPlan> {
2441        if let LogicalPlan::Projection(projection) = plan.as_ref()
2442            && matches!(
2443                projection.input.as_ref(),
2444                LogicalPlan::Join(_) | LogicalPlan::AsOfJoin(_)
2445            )
2446            && Self::is_qualified_passthrough_projection(projection)
2447        {
2448            Arc::clone(&projection.input)
2449        } else {
2450            plan
2451        }
2452    }
2453
2454    fn join_input_to_nested_relation(
2455        &self,
2456        plan: &LogicalPlan,
2457        query: &mut Option<QueryBuilder>,
2458    ) -> Result<Option<RelationBuilder>> {
2459        let join_plan = match plan {
2460            LogicalPlan::Join(_) | LogicalPlan::AsOfJoin(_) => plan,
2461            LogicalPlan::Projection(projection)
2462                if matches!(
2463                    projection.input.as_ref(),
2464                    LogicalPlan::Join(_) | LogicalPlan::AsOfJoin(_)
2465                ) && Self::is_qualified_passthrough_projection(projection) =>
2466            {
2467                projection.input.as_ref()
2468            }
2469            _ => return Ok(None),
2470        };
2471
2472        let original_query = query.clone();
2473        let mut nested_select = SelectBuilder::default();
2474        nested_select.push_from(TableWithJoinsBuilder::default());
2475        let mut nested_relation = RelationBuilder::default();
2476        self.select_to_sql_recursively(
2477            join_plan,
2478            query,
2479            &mut nested_select,
2480            &mut nested_relation,
2481        )?;
2482        if nested_select.has_selection() {
2483            *query = original_query;
2484            return Ok(None);
2485        }
2486
2487        let Some(mut nested_from) = nested_select.pop_from() else {
2488            return internal_err!("Failed to build nested join input relation");
2489        };
2490        nested_from.relation(nested_relation);
2491        let Some(table_with_joins) = nested_from.build()? else {
2492            return internal_err!("Failed to build nested join input relation");
2493        };
2494
2495        let mut relation = RelationBuilder::default();
2496        relation.nested_join(table_with_joins, None);
2497        Ok(Some(relation))
2498    }
2499
2500    /// Strip the table qualifier from every column in an expression that must
2501    /// resolve against an unnamed derived table's output columns rather than a
2502    /// deeper table alias that is out of scope at this nesting level.
2503    fn strip_column_qualifiers(expr: Expr) -> Result<Expr> {
2504        expr.transform(|e| match e {
2505            Expr::Column(mut column) => {
2506                column.relation = None;
2507                Ok(Transformed::yes(Expr::Column(column)))
2508            }
2509            other => Ok(Transformed::no(other)),
2510        })
2511        .data()
2512    }
2513
2514    fn strip_column_qualifiers_for_schema(expr: Expr, schema: &DFSchema) -> Result<Expr> {
2515        expr.transform(|e| match e {
2516            Expr::Column(mut column)
2517                if column.relation.is_some()
2518                    && schema.index_of_column(&column).is_ok() =>
2519            {
2520                column.relation = None;
2521                Ok(Transformed::yes(Expr::Column(column)))
2522            }
2523            other => Ok(Transformed::no(other)),
2524        })
2525        .data()
2526    }
2527
2528    /// Try to unparse a table scan with pushdown operations into a new subquery plan.
2529    /// If the table scan is without any pushdown operations, return None.
2530    fn unparse_table_scan_pushdown(
2531        &self,
2532        plan: &LogicalPlan,
2533        alias: Option<TableReference>,
2534        already_projected: bool,
2535    ) -> Result<Option<LogicalPlan>> {
2536        match plan {
2537            LogicalPlan::TableScan(table_scan) => {
2538                if !Self::is_scan_with_pushdown(table_scan) {
2539                    return Ok(None);
2540                }
2541                let table_schema = table_scan.source.schema();
2542                let filter_schema = DFSchema::try_from_qualified_schema(
2543                    table_scan.table_name.clone(),
2544                    table_schema.as_ref(),
2545                )?;
2546                let mut filter_alias_rewriter =
2547                    alias.as_ref().map(|alias_name| TableAliasRewriter {
2548                        table_schema: &filter_schema,
2549                        alias_name: alias_name.clone(),
2550                        rewrite_unqualified: true,
2551                    });
2552
2553                let mut builder = LogicalPlanBuilder::scan(
2554                    table_scan.table_name.clone(),
2555                    Arc::clone(&table_scan.source),
2556                    None,
2557                )?;
2558                // We will rebase the column references to the new alias if it exists.
2559                // If the projection or filters are empty, we will append alias to the table scan.
2560                //
2561                // Example:
2562                //   select t1.c1 from t1 where t1.c1 > 1 -> select a.c1 from t1 as a where a.c1 > 1
2563                if let Some(ref alias) = alias
2564                    && (table_scan.projection.is_some() || !table_scan.filters.is_empty())
2565                {
2566                    builder = builder.alias(alias.clone())?;
2567                }
2568
2569                // Avoid creating a duplicate Projection node, which would result in an additional subquery if a projection already exists.
2570                // For example, if the `optimize_projection` rule is applied, there will be a Projection node, and duplicate projection
2571                // information included in the TableScan node.
2572                if !already_projected && let Some(project_vec) = &table_scan.projection {
2573                    if project_vec.is_empty() {
2574                        builder = builder.project(self.empty_projection_fallback())?;
2575                    } else {
2576                        let schema = table_scan.source.schema();
2577                        let project_columns = project_vec
2578                            .iter()
2579                            .copied()
2580                            .map(|i| {
2581                                let field = schema.field(i);
2582                                if alias.is_some() {
2583                                    Column::new(alias.clone(), field.name().clone())
2584                                } else {
2585                                    Column::new(
2586                                        Some(table_scan.table_name.clone()),
2587                                        field.name().clone(),
2588                                    )
2589                                }
2590                            })
2591                            .collect::<Vec<_>>();
2592                        builder = builder.project(project_columns)?;
2593                    }
2594                }
2595
2596                let filter_expr: Result<Option<Expr>> = table_scan
2597                    .filters
2598                    .iter()
2599                    .cloned()
2600                    .map(|expr| {
2601                        if let Some(ref mut rewriter) = filter_alias_rewriter {
2602                            expr.rewrite(rewriter).data()
2603                        } else {
2604                            Ok(expr)
2605                        }
2606                    })
2607                    .reduce(|acc, expr_result| {
2608                        acc.and_then(|acc_expr| {
2609                            expr_result.map(|expr| acc_expr.and(expr))
2610                        })
2611                    })
2612                    .transpose();
2613
2614                if let Some(filter) = filter_expr? {
2615                    builder = builder.filter(filter)?;
2616                }
2617
2618                match (table_scan.skip, table_scan.fetch) {
2619                    (Some(offset), Some(fetch)) => {
2620                        builder = builder.limit(offset, Some(fetch))?
2621                    }
2622                    (Some(offset), None) => builder = builder.limit(offset, None)?,
2623                    (None, Some(fetch)) => builder = builder.limit(0, Some(fetch))?,
2624                    (None, None) => (),
2625                }
2626
2627                // If the table scan has an alias but no projection or filters, it means no column references are rebased.
2628                // So we will append the alias to this subquery.
2629                // Example:
2630                //   select * from t1 limit 10 -> (select * from t1 limit 10) as a
2631                if let Some(alias) = alias
2632                    && table_scan.projection.is_none()
2633                    && table_scan.filters.is_empty()
2634                {
2635                    builder = builder.alias(alias)?;
2636                }
2637
2638                Ok(Some(builder.build()?))
2639            }
2640            LogicalPlan::SubqueryAlias(subquery_alias) => {
2641                let ret = self.unparse_table_scan_pushdown(
2642                    &subquery_alias.input,
2643                    Some(subquery_alias.alias.clone()),
2644                    already_projected,
2645                )?;
2646                if let Some(alias) = alias
2647                    && let Some(plan) = ret
2648                {
2649                    let plan = LogicalPlanBuilder::new(plan).alias(alias)?.build()?;
2650                    return Ok(Some(plan));
2651                }
2652                Ok(ret)
2653            }
2654            // SubqueryAlias could be rewritten to a plan with a projection as the top node by [rewrite::subquery_alias_inner_query_and_columns].
2655            // The inner table scan could be a scan with pushdown operations.
2656            LogicalPlan::Projection(projection) => {
2657                if let Some(plan) = self.unparse_table_scan_pushdown(
2658                    &projection.input,
2659                    alias.clone(),
2660                    already_projected,
2661                )? {
2662                    // The pushed-down scan alias is only in scope for the
2663                    // projection directly above the aliased table scan. `plan`
2664                    // is the result of pushing the alias further down: if it is
2665                    // itself a `Projection`, the input was another projection
2666                    // (e.g. common subexpression elimination stacked one), so
2667                    // this projection sits over a derived table rather than
2668                    // directly over the aliased scan, and the alias is out of
2669                    // scope here. Its qualified pass-through columns must then
2670                    // reference the derived table's output unqualified instead
2671                    // of being rebased to the alias. Build it directly so the
2672                    // unqualified columns are not re-normalized back to the
2673                    // alias. (Otherwise `plan` is the scan-derived plan and we
2674                    // fall through to rebase to the alias, correct one level
2675                    // above the scan.)
2676                    if alias.is_some() && matches!(plan, LogicalPlan::Projection(_)) {
2677                        let exprs = projection
2678                            .expr
2679                            .iter()
2680                            .cloned()
2681                            .map(Self::strip_column_qualifiers)
2682                            .collect::<Result<Vec<_>>>()?;
2683                        return Ok(Some(LogicalPlan::Projection(Projection::try_new(
2684                            exprs,
2685                            Arc::new(plan),
2686                        )?)));
2687                    }
2688
2689                    let exprs = if alias.is_some() {
2690                        let mut alias_rewriter =
2691                            alias.as_ref().map(|alias_name| TableAliasRewriter {
2692                                table_schema: plan.schema().as_ref(),
2693                                alias_name: alias_name.clone(),
2694                                rewrite_unqualified: false,
2695                            });
2696                        projection
2697                            .expr
2698                            .iter()
2699                            .cloned()
2700                            .map(|expr| {
2701                                if let Some(ref mut rewriter) = alias_rewriter {
2702                                    expr.rewrite(rewriter).data()
2703                                } else {
2704                                    Ok(expr)
2705                                }
2706                            })
2707                            .collect::<Result<Vec<_>>>()?
2708                    } else {
2709                        projection.expr.clone()
2710                    };
2711                    Ok(Some(
2712                        LogicalPlanBuilder::from(plan).project(exprs)?.build()?,
2713                    ))
2714                } else {
2715                    Ok(None)
2716                }
2717            }
2718            _ => Ok(None),
2719        }
2720    }
2721
2722    fn select_item_to_sql(&self, expr: &Expr) -> Result<ast::SelectItem> {
2723        match expr {
2724            Expr::Alias(Alias { expr, name, .. }) => {
2725                let inner = self.expr_to_sql(expr)?;
2726
2727                Ok(ast::SelectItem::ExprWithAlias {
2728                    expr: inner,
2729                    alias: self.column_alias_to_sql(name)?,
2730                })
2731            }
2732            _ => {
2733                let inner = self.expr_to_sql(expr)?;
2734
2735                Ok(ast::SelectItem::UnnamedExpr(inner))
2736            }
2737        }
2738    }
2739
2740    fn column_alias_to_sql(&self, name: &str) -> Result<Ident> {
2741        let name = self
2742            .dialect
2743            .col_alias_overrides(name)?
2744            .unwrap_or_else(|| name.to_string());
2745        Ok(self.new_ident_quoted_if_needs(name))
2746    }
2747
2748    fn sorts_to_sql(&self, sort_exprs: &[SortExpr]) -> Result<OrderByKind> {
2749        Ok(OrderByKind::Expressions(
2750            sort_exprs
2751                .iter()
2752                .map(|sort_expr| self.sort_to_sql(sort_expr))
2753                .collect::<Result<Vec<_>>>()?,
2754        ))
2755    }
2756
2757    fn join_operator_to_sql(
2758        &self,
2759        join_type: JoinType,
2760        constraint: ast::JoinConstraint,
2761    ) -> Result<ast::JoinOperator> {
2762        Ok(match join_type {
2763            JoinType::Inner => match &constraint {
2764                ast::JoinConstraint::On(_)
2765                | ast::JoinConstraint::Using(_)
2766                | ast::JoinConstraint::Natural => ast::JoinOperator::Inner(constraint),
2767                ast::JoinConstraint::None => {
2768                    // Inner joins with no conditions or filters are not valid SQL in most systems,
2769                    // return a CROSS JOIN instead
2770                    ast::JoinOperator::CrossJoin(constraint)
2771                }
2772            },
2773            JoinType::Left => ast::JoinOperator::LeftOuter(constraint),
2774            JoinType::Right => ast::JoinOperator::RightOuter(constraint),
2775            JoinType::Full => ast::JoinOperator::FullOuter(constraint),
2776            JoinType::LeftAnti => ast::JoinOperator::LeftAnti(constraint),
2777            JoinType::LeftSemi => ast::JoinOperator::LeftSemi(constraint),
2778            JoinType::RightAnti => ast::JoinOperator::RightAnti(constraint),
2779            JoinType::RightSemi => ast::JoinOperator::RightSemi(constraint),
2780            JoinType::LeftMark | JoinType::RightMark => {
2781                unimplemented!("Unparsing of Mark join type")
2782            }
2783        })
2784    }
2785
2786    /// Convert the components of a USING clause to the USING AST. Returns
2787    /// 'None' if the conditions are not compatible with a USING expression,
2788    /// e.g. non-column expressions or non-matching names.
2789    fn join_using_to_sql(
2790        &self,
2791        join_conditions: &[(Expr, Expr)],
2792    ) -> Option<ast::JoinConstraint> {
2793        let mut object_names = Vec::with_capacity(join_conditions.len());
2794        for (left, right) in join_conditions {
2795            match (left, right) {
2796                (
2797                    Expr::Column(Column {
2798                        relation: _,
2799                        name: left_name,
2800                        spans: _,
2801                    }),
2802                    Expr::Column(Column {
2803                        relation: _,
2804                        name: right_name,
2805                        spans: _,
2806                    }),
2807                ) if left_name == right_name => {
2808                    // For example, if the join condition `t1.id = t2.id`
2809                    // this is represented as two columns like `[t1.id, t2.id]`
2810                    // This code forms `id` (without relation name)
2811                    let ident = self.new_ident_quoted_if_needs(left_name.to_string());
2812                    object_names.push(ast::ObjectName::from(vec![ident]));
2813                }
2814                // USING is only valid with matching column names; arbitrary expressions
2815                // are not allowed
2816                _ => return None,
2817            }
2818        }
2819        Some(ast::JoinConstraint::Using(object_names))
2820    }
2821
2822    /// Convert a join constraint and associated conditions and filter to a SQL AST node
2823    fn join_constraint_to_sql(
2824        &self,
2825        constraint: JoinConstraint,
2826        conditions: &[(Expr, Expr)],
2827        filter: Option<&Expr>,
2828    ) -> Result<ast::JoinConstraint> {
2829        match (constraint, conditions, filter) {
2830            // No constraints
2831            (JoinConstraint::On | JoinConstraint::Using, [], None) => {
2832                Ok(ast::JoinConstraint::None)
2833            }
2834
2835            (JoinConstraint::Using, conditions, None) => {
2836                match self.join_using_to_sql(conditions) {
2837                    Some(using) => Ok(using),
2838                    // As above, this should not be reachable from parsed SQL,
2839                    // but a user could create this; we "downgrade" to ON.
2840                    None => self.join_conditions_to_sql_on(conditions, None),
2841                }
2842            }
2843
2844            // Two cases here:
2845            // 1. Straightforward ON case, with possible equi-join conditions
2846            //    and additional filters
2847            // 2. USING with additional filters; we "downgrade" to ON, because
2848            //    you can't use USING with arbitrary filters. (This should not
2849            //    be accessible from parsed SQL, but may have been a
2850            //    custom-built JOIN by a user.)
2851            (JoinConstraint::On | JoinConstraint::Using, conditions, filter) => {
2852                self.join_conditions_to_sql_on(conditions, filter)
2853            }
2854        }
2855    }
2856
2857    // Convert a list of equi0join conditions and an optional filter to a SQL ON
2858    // AST node, with the equi-join conditions and the filter merged into a
2859    // single conditional expression
2860    fn join_conditions_to_sql_on(
2861        &self,
2862        join_conditions: &[(Expr, Expr)],
2863        filter: Option<&Expr>,
2864    ) -> Result<ast::JoinConstraint> {
2865        let mut condition = None;
2866        // AND the join conditions together to create the overall condition
2867        for (left, right) in join_conditions {
2868            // Parse left and right
2869            let l = self.expr_to_sql(left)?;
2870            let r = self.expr_to_sql(right)?;
2871            let e = self.binary_op_to_sql(l, r, ast::BinaryOperator::Eq);
2872            condition = match condition {
2873                Some(expr) => Some(self.and_op_to_sql(expr, e)),
2874                None => Some(e),
2875            };
2876        }
2877
2878        // Then AND the non-equijoin filter condition as well
2879        condition = match (condition, filter) {
2880            (Some(expr), Some(filter)) => {
2881                Some(self.and_op_to_sql(expr, self.expr_to_sql(filter)?))
2882            }
2883            (Some(expr), None) => Some(expr),
2884            (None, Some(filter)) => Some(self.expr_to_sql(filter)?),
2885            (None, None) => None,
2886        };
2887
2888        let constraint = match condition {
2889            Some(filter) => ast::JoinConstraint::On(filter),
2890            None => ast::JoinConstraint::None,
2891        };
2892
2893        Ok(constraint)
2894    }
2895
2896    fn and_op_to_sql(&self, lhs: ast::Expr, rhs: ast::Expr) -> ast::Expr {
2897        self.binary_op_to_sql(lhs, rhs, ast::BinaryOperator::And)
2898    }
2899
2900    fn new_table_alias(&self, alias: String, columns: Vec<Ident>) -> ast::TableAlias {
2901        let columns = columns
2902            .into_iter()
2903            .map(|ident| TableAliasColumnDef {
2904                name: ident,
2905                data_type: None,
2906            })
2907            .collect();
2908        ast::TableAlias {
2909            name: self.new_ident_quoted_if_needs(alias),
2910            columns,
2911            explicit: true,
2912            at: None,
2913        }
2914    }
2915
2916    fn dml_to_sql(&self, plan: &LogicalPlan) -> Result<ast::Statement> {
2917        not_impl_err!("Unsupported plan: {plan:?}")
2918    }
2919
2920    /// Generates appropriate projection expression for empty projection lists.
2921    /// Returns an empty vec for dialects supporting empty select lists,
2922    /// or a dummy literal `1` for other dialects.
2923    fn empty_projection_fallback(&self) -> Vec<Expr> {
2924        if self.dialect.supports_empty_select_list() {
2925            Vec::new()
2926        } else {
2927            vec![Expr::Literal(ScalarValue::Int64(Some(1)), None)]
2928        }
2929    }
2930
2931    /// Decides where extracted table-scan filters belong in the unparsed SQL:
2932    /// in the `JOIN ON` clause or in `WHERE`.
2933    ///
2934    /// For inner joins the two are semantically equivalent, so filters go to
2935    /// `WHERE` (some dialects reject subqueries inside `JOIN ON`).
2936    /// For outer joins the filters are AND-folded into `ON` to preserve correctness.
2937    ///
2938    /// Returns `(on_filter, where_filters)`.
2939    fn split_join_on_and_where_filters(
2940        join_type: JoinType,
2941        join_filter: Option<&Expr>,
2942        table_scan_filters: Vec<Expr>,
2943    ) -> (Option<Expr>, Vec<Expr>) {
2944        if table_scan_filters.is_empty() {
2945            return (join_filter.cloned(), vec![]);
2946        }
2947
2948        if join_type == JoinType::Inner {
2949            // ON and WHERE are equivalent for inner joins; prefer WHERE
2950            // because some dialects reject subqueries inside JOIN ON.
2951            return (join_filter.cloned(), table_scan_filters);
2952        }
2953
2954        // Outer joins: fold table-scan filters into ON to preserve semantics.
2955        let combined = table_scan_filters.into_iter().reduce(|acc, filter| {
2956            Expr::BinaryExpr(BinaryExpr {
2957                left: Box::new(acc),
2958                op: Operator::And,
2959                right: Box::new(filter),
2960            })
2961        });
2962
2963        let on_filter = match (join_filter, combined) {
2964            (Some(jf), Some(c)) => Some(Expr::BinaryExpr(BinaryExpr {
2965                left: Box::new(jf.clone()),
2966                op: Operator::And,
2967                right: Box::new(c),
2968            })),
2969            (Some(jf), None) => Some(jf.clone()),
2970            (None, Some(c)) => Some(c),
2971            (None, None) => None,
2972        };
2973
2974        (on_filter, vec![])
2975    }
2976}
2977
2978impl From<BuilderError> for DataFusionError {
2979    fn from(e: BuilderError) -> Self {
2980        DataFusionError::External(Box::new(e))
2981    }
2982}
2983
2984/// The type of the input to the UNNEST table factor.
2985#[derive(Debug)]
2986enum UnnestInputType {
2987    /// The input is a column reference. It will be presented like `outer_ref(column_name)`.
2988    OuterReference,
2989    /// The input is a scalar value. It will be presented like a scalar array or struct.
2990    Scalar,
2991}