Skip to main content

datafusion_sql/unparser/
ast.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 core::fmt;
6use std::ops::ControlFlow;
7
8use sqlparser::ast::helpers::attached_token::AttachedToken;
9use sqlparser::ast::{
10    self, LimitClause, OrderByKind, SelectFlavor, visit_expressions_mut,
11};
12
13#[derive(Clone)]
14pub struct QueryBuilder {
15    with: Option<ast::With>,
16    body: Option<Box<ast::SetExpr>>,
17    order_by_kind: Option<OrderByKind>,
18    limit: Option<ast::Expr>,
19    limit_by: Vec<ast::Expr>,
20    offset: Option<ast::Offset>,
21    fetch: Option<ast::Fetch>,
22    locks: Vec<ast::LockClause>,
23    for_clause: Option<ast::ForClause>,
24    // If true, we need to unparse LogicalPlan::Union as a SQL `UNION` rather than a `UNION ALL`.
25    distinct_union: bool,
26}
27
28impl QueryBuilder {
29    pub fn with(&mut self, value: Option<ast::With>) -> &mut Self {
30        self.with = value;
31        self
32    }
33    pub fn body(&mut self, value: Box<ast::SetExpr>) -> &mut Self {
34        self.body = Some(value);
35        self
36    }
37    pub fn take_body(&mut self) -> Option<Box<ast::SetExpr>> {
38        self.body.take()
39    }
40    pub fn order_by(&mut self, value: OrderByKind) -> &mut Self {
41        self.order_by_kind = Some(value);
42        self
43    }
44    pub fn limit(&mut self, value: Option<ast::Expr>) -> &mut Self {
45        self.limit = value;
46        self
47    }
48    pub fn limit_by(&mut self, value: Vec<ast::Expr>) -> &mut Self {
49        self.limit_by = value;
50        self
51    }
52    pub fn offset(&mut self, value: Option<ast::Offset>) -> &mut Self {
53        self.offset = value;
54        self
55    }
56    pub fn fetch(&mut self, value: Option<ast::Fetch>) -> &mut Self {
57        self.fetch = value;
58        self
59    }
60    pub fn locks(&mut self, value: Vec<ast::LockClause>) -> &mut Self {
61        self.locks = value;
62        self
63    }
64    pub fn for_clause(&mut self, value: Option<ast::ForClause>) -> &mut Self {
65        self.for_clause = value;
66        self
67    }
68    pub fn distinct_union(&mut self) -> &mut Self {
69        self.distinct_union = true;
70        self
71    }
72    pub fn is_distinct_union(&self) -> bool {
73        self.distinct_union
74    }
75    pub fn build(&self) -> Result<ast::Query, BuilderError> {
76        let order_by = self
77            .order_by_kind
78            .as_ref()
79            .map(|order_by_kind| ast::OrderBy {
80                kind: order_by_kind.clone(),
81                interpolate: None,
82            });
83
84        Ok(ast::Query {
85            with: self.with.clone(),
86            body: match self.body {
87                Some(ref value) => value.clone(),
88                None => return Err(Into::into(UninitializedFieldError::from("body"))),
89            },
90            order_by,
91            limit_clause: Some(LimitClause::LimitOffset {
92                limit: self.limit.clone(),
93                offset: self.offset.clone(),
94                limit_by: self.limit_by.clone(),
95            }),
96            fetch: self.fetch.clone(),
97            locks: self.locks.clone(),
98            for_clause: self.for_clause.clone(),
99            settings: None,
100            format_clause: None,
101            pipe_operators: vec![],
102        })
103    }
104    fn create_empty() -> Self {
105        Self {
106            with: Default::default(),
107            body: Default::default(),
108            order_by_kind: Default::default(),
109            limit: Default::default(),
110            limit_by: Default::default(),
111            offset: Default::default(),
112            fetch: Default::default(),
113            locks: Default::default(),
114            for_clause: Default::default(),
115            distinct_union: false,
116        }
117    }
118}
119impl Default for QueryBuilder {
120    fn default() -> Self {
121        Self::create_empty()
122    }
123}
124
125#[derive(Clone)]
126pub struct SelectBuilder {
127    distinct: Option<ast::Distinct>,
128    top: Option<ast::Top>,
129    /// Projection items for the SELECT clause.
130    ///
131    /// This field uses `Option` to distinguish between three distinct states:
132    /// - `None`: No projection has been set (not yet initialized)
133    /// - `Some(vec![])`: Empty projection explicitly set (generates `SELECT FROM ...` or `SELECT 1 FROM ...`)
134    /// - `Some(vec![SelectItem::Wildcard(...)])`: Wildcard projection (generates `SELECT * FROM ...`)
135    /// - `Some(vec![...])`: Non-empty projection with specific columns/expressions
136    ///
137    /// Use `projection()` to set this field and `already_projected()` to check if it has been set.
138    projection: Option<Vec<ast::SelectItem>>,
139    into: Option<ast::SelectInto>,
140    from: Vec<TableWithJoinsBuilder>,
141    lateral_views: Vec<ast::LateralView>,
142    selection: Option<ast::Expr>,
143    group_by: Option<ast::GroupByExpr>,
144    cluster_by: Vec<ast::Expr>,
145    distribute_by: Vec<ast::Expr>,
146    sort_by: Vec<ast::OrderByExpr>,
147    having: Option<ast::Expr>,
148    named_window: Vec<ast::NamedWindowDefinition>,
149    qualify: Option<ast::Expr>,
150    value_table_mode: Option<ast::ValueTableMode>,
151    flavor: Option<SelectFlavor>,
152    /// Counter for generating unique LATERAL FLATTEN aliases within this SELECT.
153    flatten_alias_counter: usize,
154    /// Table aliases that correspond to LATERAL FLATTEN relations.
155    /// Column references into these aliases must use `VALUE` as the column name.
156    flatten_table_aliases: Vec<String>,
157    /// Depth of explicitly named subqueries currently being rendered.
158    subquery_alias_depth: usize,
159}
160
161/// Prefix used for auto-generated LATERAL FLATTEN table aliases.
162const FLATTEN_ALIAS_PREFIX: &str = "_unnest";
163
164impl SelectBuilder {
165    /// Generate a unique alias for a LATERAL FLATTEN relation
166    /// (`_unnest_1`, `_unnest_2`, …). Each call returns a fresh name.
167    pub fn next_flatten_alias(&mut self) -> String {
168        self.flatten_alias_counter += 1;
169        format!("{FLATTEN_ALIAS_PREFIX}_{}", self.flatten_alias_counter)
170    }
171
172    /// Register a table alias as pointing to a LATERAL FLATTEN relation.
173    pub fn add_flatten_table_alias(&mut self, alias: String) {
174        self.flatten_table_aliases.push(alias);
175    }
176
177    /// Returns true if no FLATTEN table aliases have been registered.
178    pub fn flatten_table_aliases_empty(&self) -> bool {
179        self.flatten_table_aliases.is_empty()
180    }
181
182    /// Returns true if the given table alias refers to a FLATTEN relation.
183    pub fn is_flatten_table_alias(&self, alias: &str) -> bool {
184        self.flatten_table_aliases.iter().any(|a| a == alias)
185    }
186
187    pub(super) fn enter_subquery_alias(&mut self) {
188        self.subquery_alias_depth += 1;
189    }
190
191    pub(super) fn exit_subquery_alias(&mut self) {
192        debug_assert!(self.subquery_alias_depth > 0);
193        self.subquery_alias_depth -= 1;
194    }
195
196    pub(super) fn inside_subquery_alias(&self) -> bool {
197        self.subquery_alias_depth > 0
198    }
199
200    /// Returns the most recently generated flatten alias, or `None` if
201    /// `next_flatten_alias` has not been called yet.
202    pub fn current_flatten_alias(&self) -> Option<String> {
203        if self.flatten_alias_counter > 0 {
204            Some(format!(
205                "{FLATTEN_ALIAS_PREFIX}_{}",
206                self.flatten_alias_counter
207            ))
208        } else {
209            None
210        }
211    }
212
213    pub fn distinct(&mut self, value: Option<ast::Distinct>) -> &mut Self {
214        self.distinct = value;
215        self
216    }
217    pub fn top(&mut self, value: Option<ast::Top>) -> &mut Self {
218        self.top = value;
219        self
220    }
221    pub fn projection(&mut self, value: Vec<ast::SelectItem>) -> &mut Self {
222        self.projection = Some(value);
223        self
224    }
225    pub fn pop_projections(&mut self) -> Vec<ast::SelectItem> {
226        self.projection.take().unwrap_or_default()
227    }
228    /// Returns true if a projection has been explicitly set via `projection()`.
229    ///
230    /// This method is used to determine whether the SELECT clause has already been
231    /// defined, which helps avoid creating duplicate projection nodes during query
232    /// unparsing. It returns `true` for both empty and non-empty projections.
233    ///
234    /// # Returns
235    ///
236    /// - `true` if `projection()` has been called (regardless of whether it was empty or not)
237    /// - `false` if no projection has been set yet
238    ///
239    /// # Example
240    ///
241    /// ```ignore
242    /// let mut builder = SelectBuilder::default();
243    /// assert!(!builder.already_projected());
244    ///
245    /// builder.projection(vec![]);
246    /// assert!(builder.already_projected()); // true even for empty projection
247    ///
248    /// builder.projection(vec![SelectItem::Wildcard(...)]);
249    /// assert!(builder.already_projected()); // true for non-empty projection
250    /// ```
251    pub fn already_projected(&self) -> bool {
252        self.projection.is_some()
253    }
254    pub fn into(&mut self, value: Option<ast::SelectInto>) -> &mut Self {
255        self.into = value;
256        self
257    }
258    pub fn from(&mut self, value: Vec<TableWithJoinsBuilder>) -> &mut Self {
259        self.from = value;
260        self
261    }
262    pub fn push_from(&mut self, value: TableWithJoinsBuilder) -> &mut Self {
263        self.from.push(value);
264        self
265    }
266    pub fn pop_from(&mut self) -> Option<TableWithJoinsBuilder> {
267        self.from.pop()
268    }
269    pub fn has_selection(&self) -> bool {
270        self.selection.is_some()
271    }
272    pub fn lateral_views(&mut self, value: Vec<ast::LateralView>) -> &mut Self {
273        self.lateral_views = value;
274        self
275    }
276
277    /// Replaces the selection with a new value.
278    ///
279    /// This function is used to replace a specific expression within the selection.
280    /// Unlike the `selection` method which combines existing and new selections with AND,
281    /// this method searches for and replaces occurrences of a specific expression.
282    ///
283    /// This method is primarily used to modify LEFT MARK JOIN expressions.
284    /// When processing a LEFT MARK JOIN, we need to replace the placeholder expression
285    /// with the actual join condition in the selection clause.
286    ///
287    /// # Arguments
288    ///
289    /// * `existing_expr` - The expression to replace
290    /// * `value` - The new expression to set as the selection
291    pub fn replace_mark(
292        &mut self,
293        existing_expr: &ast::Expr,
294        value: &ast::Expr,
295    ) -> &mut Self {
296        if let Some(selection) = &mut self.selection {
297            let _ = visit_expressions_mut(selection, |expr| {
298                if expr == existing_expr {
299                    *expr = value.clone();
300                }
301                ControlFlow::<()>::Continue(())
302            });
303        }
304        self
305    }
306
307    pub fn selection(&mut self, value: Option<ast::Expr>) -> &mut Self {
308        // With filter pushdown optimization, the LogicalPlan can have filters defined as part of `TableScan` and `Filter` nodes.
309        // To avoid overwriting one of the filters, we combine the existing filter with the additional filter.
310        // Example:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
311        // |  Projection: customer.c_phone AS cntrycode, customer.c_acctbal                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
312        // |   Filter: CAST(customer.c_acctbal AS Decimal128(38, 6)) > (<subquery>)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
313        // |     Subquery:
314        // |     ..                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
315        // |     TableScan: customer, full_filters=[customer.c_mktsegment = Utf8("BUILDING")]
316        match (&self.selection, value) {
317            (Some(existing_selection), Some(new_selection)) => {
318                self.selection = Some(ast::Expr::BinaryOp {
319                    left: Box::new(existing_selection.clone()),
320                    op: ast::BinaryOperator::And,
321                    right: Box::new(new_selection),
322                });
323            }
324            (None, Some(new_selection)) => {
325                self.selection = Some(new_selection);
326            }
327            (_, None) => (),
328        }
329
330        self
331    }
332    pub fn group_by(&mut self, value: ast::GroupByExpr) -> &mut Self {
333        self.group_by = Some(value);
334        self
335    }
336    pub fn cluster_by(&mut self, value: Vec<ast::Expr>) -> &mut Self {
337        self.cluster_by = value;
338        self
339    }
340    pub fn distribute_by(&mut self, value: Vec<ast::Expr>) -> &mut Self {
341        self.distribute_by = value;
342        self
343    }
344    pub fn sort_by(&mut self, value: Vec<ast::OrderByExpr>) -> &mut Self {
345        self.sort_by = value;
346        self
347    }
348    pub fn having(&mut self, value: Option<ast::Expr>) -> &mut Self {
349        self.having = value;
350        self
351    }
352    pub fn named_window(&mut self, value: Vec<ast::NamedWindowDefinition>) -> &mut Self {
353        self.named_window = value;
354        self
355    }
356    pub fn qualify(&mut self, value: Option<ast::Expr>) -> &mut Self {
357        self.qualify = value;
358        self
359    }
360    pub fn value_table_mode(&mut self, value: Option<ast::ValueTableMode>) -> &mut Self {
361        self.value_table_mode = value;
362        self
363    }
364    pub fn build(&self) -> Result<ast::Select, BuilderError> {
365        Ok(ast::Select {
366            optimizer_hints: vec![],
367            distinct: self.distinct.clone(),
368            select_modifiers: None,
369            top_before_distinct: false,
370            top: self.top.clone(),
371            projection: self.projection.clone().unwrap_or_default(),
372            into: self.into.clone(),
373            from: self
374                .from
375                .iter()
376                .filter_map(|b| b.build().transpose())
377                .collect::<Result<Vec<_>, BuilderError>>()?,
378            lateral_views: self.lateral_views.clone(),
379            selection: self.selection.clone(),
380            group_by: match self.group_by {
381                Some(ref value) => value.clone(),
382                None => {
383                    return Err(Into::into(UninitializedFieldError::from("group_by")));
384                }
385            },
386            cluster_by: self.cluster_by.clone(),
387            distribute_by: self.distribute_by.clone(),
388            sort_by: self.sort_by.clone(),
389            having: self.having.clone(),
390            named_window: self.named_window.clone(),
391            qualify: self.qualify.clone(),
392            value_table_mode: self.value_table_mode,
393            connect_by: Vec::new(),
394            window_before_qualify: false,
395            prewhere: None,
396            select_token: AttachedToken::empty(),
397            flavor: match self.flavor {
398                Some(ref value) => *value,
399                None => return Err(Into::into(UninitializedFieldError::from("flavor"))),
400            },
401            exclude: None,
402        })
403    }
404    fn create_empty() -> Self {
405        Self {
406            distinct: Default::default(),
407            top: Default::default(),
408            projection: None,
409            into: Default::default(),
410            from: Default::default(),
411            lateral_views: Default::default(),
412            selection: Default::default(),
413            group_by: Some(ast::GroupByExpr::Expressions(Vec::new(), Vec::new())),
414            cluster_by: Default::default(),
415            distribute_by: Default::default(),
416            sort_by: Default::default(),
417            having: Default::default(),
418            named_window: Default::default(),
419            qualify: Default::default(),
420            value_table_mode: Default::default(),
421            flavor: Some(SelectFlavor::Standard),
422            flatten_alias_counter: 0,
423            flatten_table_aliases: Vec::new(),
424            subquery_alias_depth: 0,
425        }
426    }
427}
428impl Default for SelectBuilder {
429    fn default() -> Self {
430        Self::create_empty()
431    }
432}
433
434#[derive(Clone)]
435pub struct TableWithJoinsBuilder {
436    relation: Option<RelationBuilder>,
437    joins: Vec<ast::Join>,
438}
439
440impl TableWithJoinsBuilder {
441    pub fn relation(&mut self, value: RelationBuilder) -> &mut Self {
442        self.relation = Some(value);
443        self
444    }
445
446    pub fn joins(&mut self, value: Vec<ast::Join>) -> &mut Self {
447        self.joins = value;
448        self
449    }
450    pub fn push_join(&mut self, value: ast::Join) -> &mut Self {
451        self.joins.push(value);
452        self
453    }
454
455    pub fn build(&self) -> Result<Option<ast::TableWithJoins>, BuilderError> {
456        match self.relation {
457            Some(ref value) => match value.build()? {
458                Some(relation) => Ok(Some(ast::TableWithJoins {
459                    relation,
460                    joins: self.joins.clone(),
461                })),
462                None => Ok(None),
463            },
464            None => Err(Into::into(UninitializedFieldError::from("relation"))),
465        }
466    }
467    fn create_empty() -> Self {
468        Self {
469            relation: Default::default(),
470            joins: Default::default(),
471        }
472    }
473}
474impl Default for TableWithJoinsBuilder {
475    fn default() -> Self {
476        Self::create_empty()
477    }
478}
479
480#[derive(Clone)]
481pub struct RelationBuilder {
482    relation: Option<TableFactorBuilder>,
483}
484
485#[derive(Clone)]
486// Boxing variants would penalize the common builder path; this enum is
487// constructed-then-consumed locally rather than stored at scale.
488#[expect(clippy::large_enum_variant)]
489enum TableFactorBuilder {
490    Table(TableRelationBuilder),
491    Derived(DerivedRelationBuilder),
492    NestedJoin(ast::TableWithJoins, Option<ast::TableAlias>),
493    Unnest(UnnestRelationBuilder),
494    Flatten(FlattenRelationBuilder),
495    Empty,
496}
497
498impl RelationBuilder {
499    pub fn has_relation(&self) -> bool {
500        self.relation.is_some()
501    }
502    pub fn table(&mut self, value: TableRelationBuilder) -> &mut Self {
503        self.relation = Some(TableFactorBuilder::Table(value));
504        self
505    }
506    pub fn derived(&mut self, value: DerivedRelationBuilder) -> &mut Self {
507        self.relation = Some(TableFactorBuilder::Derived(value));
508        self
509    }
510
511    pub fn nested_join(
512        &mut self,
513        value: ast::TableWithJoins,
514        alias: Option<ast::TableAlias>,
515    ) -> &mut Self {
516        self.relation = Some(TableFactorBuilder::NestedJoin(value, alias));
517        self
518    }
519
520    pub fn unnest(&mut self, value: UnnestRelationBuilder) -> &mut Self {
521        self.relation = Some(TableFactorBuilder::Unnest(value));
522        self
523    }
524
525    pub fn flatten(&mut self, value: FlattenRelationBuilder) -> &mut Self {
526        self.relation = Some(TableFactorBuilder::Flatten(value));
527        self
528    }
529
530    pub fn empty(&mut self) -> &mut Self {
531        self.relation = Some(TableFactorBuilder::Empty);
532        self
533    }
534    pub fn alias(&mut self, value: Option<ast::TableAlias>) -> &mut Self {
535        let new = self;
536        match new.relation {
537            Some(TableFactorBuilder::Table(ref mut rel_builder)) => {
538                rel_builder.alias = value;
539            }
540            Some(TableFactorBuilder::Derived(ref mut rel_builder)) => {
541                rel_builder.alias = value;
542            }
543            Some(TableFactorBuilder::NestedJoin(_, ref mut alias)) => {
544                *alias = value;
545            }
546            Some(TableFactorBuilder::Unnest(ref mut rel_builder)) => {
547                rel_builder.alias = value;
548            }
549            Some(TableFactorBuilder::Flatten(ref mut rel_builder)) => {
550                rel_builder.alias = value;
551            }
552            Some(TableFactorBuilder::Empty) => (),
553            None => (),
554        }
555        new
556    }
557    pub fn build(&self) -> Result<Option<ast::TableFactor>, BuilderError> {
558        Ok(match self.relation {
559            Some(TableFactorBuilder::Table(ref value)) => Some(value.build()?),
560            Some(TableFactorBuilder::Derived(ref value)) => Some(value.build()?),
561            Some(TableFactorBuilder::NestedJoin(ref table_with_joins, ref alias)) => {
562                Some(ast::TableFactor::NestedJoin {
563                    table_with_joins: Box::new(table_with_joins.clone()),
564                    alias: alias.clone(),
565                })
566            }
567            Some(TableFactorBuilder::Unnest(ref value)) => Some(value.build()?),
568            Some(TableFactorBuilder::Flatten(ref value)) => Some(value.build()?),
569            Some(TableFactorBuilder::Empty) => None,
570            None => return Err(Into::into(UninitializedFieldError::from("relation"))),
571        })
572    }
573    fn create_empty() -> Self {
574        Self {
575            relation: Default::default(),
576        }
577    }
578}
579impl Default for RelationBuilder {
580    fn default() -> Self {
581        Self::create_empty()
582    }
583}
584
585#[derive(Clone)]
586pub struct TableRelationBuilder {
587    name: Option<ast::ObjectName>,
588    alias: Option<ast::TableAlias>,
589    args: Option<Vec<ast::FunctionArg>>,
590    with_hints: Vec<ast::Expr>,
591    version: Option<ast::TableVersion>,
592    partitions: Vec<ast::Ident>,
593    index_hints: Vec<ast::TableIndexHints>,
594}
595
596impl TableRelationBuilder {
597    pub fn name(&mut self, value: ast::ObjectName) -> &mut Self {
598        self.name = Some(value);
599        self
600    }
601    pub fn alias(&mut self, value: Option<ast::TableAlias>) -> &mut Self {
602        self.alias = value;
603        self
604    }
605    pub fn args(&mut self, value: Option<Vec<ast::FunctionArg>>) -> &mut Self {
606        self.args = value;
607        self
608    }
609    pub fn with_hints(&mut self, value: Vec<ast::Expr>) -> &mut Self {
610        self.with_hints = value;
611        self
612    }
613    pub fn version(&mut self, value: Option<ast::TableVersion>) -> &mut Self {
614        self.version = value;
615        self
616    }
617    pub fn partitions(&mut self, value: Vec<ast::Ident>) -> &mut Self {
618        self.partitions = value;
619        self
620    }
621    pub fn index_hints(&mut self, value: Vec<ast::TableIndexHints>) -> &mut Self {
622        self.index_hints = value;
623        self
624    }
625    pub fn build(&self) -> Result<ast::TableFactor, BuilderError> {
626        Ok(ast::TableFactor::Table {
627            name: match self.name {
628                Some(ref value) => value.clone(),
629                None => return Err(Into::into(UninitializedFieldError::from("name"))),
630            },
631            alias: self.alias.clone(),
632            args: self.args.clone().map(|args| ast::TableFunctionArgs {
633                args,
634                settings: None,
635            }),
636            with_hints: self.with_hints.clone(),
637            version: self.version.clone(),
638            partitions: self.partitions.clone(),
639            with_ordinality: false,
640            json_path: None,
641            sample: None,
642            index_hints: self.index_hints.clone(),
643        })
644    }
645    fn create_empty() -> Self {
646        Self {
647            name: Default::default(),
648            alias: Default::default(),
649            args: Default::default(),
650            with_hints: Default::default(),
651            version: Default::default(),
652            partitions: Default::default(),
653            index_hints: Default::default(),
654        }
655    }
656}
657impl Default for TableRelationBuilder {
658    fn default() -> Self {
659        Self::create_empty()
660    }
661}
662#[derive(Clone)]
663pub struct DerivedRelationBuilder {
664    lateral: Option<bool>,
665    subquery: Option<Box<ast::Query>>,
666    alias: Option<ast::TableAlias>,
667    projection_names: Vec<ast::Ident>,
668}
669
670impl DerivedRelationBuilder {
671    pub fn lateral(&mut self, value: bool) -> &mut Self {
672        self.lateral = Some(value);
673        self
674    }
675    pub fn subquery(&mut self, value: Box<ast::Query>) -> &mut Self {
676        self.subquery = Some(value);
677        self
678    }
679    pub fn alias(&mut self, value: Option<ast::TableAlias>) -> &mut Self {
680        self.alias = value;
681        self
682    }
683    pub(super) fn projection_names(&mut self, value: Vec<ast::Ident>) -> &mut Self {
684        self.projection_names = value;
685        self
686    }
687    fn build(&self) -> Result<ast::TableFactor, BuilderError> {
688        let mut subquery = match self.subquery {
689            Some(ref value) => value.clone(),
690            None => {
691                return Err(Into::into(UninitializedFieldError::from("subquery")));
692            }
693        };
694        if self
695            .alias
696            .as_ref()
697            .is_none_or(|alias| alias.columns.is_empty())
698            && let ast::SetExpr::Select(select) = subquery.body.as_mut()
699            && select.projection.len() == self.projection_names.len()
700        {
701            for (item, alias) in select.projection.iter_mut().zip(&self.projection_names)
702            {
703                if let ast::SelectItem::UnnamedExpr(expr) = item {
704                    let preserves_name = match expr {
705                        ast::Expr::Identifier(name) => name.value == alias.value,
706                        ast::Expr::CompoundIdentifier(names) => {
707                            names.last().is_some_and(|name| name.value == alias.value)
708                        }
709                        _ => false,
710                    };
711                    if !preserves_name {
712                        *item = ast::SelectItem::ExprWithAlias {
713                            expr: expr.clone(),
714                            alias: alias.clone(),
715                        };
716                    }
717                }
718            }
719        }
720        Ok(ast::TableFactor::Derived {
721            lateral: match self.lateral {
722                Some(ref value) => *value,
723                None => return Err(Into::into(UninitializedFieldError::from("lateral"))),
724            },
725            subquery,
726            alias: self.alias.clone(),
727            sample: None,
728        })
729    }
730    fn create_empty() -> Self {
731        Self {
732            lateral: Default::default(),
733            subquery: Default::default(),
734            alias: Default::default(),
735            projection_names: Default::default(),
736        }
737    }
738}
739impl Default for DerivedRelationBuilder {
740    fn default() -> Self {
741        Self::create_empty()
742    }
743}
744
745#[derive(Clone)]
746pub struct UnnestRelationBuilder {
747    pub alias: Option<ast::TableAlias>,
748    pub array_exprs: Vec<ast::Expr>,
749    with_offset: bool,
750    with_offset_alias: Option<ast::Ident>,
751    with_ordinality: bool,
752}
753
754impl UnnestRelationBuilder {
755    pub fn alias(&mut self, value: Option<ast::TableAlias>) -> &mut Self {
756        self.alias = value;
757        self
758    }
759    pub fn array_exprs(&mut self, value: Vec<ast::Expr>) -> &mut Self {
760        self.array_exprs = value;
761        self
762    }
763
764    pub fn with_offset(&mut self, value: bool) -> &mut Self {
765        self.with_offset = value;
766        self
767    }
768
769    pub fn with_offset_alias(&mut self, value: Option<ast::Ident>) -> &mut Self {
770        self.with_offset_alias = value;
771        self
772    }
773
774    pub fn with_ordinality(&mut self, value: bool) -> &mut Self {
775        self.with_ordinality = value;
776        self
777    }
778
779    pub fn build(&self) -> Result<ast::TableFactor, BuilderError> {
780        Ok(ast::TableFactor::UNNEST {
781            alias: self.alias.clone(),
782            array_exprs: self.array_exprs.clone(),
783            with_offset: self.with_offset,
784            with_offset_alias: self.with_offset_alias.clone(),
785            with_ordinality: self.with_ordinality,
786        })
787    }
788
789    fn create_empty() -> Self {
790        Self {
791            alias: Default::default(),
792            array_exprs: Default::default(),
793            with_offset: Default::default(),
794            with_offset_alias: Default::default(),
795            with_ordinality: Default::default(),
796        }
797    }
798}
799
800impl Default for UnnestRelationBuilder {
801    fn default() -> Self {
802        Self::create_empty()
803    }
804}
805
806/// Builds a `LATERAL FLATTEN(INPUT => expr, OUTER => bool)` table factor
807/// for Snowflake-style unnesting.
808#[derive(Clone)]
809pub struct FlattenRelationBuilder {
810    pub alias: Option<ast::TableAlias>,
811    /// The input expression to flatten (e.g. a column reference).
812    pub input_expr: Option<ast::Expr>,
813    /// Whether to preserve rows for NULL/empty inputs (Snowflake `OUTER` param).
814    pub outer: bool,
815}
816
817impl FlattenRelationBuilder {
818    pub fn alias(&mut self, value: Option<ast::TableAlias>) -> &mut Self {
819        self.alias = value;
820        self
821    }
822
823    pub fn input_expr(&mut self, value: ast::Expr) -> &mut Self {
824        self.input_expr = Some(value);
825        self
826    }
827
828    pub fn outer(&mut self, value: bool) -> &mut Self {
829        self.outer = value;
830        self
831    }
832
833    pub fn build(&self) -> Result<ast::TableFactor, BuilderError> {
834        let input = self.input_expr.clone().ok_or_else(|| {
835            BuilderError::from(UninitializedFieldError::from("input_expr"))
836        })?;
837
838        let mut args = vec![ast::FunctionArg::Named {
839            name: ast::Ident::new("INPUT"),
840            arg: ast::FunctionArgExpr::Expr(input),
841            operator: ast::FunctionArgOperator::RightArrow,
842        }];
843
844        if self.outer {
845            args.push(ast::FunctionArg::Named {
846                name: ast::Ident::new("OUTER"),
847                arg: ast::FunctionArgExpr::Expr(ast::Expr::Value(
848                    ast::Value::Boolean(true).into(),
849                )),
850                operator: ast::FunctionArgOperator::RightArrow,
851            });
852        }
853
854        Ok(ast::TableFactor::Function {
855            lateral: true,
856            name: ast::ObjectName::from(vec![ast::Ident::new("FLATTEN")]),
857            args,
858            with_ordinality: false,
859            alias: self.alias.clone(),
860        })
861    }
862
863    fn create_empty() -> Self {
864        Self {
865            alias: None,
866            input_expr: None,
867            outer: false,
868        }
869    }
870}
871
872impl Default for FlattenRelationBuilder {
873    fn default() -> Self {
874        Self::create_empty()
875    }
876}
877
878/// Runtime error when a `build()` method is called and one or more required fields
879/// do not have a value.
880#[derive(Debug, Clone)]
881pub struct UninitializedFieldError(&'static str);
882
883impl UninitializedFieldError {
884    /// Create a new `UninitializedFieldError` for the specified field name.
885    pub fn new(field_name: &'static str) -> Self {
886        UninitializedFieldError(field_name)
887    }
888
889    /// Get the name of the first-declared field that wasn't initialized
890    pub fn field_name(&self) -> &'static str {
891        self.0
892    }
893}
894
895impl fmt::Display for UninitializedFieldError {
896    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
897        write!(f, "Field not initialized: {}", self.0)
898    }
899}
900
901impl From<&'static str> for UninitializedFieldError {
902    fn from(field_name: &'static str) -> Self {
903        Self::new(field_name)
904    }
905}
906impl std::error::Error for UninitializedFieldError {}
907
908#[derive(Debug)]
909pub enum BuilderError {
910    UninitializedField(&'static str),
911    ValidationError(String),
912}
913impl From<UninitializedFieldError> for BuilderError {
914    fn from(s: UninitializedFieldError) -> Self {
915        Self::UninitializedField(s.field_name())
916    }
917}
918impl From<String> for BuilderError {
919    fn from(s: String) -> Self {
920        Self::ValidationError(s)
921    }
922}
923impl fmt::Display for BuilderError {
924    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
925        match self {
926            Self::UninitializedField(field) => {
927                write!(f, "`{field}` must be initialized")
928            }
929            Self::ValidationError(error) => write!(f, "{error}"),
930        }
931    }
932}
933impl std::error::Error for BuilderError {}