Skip to main content

sqlparser/ast/
query.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18#[cfg(not(feature = "std"))]
19use alloc::{boxed::Box, vec::Vec};
20
21use helpers::attached_token::AttachedToken;
22#[cfg(feature = "serde")]
23use serde::{Deserialize, Serialize};
24
25#[cfg(feature = "visitor")]
26use sqlparser_derive::{Visit, VisitMut};
27
28use crate::{
29    ast::*,
30    display_utils::{indented_list, SpaceOrNewline},
31    tokenizer::{Token, TokenWithSpan},
32};
33
34/// The most complete variant of a `SELECT` query expression, optionally
35/// including `WITH`, `UNION` / other set operations, and `ORDER BY`.
36#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
37#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
38#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
39#[cfg_attr(feature = "visitor", visit(with = "visit_query"))]
40pub struct Query {
41    /// WITH (common table expressions, or CTEs)
42    pub with: Option<With>,
43    /// SELECT or UNION / EXCEPT / INTERSECT
44    pub body: Box<SetExpr>,
45    /// ORDER BY
46    pub order_by: Option<OrderBy>,
47    /// `LIMIT ... OFFSET ... | LIMIT <offset>, <limit>`
48    pub limit_clause: Option<LimitClause>,
49    /// `FETCH { FIRST | NEXT } <N> [ PERCENT ] { ROW | ROWS } | { ONLY | WITH TIES }`
50    pub fetch: Option<Fetch>,
51    /// `FOR { UPDATE | SHARE } [ OF table_name ] [ SKIP LOCKED | NOWAIT ]`
52    pub locks: Vec<LockClause>,
53    /// `FOR XML { RAW | AUTO | EXPLICIT | PATH } [ , ELEMENTS ]`
54    /// `FOR JSON { AUTO | PATH } [ , INCLUDE_NULL_VALUES ]`
55    /// (MSSQL-specific)
56    pub for_clause: Option<ForClause>,
57    /// ClickHouse syntax: `SELECT * FROM t SETTINGS key1 = value1, key2 = value2`
58    ///
59    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/select#settings-in-select-query)
60    pub settings: Option<Vec<Setting>>,
61    /// `SELECT * FROM t FORMAT JSONCompact`
62    ///
63    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/select/format)
64    /// (ClickHouse-specific)
65    pub format_clause: Option<FormatClause>,
66
67    /// Pipe operator
68    pub pipe_operators: Vec<PipeOperator>,
69}
70
71impl fmt::Display for Query {
72    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73        if let Some(ref with) = self.with {
74            with.fmt(f)?;
75            SpaceOrNewline.fmt(f)?;
76        }
77        self.body.fmt(f)?;
78        if let Some(ref order_by) = self.order_by {
79            f.write_str(" ")?;
80            order_by.fmt(f)?;
81        }
82
83        if let Some(ref limit_clause) = self.limit_clause {
84            limit_clause.fmt(f)?;
85        }
86        if let Some(ref settings) = self.settings {
87            f.write_str(" SETTINGS ")?;
88            display_comma_separated(settings).fmt(f)?;
89        }
90        if let Some(ref fetch) = self.fetch {
91            f.write_str(" ")?;
92            fetch.fmt(f)?;
93        }
94        if !self.locks.is_empty() {
95            f.write_str(" ")?;
96            display_separated(&self.locks, " ").fmt(f)?;
97        }
98        if let Some(ref for_clause) = self.for_clause {
99            f.write_str(" ")?;
100            for_clause.fmt(f)?;
101        }
102        if let Some(ref format) = self.format_clause {
103            f.write_str(" ")?;
104            format.fmt(f)?;
105        }
106        for pipe_operator in &self.pipe_operators {
107            f.write_str(" |> ")?;
108            pipe_operator.fmt(f)?;
109        }
110        Ok(())
111    }
112}
113
114/// Query syntax for ClickHouse ADD PROJECTION statement.
115/// Its syntax is similar to SELECT statement, but it is used to add a new projection to a table.
116/// Syntax is `SELECT <COLUMN LIST EXPR> [GROUP BY] [ORDER BY]`
117///
118/// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/projection#add-projection)
119#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
120#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
121#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
122pub struct ProjectionSelect {
123    /// The list of projected select items.
124    pub projection: Vec<SelectItem>,
125    /// Optional `ORDER BY` clause for the projection-select.
126    pub order_by: Option<OrderBy>,
127    /// Optional `GROUP BY` clause for the projection-select.
128    pub group_by: Option<GroupByExpr>,
129}
130
131impl fmt::Display for ProjectionSelect {
132    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133        write!(f, "SELECT {}", display_comma_separated(&self.projection))?;
134        if let Some(ref group_by) = self.group_by {
135            write!(f, " {group_by}")?;
136        }
137        if let Some(ref order_by) = self.order_by {
138            write!(f, " {order_by}")?;
139        }
140        Ok(())
141    }
142}
143
144/// A node in a tree, representing a "query body" expression, roughly:
145/// `SELECT ... [ {UNION|EXCEPT|INTERSECT} SELECT ...]`
146#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
147#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
148#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
149pub enum SetExpr {
150    /// Restricted SELECT .. FROM .. HAVING (no ORDER BY or set operations)
151    Select(Box<Select>),
152    /// Parenthesized SELECT subquery, which may include more set operations
153    /// in its body and an optional ORDER BY / LIMIT.
154    Query(Box<Query>),
155    /// UNION/EXCEPT/INTERSECT of two queries
156    /// A set operation combining two query expressions.
157    SetOperation {
158        /// Left operand of the set operation.
159        left: Box<SetExpr>,
160        /// The set operator used (e.g. `UNION`, `EXCEPT`).
161        op: SetOperator,
162        /// Optional quantifier (`ALL`, `DISTINCT`, etc.).
163        set_quantifier: SetQuantifier,
164        /// Right operand of the set operation.
165        right: Box<SetExpr>,
166    },
167    /// `VALUES (...)`
168    Values(Values),
169    /// `INSERT` statement
170    Insert(Statement),
171    /// `UPDATE` statement
172    Update(Statement),
173    /// `DELETE` statement
174    Delete(Statement),
175    /// `MERGE` statement
176    Merge(Statement),
177    /// `TABLE` command
178    Table(Box<Table>),
179}
180
181impl SetExpr {
182    /// If this `SetExpr` is a `SELECT`, returns the [`Select`].
183    pub fn as_select(&self) -> Option<&Select> {
184        if let Self::Select(select) = self {
185            Some(&**select)
186        } else {
187            None
188        }
189    }
190}
191
192impl fmt::Display for SetExpr {
193    #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
194    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
195        match self {
196            SetExpr::Select(s) => s.fmt(f),
197            SetExpr::Query(q) => {
198                f.write_str("(")?;
199                q.fmt(f)?;
200                f.write_str(")")
201            }
202            SetExpr::Values(v) => v.fmt(f),
203            SetExpr::Insert(v) => v.fmt(f),
204            SetExpr::Update(v) => v.fmt(f),
205            SetExpr::Delete(v) => v.fmt(f),
206            SetExpr::Merge(v) => v.fmt(f),
207            SetExpr::Table(t) => t.fmt(f),
208            SetExpr::SetOperation {
209                left,
210                right,
211                op,
212                set_quantifier,
213            } => {
214                left.fmt(f)?;
215                SpaceOrNewline.fmt(f)?;
216                op.fmt(f)?;
217                match set_quantifier {
218                    SetQuantifier::All
219                    | SetQuantifier::Distinct
220                    | SetQuantifier::ByName
221                    | SetQuantifier::AllByName
222                    | SetQuantifier::DistinctByName => {
223                        f.write_str(" ")?;
224                        set_quantifier.fmt(f)?;
225                    }
226                    SetQuantifier::None => {}
227                }
228                SpaceOrNewline.fmt(f)?;
229                right.fmt(f)?;
230                Ok(())
231            }
232        }
233    }
234}
235
236#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
237#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
238#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
239/// A set operator for combining two `SetExpr`s.
240pub enum SetOperator {
241    /// `UNION` set operator
242    Union,
243    /// `EXCEPT` set operator
244    Except,
245    /// `INTERSECT` set operator
246    Intersect,
247    /// `MINUS` set operator (non-standard)
248    Minus,
249}
250
251impl fmt::Display for SetOperator {
252    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
253        f.write_str(match self {
254            SetOperator::Union => "UNION",
255            SetOperator::Except => "EXCEPT",
256            SetOperator::Intersect => "INTERSECT",
257            SetOperator::Minus => "MINUS",
258        })
259    }
260}
261
262/// A quantifier for [SetOperator].
263// TODO: Restrict parsing specific SetQuantifier in some specific dialects.
264// For example, BigQuery does not support `DISTINCT` for `EXCEPT` and `INTERSECT`
265#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
266#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
267#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
268pub enum SetQuantifier {
269    /// `ALL` quantifier
270    All,
271    /// `DISTINCT` quantifier
272    Distinct,
273    /// `BY NAME` quantifier
274    ByName,
275    /// `ALL BY NAME` quantifier
276    AllByName,
277    /// `DISTINCT BY NAME` quantifier
278    DistinctByName,
279    /// No quantifier specified
280    None,
281}
282
283impl fmt::Display for SetQuantifier {
284    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
285        match self {
286            SetQuantifier::All => write!(f, "ALL"),
287            SetQuantifier::Distinct => write!(f, "DISTINCT"),
288            SetQuantifier::ByName => write!(f, "BY NAME"),
289            SetQuantifier::AllByName => write!(f, "ALL BY NAME"),
290            SetQuantifier::DistinctByName => write!(f, "DISTINCT BY NAME"),
291            SetQuantifier::None => Ok(()),
292        }
293    }
294}
295
296#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
297#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
298/// A [`TABLE` command](https://www.postgresql.org/docs/current/sql-select.html#SQL-TABLE)
299#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
300pub struct Table {
301    /// Optional table name (absent for e.g. `TABLE` command without argument).
302    pub table_name: Option<Ident>,
303    /// Optional schema/catalog name qualifying the table.
304    pub schema_name: Option<Ident>,
305}
306
307impl fmt::Display for Table {
308    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
309        if let Some(ref table_name) = self.table_name {
310            if let Some(ref schema_name) = self.schema_name {
311                write!(f, "TABLE {}.{}", schema_name, table_name,)?;
312            } else {
313                write!(f, "TABLE {}", table_name)?;
314            }
315        } else {
316            write!(f, "TABLE")?;
317        }
318        Ok(())
319    }
320}
321
322/// What did this select look like?
323#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
324#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
325#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
326pub enum SelectFlavor {
327    /// `SELECT *`
328    Standard,
329    /// `FROM ... SELECT *`
330    FromFirst,
331    /// `FROM *`
332    FromFirstNoSelect,
333}
334
335/// MySQL-specific SELECT modifiers that appear after the SELECT keyword.
336///
337/// These modifiers affect query execution and optimization. They can appear in any order after
338/// SELECT and before the column list, can be repeated, and can be interleaved with
339/// DISTINCT/DISTINCTROW/ALL:
340///
341/// ```sql
342/// SELECT
343///     [ALL | DISTINCT | DISTINCTROW]
344///     [HIGH_PRIORITY]
345///     [STRAIGHT_JOIN]
346///     [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
347///     [SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
348///     select_expr [, select_expr] ...
349/// ```
350///
351/// See [MySQL SELECT](https://dev.mysql.com/doc/refman/8.4/en/select.html).
352#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Default)]
353#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
354#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
355pub struct SelectModifiers {
356    /// `HIGH_PRIORITY` gives the SELECT higher priority than statements that update a table.
357    ///
358    /// <https://dev.mysql.com/doc/refman/8.4/en/select.html>
359    pub high_priority: bool,
360    /// `STRAIGHT_JOIN` forces the optimizer to join tables in the order listed in the FROM clause.
361    ///
362    /// <https://dev.mysql.com/doc/refman/8.4/en/select.html>
363    pub straight_join: bool,
364    /// `SQL_SMALL_RESULT` hints that the result set is small, using in-memory temp tables.
365    ///
366    /// <https://dev.mysql.com/doc/refman/8.4/en/select.html>
367    pub sql_small_result: bool,
368    /// `SQL_BIG_RESULT` hints that the result set is large, using disk-based temp tables.
369    ///
370    /// <https://dev.mysql.com/doc/refman/8.4/en/select.html>
371    pub sql_big_result: bool,
372    /// `SQL_BUFFER_RESULT` forces the result to be put into a temporary table to release locks early.
373    ///
374    /// <https://dev.mysql.com/doc/refman/8.4/en/select.html>
375    pub sql_buffer_result: bool,
376    /// `SQL_NO_CACHE` tells MySQL not to cache the query result. (Deprecated in 8.4+.)
377    ///
378    /// <https://dev.mysql.com/doc/refman/8.4/en/select.html>
379    pub sql_no_cache: bool,
380    /// `SQL_CALC_FOUND_ROWS` tells MySQL to calculate the total number of rows. (Deprecated in 8.0.17+.)
381    ///
382    /// - [MySQL SELECT modifiers](https://dev.mysql.com/doc/refman/8.4/en/select.html)
383    /// - [`FOUND_ROWS()`](https://dev.mysql.com/doc/refman/8.4/en/information-functions.html#function_found-rows)
384    pub sql_calc_found_rows: bool,
385}
386
387impl fmt::Display for SelectModifiers {
388    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
389        if self.high_priority {
390            f.write_str(" HIGH_PRIORITY")?;
391        }
392        if self.straight_join {
393            f.write_str(" STRAIGHT_JOIN")?;
394        }
395        if self.sql_small_result {
396            f.write_str(" SQL_SMALL_RESULT")?;
397        }
398        if self.sql_big_result {
399            f.write_str(" SQL_BIG_RESULT")?;
400        }
401        if self.sql_buffer_result {
402            f.write_str(" SQL_BUFFER_RESULT")?;
403        }
404        if self.sql_no_cache {
405            f.write_str(" SQL_NO_CACHE")?;
406        }
407        if self.sql_calc_found_rows {
408            f.write_str(" SQL_CALC_FOUND_ROWS")?;
409        }
410        Ok(())
411    }
412}
413
414impl SelectModifiers {
415    /// Returns true if any of the modifiers are set.
416    pub fn is_any_set(&self) -> bool {
417        // Using irrefutable destructuring to catch fields added in the future
418        let Self {
419            high_priority,
420            straight_join,
421            sql_small_result,
422            sql_big_result,
423            sql_buffer_result,
424            sql_no_cache,
425            sql_calc_found_rows,
426        } = self;
427        *high_priority
428            || *straight_join
429            || *sql_small_result
430            || *sql_big_result
431            || *sql_buffer_result
432            || *sql_no_cache
433            || *sql_calc_found_rows
434    }
435}
436
437/// A restricted variant of `SELECT` (without CTEs/`ORDER BY`), which may
438/// appear either as the only body item of a `Query`, or as an operand
439/// to a set operation like `UNION`.
440#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
441#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
442#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
443#[cfg_attr(feature = "visitor", visit(with = "visit_select"))]
444pub struct Select {
445    /// Token for the `SELECT` keyword
446    pub select_token: AttachedToken,
447    /// Query optimizer hints
448    ///
449    /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/optimizer-hints.html)
450    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Comments.html#GUID-D316D545-89E2-4D54-977F-FC97815CD62E)
451    pub optimizer_hints: Vec<OptimizerHint>,
452    /// `SELECT [DISTINCT] ...`
453    pub distinct: Option<Distinct>,
454    /// MySQL-specific SELECT modifiers.
455    ///
456    /// See [MySQL SELECT](https://dev.mysql.com/doc/refman/8.4/en/select.html).
457    pub select_modifiers: Option<SelectModifiers>,
458    /// MSSQL syntax: `TOP (<N>) [ PERCENT ] [ WITH TIES ]`
459    pub top: Option<Top>,
460    /// Whether the top was located before `ALL`/`DISTINCT`
461    pub top_before_distinct: bool,
462    /// projection expressions
463    pub projection: Vec<SelectItem>,
464    /// Excluded columns from the projection expression which are not specified
465    /// directly after a wildcard.
466    ///
467    /// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_EXCLUDE_list.html)
468    pub exclude: Option<ExcludeSelectItem>,
469    /// INTO
470    pub into: Option<SelectInto>,
471    /// FROM
472    pub from: Vec<TableWithJoins>,
473    /// LATERAL VIEWs
474    pub lateral_views: Vec<LateralView>,
475    /// ClickHouse syntax: `PREWHERE a = 1 WHERE b = 2`,
476    /// and it can be used together with WHERE selection.
477    ///
478    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/select/prewhere)
479    pub prewhere: Option<Expr>,
480    /// WHERE
481    pub selection: Option<Expr>,
482    /// [START WITH ..] CONNECT BY ..
483    pub connect_by: Vec<ConnectByKind>,
484    /// GROUP BY
485    pub group_by: GroupByExpr,
486    /// CLUSTER BY (Hive)
487    pub cluster_by: Vec<Expr>,
488    /// DISTRIBUTE BY (Hive)
489    pub distribute_by: Vec<Expr>,
490    /// SORT BY (Hive)
491    pub sort_by: Vec<OrderByExpr>,
492    /// HAVING
493    pub having: Option<Expr>,
494    /// WINDOW AS
495    pub named_window: Vec<NamedWindowDefinition>,
496    /// QUALIFY (Snowflake)
497    pub qualify: Option<Expr>,
498    /// The positioning of QUALIFY and WINDOW clauses differ between dialects.
499    /// e.g. BigQuery requires that WINDOW comes after QUALIFY, while DUCKDB accepts
500    /// WINDOW before QUALIFY.
501    /// We accept either positioning and flag the accepted variant.
502    pub window_before_qualify: bool,
503    /// BigQuery syntax: `SELECT AS VALUE | SELECT AS STRUCT`
504    pub value_table_mode: Option<ValueTableMode>,
505    /// Was this a FROM-first query?
506    pub flavor: SelectFlavor,
507}
508
509impl fmt::Display for Select {
510    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
511        match self.flavor {
512            SelectFlavor::Standard => {
513                write!(f, "SELECT")?;
514            }
515            SelectFlavor::FromFirst => {
516                write!(f, "FROM {} SELECT", display_comma_separated(&self.from))?;
517            }
518            SelectFlavor::FromFirstNoSelect => {
519                write!(f, "FROM {}", display_comma_separated(&self.from))?;
520            }
521        }
522
523        for hint in &self.optimizer_hints {
524            f.write_str(" ")?;
525            hint.fmt(f)?;
526        }
527
528        if let Some(value_table_mode) = self.value_table_mode {
529            f.write_str(" ")?;
530            value_table_mode.fmt(f)?;
531        }
532
533        if let Some(ref top) = self.top {
534            if self.top_before_distinct {
535                f.write_str(" ")?;
536                top.fmt(f)?;
537            }
538        }
539        if let Some(ref distinct) = self.distinct {
540            f.write_str(" ")?;
541            distinct.fmt(f)?;
542        }
543        if let Some(ref top) = self.top {
544            if !self.top_before_distinct {
545                f.write_str(" ")?;
546                top.fmt(f)?;
547            }
548        }
549
550        if let Some(ref select_modifiers) = self.select_modifiers {
551            select_modifiers.fmt(f)?;
552        }
553
554        if !self.projection.is_empty() {
555            indented_list(f, &self.projection)?;
556        }
557
558        if let Some(exclude) = &self.exclude {
559            write!(f, " {exclude}")?;
560        }
561
562        if let Some(ref into) = self.into {
563            f.write_str(" ")?;
564            into.fmt(f)?;
565        }
566
567        if self.flavor == SelectFlavor::Standard && !self.from.is_empty() {
568            SpaceOrNewline.fmt(f)?;
569            f.write_str("FROM")?;
570            indented_list(f, &self.from)?;
571        }
572        if !self.lateral_views.is_empty() {
573            for lv in &self.lateral_views {
574                lv.fmt(f)?;
575            }
576        }
577        if let Some(ref prewhere) = self.prewhere {
578            f.write_str(" PREWHERE ")?;
579            prewhere.fmt(f)?;
580        }
581        if let Some(ref selection) = self.selection {
582            SpaceOrNewline.fmt(f)?;
583            f.write_str("WHERE")?;
584            SpaceOrNewline.fmt(f)?;
585            Indent(selection).fmt(f)?;
586        }
587        for clause in &self.connect_by {
588            SpaceOrNewline.fmt(f)?;
589            clause.fmt(f)?;
590        }
591        match &self.group_by {
592            GroupByExpr::All(_) => {
593                SpaceOrNewline.fmt(f)?;
594                self.group_by.fmt(f)?;
595            }
596            GroupByExpr::Expressions(exprs, _) => {
597                if !exprs.is_empty() {
598                    SpaceOrNewline.fmt(f)?;
599                    self.group_by.fmt(f)?;
600                }
601            }
602        }
603        if !self.cluster_by.is_empty() {
604            SpaceOrNewline.fmt(f)?;
605            f.write_str("CLUSTER BY")?;
606            SpaceOrNewline.fmt(f)?;
607            Indent(display_comma_separated(&self.cluster_by)).fmt(f)?;
608        }
609        if !self.distribute_by.is_empty() {
610            SpaceOrNewline.fmt(f)?;
611            f.write_str("DISTRIBUTE BY")?;
612            SpaceOrNewline.fmt(f)?;
613            display_comma_separated(&self.distribute_by).fmt(f)?;
614        }
615        if !self.sort_by.is_empty() {
616            SpaceOrNewline.fmt(f)?;
617            f.write_str("SORT BY")?;
618            SpaceOrNewline.fmt(f)?;
619            Indent(display_comma_separated(&self.sort_by)).fmt(f)?;
620        }
621        if let Some(ref having) = self.having {
622            SpaceOrNewline.fmt(f)?;
623            f.write_str("HAVING")?;
624            SpaceOrNewline.fmt(f)?;
625            Indent(having).fmt(f)?;
626        }
627        if self.window_before_qualify {
628            if !self.named_window.is_empty() {
629                SpaceOrNewline.fmt(f)?;
630                f.write_str("WINDOW")?;
631                SpaceOrNewline.fmt(f)?;
632                display_comma_separated(&self.named_window).fmt(f)?;
633            }
634            if let Some(ref qualify) = self.qualify {
635                SpaceOrNewline.fmt(f)?;
636                f.write_str("QUALIFY")?;
637                SpaceOrNewline.fmt(f)?;
638                qualify.fmt(f)?;
639            }
640        } else {
641            if let Some(ref qualify) = self.qualify {
642                SpaceOrNewline.fmt(f)?;
643                f.write_str("QUALIFY")?;
644                SpaceOrNewline.fmt(f)?;
645                qualify.fmt(f)?;
646            }
647            if !self.named_window.is_empty() {
648                SpaceOrNewline.fmt(f)?;
649                f.write_str("WINDOW")?;
650                SpaceOrNewline.fmt(f)?;
651                display_comma_separated(&self.named_window).fmt(f)?;
652            }
653        }
654        Ok(())
655    }
656}
657
658/// A hive LATERAL VIEW with potential column aliases
659#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
660#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
661#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
662pub struct LateralView {
663    /// LATERAL VIEW
664    pub lateral_view: Expr,
665    /// LATERAL VIEW table name
666    pub lateral_view_name: ObjectName,
667    /// LATERAL VIEW optional column aliases
668    pub lateral_col_alias: Vec<Ident>,
669    /// LATERAL VIEW OUTER
670    pub outer: bool,
671}
672
673impl fmt::Display for LateralView {
674    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
675        write!(
676            f,
677            " LATERAL VIEW{outer} {} {}",
678            self.lateral_view,
679            self.lateral_view_name,
680            outer = if self.outer { " OUTER" } else { "" }
681        )?;
682        if !self.lateral_col_alias.is_empty() {
683            write!(
684                f,
685                " AS {}",
686                display_comma_separated(&self.lateral_col_alias)
687            )?;
688        }
689        Ok(())
690    }
691}
692
693/// An expression used in a named window declaration.
694///
695/// ```sql
696/// WINDOW mywindow AS [named_window_expr]
697/// ```
698#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
699#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
700#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
701pub enum NamedWindowExpr {
702    /// A direct reference to another named window definition.
703    /// [BigQuery]
704    ///
705    /// Example:
706    /// ```sql
707    /// WINDOW mywindow AS prev_window
708    /// ```
709    ///
710    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls#ref_named_window
711    NamedWindow(Ident),
712    /// A window expression.
713    ///
714    /// Example:
715    /// ```sql
716    /// WINDOW mywindow AS (ORDER BY 1)
717    /// ```
718    WindowSpec(WindowSpec),
719}
720
721impl fmt::Display for NamedWindowExpr {
722    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
723        match self {
724            NamedWindowExpr::NamedWindow(named_window) => {
725                write!(f, "{named_window}")?;
726            }
727            NamedWindowExpr::WindowSpec(window_spec) => {
728                write!(f, "({window_spec})")?;
729            }
730        };
731        Ok(())
732    }
733}
734
735#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
736#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
737#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
738/// A named window definition: `<name> AS <window specification>`
739pub struct NamedWindowDefinition(pub Ident, pub NamedWindowExpr);
740
741impl fmt::Display for NamedWindowDefinition {
742    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
743        write!(f, "{} AS {}", self.0, self.1)
744    }
745}
746
747#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
748#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
749#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
750/// A `WITH` clause, introducing common table expressions (CTEs).
751pub struct With {
752    /// Token for the `WITH` keyword
753    pub with_token: AttachedToken,
754    /// Whether the `WITH` is recursive (`WITH RECURSIVE`).
755    pub recursive: bool,
756    /// The list of CTEs declared by this `WITH` clause.
757    pub cte_tables: Vec<Cte>,
758}
759
760impl fmt::Display for With {
761    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
762        f.write_str("WITH ")?;
763        if self.recursive {
764            f.write_str("RECURSIVE ")?;
765        }
766        display_comma_separated(&self.cte_tables).fmt(f)?;
767        Ok(())
768    }
769}
770
771#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
772#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
773#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
774/// Indicates whether a CTE is materialized or not.
775pub enum CteAsMaterialized {
776    /// The `WITH` statement specifies `AS MATERIALIZED` behavior
777    Materialized,
778    /// The `WITH` statement specifies `AS NOT MATERIALIZED` behavior
779    NotMaterialized,
780}
781
782impl fmt::Display for CteAsMaterialized {
783    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
784        match *self {
785            CteAsMaterialized::Materialized => {
786                write!(f, "MATERIALIZED")?;
787            }
788            CteAsMaterialized::NotMaterialized => {
789                write!(f, "NOT MATERIALIZED")?;
790            }
791        };
792        Ok(())
793    }
794}
795
796/// A single CTE (used after `WITH`): `<alias> [(col1, col2, ...)] AS <materialized> ( <query> )`
797/// The names in the column list before `AS`, when specified, replace the names
798/// of the columns returned by the query. The parser does not validate that the
799/// number of columns in the query matches the number of columns in the query.
800#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
801#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
802#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
803pub struct Cte {
804    /// The CTE alias (name introduced before the `AS` keyword).
805    pub alias: TableAlias,
806    /// The query that defines the CTE body.
807    pub query: Box<Query>,
808    /// Optional `FROM` identifier for materialized CTEs.
809    pub from: Option<Ident>,
810    /// Optional `AS MATERIALIZED` / `AS NOT MATERIALIZED` hint.
811    pub materialized: Option<CteAsMaterialized>,
812    /// Token for the closing parenthesis of the CTE definition.
813    pub closing_paren_token: AttachedToken,
814}
815
816impl fmt::Display for Cte {
817    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
818        match self.materialized.as_ref() {
819            None => {
820                self.alias.fmt(f)?;
821                f.write_str(" AS (")?;
822                NewLine.fmt(f)?;
823                Indent(&self.query).fmt(f)?;
824                NewLine.fmt(f)?;
825                f.write_str(")")?;
826            }
827            Some(materialized) => {
828                self.alias.fmt(f)?;
829                f.write_str(" AS ")?;
830                materialized.fmt(f)?;
831                f.write_str(" (")?;
832                NewLine.fmt(f)?;
833                Indent(&self.query).fmt(f)?;
834                NewLine.fmt(f)?;
835                f.write_str(")")?;
836            }
837        };
838        if let Some(ref fr) = self.from {
839            write!(f, " FROM {fr}")?;
840        }
841        Ok(())
842    }
843}
844
845/// Represents an expression behind a wildcard expansion in a projection.
846/// `SELECT T.* FROM T;
847#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
848#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
849#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
850pub enum SelectItemQualifiedWildcardKind {
851    /// Expression is an object name.
852    /// e.g. `alias.*` or even `schema.table.*`
853    ObjectName(ObjectName),
854    /// Select star on an arbitrary expression.
855    /// e.g. `STRUCT<STRING>('foo').*`
856    Expr(Expr),
857}
858
859/// One item of the comma-separated list following `SELECT`
860#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
861#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
862#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
863pub enum SelectItem {
864    /// Any expression, not followed by `[ AS ] alias`
865    UnnamedExpr(Expr),
866    /// An expression, followed by `[ AS ] alias`
867    ExprWithAlias {
868        /// The expression being projected.
869        expr: Expr,
870        /// The alias for the expression.
871        alias: Ident,
872    },
873    /// An expression, followed by `[ AS ] (alias1, alias2, ...)`
874    ///
875    /// [Spark SQL](https://spark.apache.org/docs/latest/sql-ref-syntax-qry-select.html)
876    ExprWithAliases {
877        /// The expression being projected.
878        expr: Expr,
879        /// The list of aliases for the expression.
880        aliases: Vec<Ident>,
881    },
882    /// An expression, followed by a wildcard expansion.
883    /// e.g. `alias.*`, `STRUCT<STRING>('foo').*`
884    QualifiedWildcard(SelectItemQualifiedWildcardKind, WildcardAdditionalOptions),
885    /// An unqualified `*`
886    Wildcard(WildcardAdditionalOptions),
887}
888
889impl fmt::Display for SelectItemQualifiedWildcardKind {
890    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
891        match &self {
892            SelectItemQualifiedWildcardKind::ObjectName(object_name) => {
893                write!(f, "{object_name}.*")
894            }
895            SelectItemQualifiedWildcardKind::Expr(expr) => write!(f, "{expr}.*"),
896        }
897    }
898}
899
900/// Single aliased identifier
901///
902/// # Syntax
903/// ```plaintext
904/// <ident> AS <alias>
905/// ```
906#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
907#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
908#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
909pub struct IdentWithAlias {
910    /// The identifier being aliased.
911    pub ident: Ident,
912    /// The alias to apply to `ident`.
913    pub alias: Ident,
914}
915
916impl fmt::Display for IdentWithAlias {
917    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
918        write!(f, "{} AS {}", self.ident, self.alias)
919    }
920}
921
922/// Additional options for wildcards, e.g. Snowflake `EXCLUDE`/`RENAME` and Bigquery `EXCEPT`.
923#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
924#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
925#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
926pub struct WildcardAdditionalOptions {
927    /// The wildcard token `*`
928    pub wildcard_token: AttachedToken,
929    /// `[ILIKE...]`.
930    ///  Snowflake syntax: <https://docs.snowflake.com/en/sql-reference/sql/select#parameters>
931    pub opt_ilike: Option<IlikeSelectItem>,
932    /// `[EXCLUDE...]`.
933    pub opt_exclude: Option<ExcludeSelectItem>,
934    /// `[EXCEPT...]`.
935    ///  Clickhouse syntax: <https://clickhouse.com/docs/en/sql-reference/statements/select#except>
936    pub opt_except: Option<ExceptSelectItem>,
937    /// `[REPLACE]`
938    ///  BigQuery syntax: <https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#select_replace>
939    ///  Clickhouse syntax: <https://clickhouse.com/docs/en/sql-reference/statements/select#replace>
940    ///  Snowflake syntax: <https://docs.snowflake.com/en/sql-reference/sql/select#parameters>
941    pub opt_replace: Option<ReplaceSelectItem>,
942    /// `[RENAME ...]`.
943    pub opt_rename: Option<RenameSelectItem>,
944    /// `[AS <alias>]`.
945    ///  Redshift syntax: <https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_list.html>
946    pub opt_alias: Option<Ident>,
947}
948
949impl Default for WildcardAdditionalOptions {
950    fn default() -> Self {
951        Self {
952            wildcard_token: TokenWithSpan::wrap(Token::Mul).into(),
953            opt_ilike: None,
954            opt_exclude: None,
955            opt_except: None,
956            opt_replace: None,
957            opt_rename: None,
958            opt_alias: None,
959        }
960    }
961}
962
963impl fmt::Display for WildcardAdditionalOptions {
964    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
965        if let Some(ilike) = &self.opt_ilike {
966            write!(f, " {ilike}")?;
967        }
968        if let Some(exclude) = &self.opt_exclude {
969            write!(f, " {exclude}")?;
970        }
971        if let Some(except) = &self.opt_except {
972            write!(f, " {except}")?;
973        }
974        if let Some(replace) = &self.opt_replace {
975            write!(f, " {replace}")?;
976        }
977        if let Some(rename) = &self.opt_rename {
978            write!(f, " {rename}")?;
979        }
980        if let Some(alias) = &self.opt_alias {
981            write!(f, " AS {alias}")?;
982        }
983        Ok(())
984    }
985}
986
987/// Snowflake `ILIKE` information.
988///
989/// # Syntax
990/// ```plaintext
991/// ILIKE <value>
992/// ```
993#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
994#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
995#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
996pub struct IlikeSelectItem {
997    /// The pattern expression used with `ILIKE`.
998    pub pattern: String,
999}
1000
1001impl fmt::Display for IlikeSelectItem {
1002    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1003        write!(
1004            f,
1005            "ILIKE '{}'",
1006            value::escape_single_quote_string(&self.pattern)
1007        )?;
1008        Ok(())
1009    }
1010}
1011/// Snowflake `EXCLUDE` information.
1012///
1013/// # Syntax
1014/// ```plaintext
1015/// <col_name>
1016/// | (<col_name>, <col_name>, ...)
1017/// ```
1018#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1019#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1020#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1021pub enum ExcludeSelectItem {
1022    /// Single column name without parenthesis.
1023    ///
1024    /// # Syntax
1025    /// ```plaintext
1026    /// <col_name>
1027    /// ```
1028    Single(ObjectName),
1029    /// Multiple column names inside parenthesis.
1030    /// # Syntax
1031    /// ```plaintext
1032    /// (<col_name>, <col_name>, ...)
1033    /// ```
1034    Multiple(Vec<ObjectName>),
1035}
1036
1037impl fmt::Display for ExcludeSelectItem {
1038    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1039        write!(f, "EXCLUDE")?;
1040        match self {
1041            Self::Single(column) => {
1042                write!(f, " {column}")?;
1043            }
1044            Self::Multiple(columns) => {
1045                write!(f, " ({})", display_comma_separated(columns))?;
1046            }
1047        }
1048        Ok(())
1049    }
1050}
1051
1052/// Snowflake `RENAME` information.
1053///
1054/// # Syntax
1055/// ```plaintext
1056/// <col_name> AS <col_alias>
1057/// | (<col_name> AS <col_alias>, <col_name> AS <col_alias>, ...)
1058/// ```
1059#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1060#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1061#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1062pub enum RenameSelectItem {
1063    /// Single column name with alias without parenthesis.
1064    ///
1065    /// # Syntax
1066    /// ```plaintext
1067    /// <col_name> AS <col_alias>
1068    /// ```
1069    Single(IdentWithAlias),
1070    /// Multiple column names with aliases inside parenthesis.
1071    /// # Syntax
1072    /// ```plaintext
1073    /// (<col_name> AS <col_alias>, <col_name> AS <col_alias>, ...)
1074    /// ```
1075    Multiple(Vec<IdentWithAlias>),
1076}
1077
1078impl fmt::Display for RenameSelectItem {
1079    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1080        write!(f, "RENAME")?;
1081        match self {
1082            Self::Single(column) => {
1083                write!(f, " {column}")?;
1084            }
1085            Self::Multiple(columns) => {
1086                write!(f, " ({})", display_comma_separated(columns))?;
1087            }
1088        }
1089        Ok(())
1090    }
1091}
1092
1093/// Bigquery `EXCEPT` information, with at least one column.
1094///
1095/// # Syntax
1096/// ```plaintext
1097/// EXCEPT (<col_name> [, ...])
1098/// ```
1099#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1100#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1101#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1102pub struct ExceptSelectItem {
1103    /// First guaranteed column.
1104    pub first_element: Ident,
1105    /// Additional columns. This list can be empty.
1106    pub additional_elements: Vec<Ident>,
1107}
1108
1109impl fmt::Display for ExceptSelectItem {
1110    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1111        write!(f, "EXCEPT ")?;
1112        if self.additional_elements.is_empty() {
1113            write!(f, "({})", self.first_element)?;
1114        } else {
1115            write!(
1116                f,
1117                "({}, {})",
1118                self.first_element,
1119                display_comma_separated(&self.additional_elements)
1120            )?;
1121        }
1122        Ok(())
1123    }
1124}
1125
1126/// Bigquery `REPLACE` information.
1127///
1128/// # Syntax
1129/// ```plaintext
1130/// REPLACE (<new_expr> [AS] <col_name>)
1131/// REPLACE (<col_name> [AS] <col_alias>, <col_name> [AS] <col_alias>, ...)
1132/// ```
1133#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1135#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1136pub struct ReplaceSelectItem {
1137    /// List of replacement elements contained in the `REPLACE(...)` clause.
1138    pub items: Vec<Box<ReplaceSelectElement>>,
1139}
1140
1141impl fmt::Display for ReplaceSelectItem {
1142    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1143        write!(f, "REPLACE")?;
1144        write!(f, " ({})", display_comma_separated(&self.items))?;
1145        Ok(())
1146    }
1147}
1148
1149/// # Syntax
1150/// ```plaintext
1151/// <expr> [AS] <column_name>
1152/// ```
1153#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1154#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1155#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1156pub struct ReplaceSelectElement {
1157    /// Expression producing the replacement value.
1158    pub expr: Expr,
1159    /// The target column name for the replacement.
1160    pub column_name: Ident,
1161    /// Whether the `AS` keyword was present in the original syntax.
1162    pub as_keyword: bool,
1163}
1164
1165impl fmt::Display for ReplaceSelectElement {
1166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1167        if self.as_keyword {
1168            write!(f, "{} AS {}", self.expr, self.column_name)
1169        } else {
1170            write!(f, "{} {}", self.expr, self.column_name)
1171        }
1172    }
1173}
1174
1175impl fmt::Display for SelectItem {
1176    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1177        use core::fmt::Write;
1178        match &self {
1179            SelectItem::UnnamedExpr(expr) => expr.fmt(f),
1180            SelectItem::ExprWithAlias { expr, alias } => {
1181                expr.fmt(f)?;
1182                f.write_str(" AS ")?;
1183                alias.fmt(f)
1184            }
1185            SelectItem::ExprWithAliases { expr, aliases } => {
1186                expr.fmt(f)?;
1187                f.write_str(" AS (")?;
1188                display_comma_separated(aliases).fmt(f)?;
1189                f.write_str(")")
1190            }
1191            SelectItem::QualifiedWildcard(kind, additional_options) => {
1192                kind.fmt(f)?;
1193                additional_options.fmt(f)
1194            }
1195            SelectItem::Wildcard(additional_options) => {
1196                f.write_char('*')?;
1197                additional_options.fmt(f)
1198            }
1199        }
1200    }
1201}
1202
1203#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1204#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1205#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1206/// A left table followed by zero or more joins.
1207pub struct TableWithJoins {
1208    /// The starting table factor (left side) of the join chain.
1209    pub relation: TableFactor,
1210    /// The sequence of joins applied to the relation.
1211    pub joins: Vec<Join>,
1212}
1213
1214impl fmt::Display for TableWithJoins {
1215    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1216        self.relation.fmt(f)?;
1217        for join in &self.joins {
1218            SpaceOrNewline.fmt(f)?;
1219            join.fmt(f)?;
1220        }
1221        Ok(())
1222    }
1223}
1224
1225/// Joins a table to itself to process hierarchical data in the table.
1226///
1227/// See <https://docs.snowflake.com/en/sql-reference/constructs/connect-by>.
1228/// See <https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Hierarchical-Queries.html>
1229#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1230#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1231#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1232pub enum ConnectByKind {
1233    /// CONNECT BY
1234    ConnectBy {
1235        /// the `CONNECT` token
1236        connect_token: AttachedToken,
1237
1238        /// [CONNECT BY] NOCYCLE
1239        ///
1240        /// Optional on [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Hierarchical-Queries.html#GUID-0118DF1D-B9A9-41EB-8556-C6E7D6A5A84E__GUID-5377971A-F518-47E4-8781-F06FEB3EF993)
1241        nocycle: bool,
1242
1243        /// join conditions denoting the hierarchical relationship
1244        relationships: Vec<Expr>,
1245    },
1246
1247    /// START WITH
1248    ///
1249    /// Optional on [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Hierarchical-Queries.html#GUID-0118DF1D-B9A9-41EB-8556-C6E7D6A5A84E)
1250    /// when comming _after_ the `CONNECT BY`.
1251    StartWith {
1252        /// the `START` token
1253        start_token: AttachedToken,
1254
1255        /// condition selecting the root rows of the hierarchy
1256        condition: Box<Expr>,
1257    },
1258}
1259
1260impl fmt::Display for ConnectByKind {
1261    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1262        match self {
1263            ConnectByKind::ConnectBy {
1264                connect_token: _,
1265                nocycle,
1266                relationships,
1267            } => {
1268                write!(
1269                    f,
1270                    "CONNECT BY {nocycle}{relationships}",
1271                    nocycle = if *nocycle { "NOCYCLE " } else { "" },
1272                    relationships = display_comma_separated(relationships)
1273                )
1274            }
1275            ConnectByKind::StartWith {
1276                start_token: _,
1277                condition,
1278            } => {
1279                write!(f, "START WITH {condition}")
1280            }
1281        }
1282    }
1283}
1284
1285#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1286#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1287#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1288/// A single setting key-value pair.
1289pub struct Setting {
1290    /// Setting name/key.
1291    pub key: Ident,
1292    /// The value expression assigned to the setting.
1293    pub value: Expr,
1294}
1295
1296impl fmt::Display for Setting {
1297    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1298        write!(f, "{} = {}", self.key, self.value)
1299    }
1300}
1301
1302/// An expression optionally followed by an alias.
1303///
1304/// Example:
1305/// ```sql
1306/// 42 AS myint
1307/// ```
1308#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1309#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1310#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1311pub struct ExprWithAlias {
1312    /// The expression.
1313    pub expr: Expr,
1314    /// Optional alias for the expression.
1315    pub alias: Option<Ident>,
1316}
1317
1318impl fmt::Display for ExprWithAlias {
1319    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1320        let ExprWithAlias { expr, alias } = self;
1321        write!(f, "{expr}")?;
1322        if let Some(alias) = alias {
1323            write!(f, " AS {alias}")?;
1324        }
1325        Ok(())
1326    }
1327}
1328
1329/// An expression optionally followed by an alias and order by options.
1330///
1331/// Example:
1332/// ```sql
1333/// 42 AS myint ASC
1334/// ```
1335#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1336#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1337#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1338pub struct ExprWithAliasAndOrderBy {
1339    /// Expression with optional alias.
1340    pub expr: ExprWithAlias,
1341    /// Ordering options applied to the expression.
1342    pub order_by: OrderByOptions,
1343}
1344
1345impl fmt::Display for ExprWithAliasAndOrderBy {
1346    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1347        write!(f, "{}{}", self.expr, self.order_by)
1348    }
1349}
1350
1351/// Arguments to a table-valued function
1352#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1353#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1354#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1355pub struct TableFunctionArgs {
1356    /// The list of arguments passed to the table-valued function.
1357    pub args: Vec<FunctionArg>,
1358    /// ClickHouse-specific `SETTINGS` clause.
1359    /// For example,
1360    /// `SELECT * FROM executable('generate_random.py', TabSeparated, 'id UInt32, random String', SETTINGS send_chunk_header = false, pool_size = 16)`
1361    /// [`executable` table function](https://clickhouse.com/docs/en/engines/table-functions/executable)
1362    pub settings: Option<Vec<Setting>>,
1363}
1364
1365#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1366#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1367#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1368/// Type of index hint (e.g., `USE`, `IGNORE`, `FORCE`).
1369pub enum TableIndexHintType {
1370    /// `USE` hint.
1371    Use,
1372    /// `IGNORE` hint.
1373    Ignore,
1374    /// `FORCE` hint.
1375    Force,
1376}
1377
1378impl fmt::Display for TableIndexHintType {
1379    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1380        f.write_str(match self {
1381            TableIndexHintType::Use => "USE",
1382            TableIndexHintType::Ignore => "IGNORE",
1383            TableIndexHintType::Force => "FORCE",
1384        })
1385    }
1386}
1387
1388#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1389#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1390#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1391/// The kind of index referenced by an index hint (e.g. `USE INDEX`).
1392pub enum TableIndexType {
1393    /// The `INDEX` kind.
1394    Index,
1395    /// The `KEY` kind.
1396    Key,
1397}
1398
1399impl fmt::Display for TableIndexType {
1400    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1401        f.write_str(match self {
1402            TableIndexType::Index => "INDEX",
1403            TableIndexType::Key => "KEY",
1404        })
1405    }
1406}
1407
1408#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1409#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1410#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1411/// Which clause the table index hint applies to.
1412pub enum TableIndexHintForClause {
1413    /// Apply the hint to JOIN clauses.
1414    Join,
1415    /// Apply the hint to `ORDER BY` clauses.
1416    OrderBy,
1417    /// Apply the hint to `GROUP BY` clauses.
1418    GroupBy,
1419}
1420
1421impl fmt::Display for TableIndexHintForClause {
1422    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1423        f.write_str(match self {
1424            TableIndexHintForClause::Join => "JOIN",
1425            TableIndexHintForClause::OrderBy => "ORDER BY",
1426            TableIndexHintForClause::GroupBy => "GROUP BY",
1427        })
1428    }
1429}
1430
1431#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1432#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1433#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1434/// MySQL-style index hints attached to a table (e.g., `USE INDEX(...)`).
1435pub struct TableIndexHints {
1436    /// Type of hint (e.g., `USE`, `FORCE`, or `IGNORE`).
1437    pub hint_type: TableIndexHintType,
1438    /// The index type (e.g., `INDEX`).
1439    pub index_type: TableIndexType,
1440    /// Optional `FOR` clause specifying the scope (JOIN / ORDER BY / GROUP BY).
1441    pub for_clause: Option<TableIndexHintForClause>,
1442    /// List of index names referred to by the hint.
1443    pub index_names: Vec<Ident>,
1444}
1445
1446impl fmt::Display for TableIndexHints {
1447    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1448        write!(f, "{} {} ", self.hint_type, self.index_type)?;
1449        if let Some(for_clause) = &self.for_clause {
1450            write!(f, "FOR {for_clause} ")?;
1451        }
1452        write!(f, "({})", display_comma_separated(&self.index_names))
1453    }
1454}
1455
1456/// A table-level index-selection directive, see [`TableFactor::Table::index_directives`].
1457#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1458#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1459#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1460pub enum TableIndexDirective {
1461    /// `{USE | IGNORE | FORCE} {INDEX | KEY} [FOR ...] (index_name, ...)`, see
1462    /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/index-hints.html)
1463    MySql(TableIndexHints),
1464    /// Require the named index with SQLite's [`INDEXED BY`](https://www.sqlite.org/lang_indexedby.html).
1465    IndexedBy(Ident),
1466    /// Prohibit index use except rowid lookups with SQLite's [`NOT INDEXED`](https://www.sqlite.org/lang_indexedby.html).
1467    NotIndexed,
1468}
1469
1470impl fmt::Display for TableIndexDirective {
1471    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1472        match self {
1473            TableIndexDirective::MySql(hint) => hint.fmt(f),
1474            TableIndexDirective::IndexedBy(name) => write!(f, "INDEXED BY {name}"),
1475            TableIndexDirective::NotIndexed => f.write_str("NOT INDEXED"),
1476        }
1477    }
1478}
1479
1480/// PostgreSQL table inheritance marker, see [`TableFactor::Table::inheritance`].
1481///
1482/// <https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM>
1483#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1484#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1485#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1486pub enum TableInheritance {
1487    /// `ONLY name`, or `ONLY (name)` when `parenthesized`, excluding descendant tables.
1488    Only {
1489        /// Whether the name was written in parentheses.
1490        parenthesized: bool,
1491    },
1492    /// `name *`, explicitly including descendant tables.
1493    IncludeDescendants,
1494}
1495
1496/// A table name or a parenthesized subquery with an optional alias
1497#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1498#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1499#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1500#[cfg_attr(feature = "visitor", visit(with = "visit_table_factor"))]
1501pub enum TableFactor {
1502    /// A named table or relation, possibly with arguments, hints, or sampling.
1503    Table {
1504        #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
1505        /// Table or relation name.
1506        name: ObjectName,
1507        /// Optional alias for the table (e.g. `table AS t`).
1508        alias: Option<TableAlias>,
1509        /// Arguments of a table-valued function, as supported by Postgres
1510        /// and MSSQL. Note that deprecated MSSQL `FROM foo (NOLOCK)` syntax
1511        /// will also be parsed as `args`.
1512        ///
1513        /// This field's value is `Some(v)`, where `v` is a (possibly empty)
1514        /// vector of arguments, in the case of a table-valued function call,
1515        /// whereas it's `None` in the case of a regular table name.
1516        args: Option<TableFunctionArgs>,
1517        /// MSSQL-specific `WITH (...)` hints such as NOLOCK.
1518        with_hints: Vec<Expr>,
1519        /// Optional version qualifier to facilitate table time-travel, as
1520        /// supported by BigQuery and MSSQL.
1521        version: Option<TableVersion>,
1522        //  Optional table function modifier to generate the ordinality for column.
1523        /// For example, `SELECT * FROM generate_series(1, 10) WITH ORDINALITY AS t(a, b);`
1524        /// [WITH ORDINALITY](https://www.postgresql.org/docs/current/functions-srf.html), supported by Postgres.
1525        with_ordinality: bool,
1526        /// [Partition selection](https://dev.mysql.com/doc/refman/8.0/en/partitioning-selection.html), supported by MySQL.
1527        partitions: Vec<Ident>,
1528        /// Optional PartiQL JsonPath: <https://partiql.org/dql/from.html>
1529        json_path: Option<JsonPath>,
1530        /// Optional table sample modifier
1531        /// See: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#sample-clause>
1532        sample: Option<TableSampleKind>,
1533        /// Optional table-level index-selection hints or requirements.
1534        index_directives: Vec<TableIndexDirective>,
1535        /// PostgreSQL `ONLY` or `*` inheritance marker.
1536        inheritance: Option<TableInheritance>,
1537    },
1538    /// A derived table (a parenthesized subquery), optionally `LATERAL`.
1539    Derived {
1540        /// Whether the derived table is LATERAL.
1541        lateral: bool,
1542        /// The subquery producing the derived table.
1543        subquery: Box<Query>,
1544        /// Optional alias for the derived table.
1545        alias: Option<TableAlias>,
1546        /// Optional table sample modifier
1547        sample: Option<TableSampleKind>,
1548    },
1549    /// `TABLE(<expr>)[ AS <alias> ]`
1550    TableFunction {
1551        /// Expression representing the table function call.
1552        expr: Expr,
1553        /// Optional alias for the table function result.
1554        alias: Option<TableAlias>,
1555    },
1556    /// `e.g. LATERAL FLATTEN(<args>)[ AS <alias> ]`
1557    Function {
1558        /// Whether the function is LATERAL.
1559        lateral: bool,
1560        /// Name of the table function.
1561        name: ObjectName,
1562        /// Arguments passed to the function.
1563        args: Vec<FunctionArg>,
1564        /// Whether `WITH ORDINALITY` was specified to include ordinality.
1565        with_ordinality: bool,
1566        /// Optional alias for the result of the function.
1567        alias: Option<TableAlias>,
1568    },
1569    /// ```sql
1570    /// SELECT * FROM UNNEST ([10,20,30]) as numbers WITH OFFSET;
1571    /// +---------+--------+
1572    /// | numbers | offset |
1573    /// +---------+--------+
1574    /// | 10      | 0      |
1575    /// | 20      | 1      |
1576    /// | 30      | 2      |
1577    /// +---------+--------+
1578    /// ```
1579    UNNEST {
1580        /// Optional alias for the UNNEST table (e.g. `UNNEST(...) AS t`).
1581        alias: Option<TableAlias>,
1582        /// Expressions producing the arrays to be unnested.
1583        array_exprs: Vec<Expr>,
1584        /// Whether `WITH OFFSET` was specified to include element offsets.
1585        with_offset: bool,
1586        /// Optional alias for the offset column when `WITH OFFSET` is used.
1587        with_offset_alias: Option<Ident>,
1588        /// Whether `WITH ORDINALITY` was specified to include ordinality.
1589        with_ordinality: bool,
1590    },
1591    /// The `JSON_TABLE` table-valued function.
1592    /// Part of the SQL standard, but implemented only by MySQL, Oracle, and DB2.
1593    ///
1594    /// <https://modern-sql.com/blog/2017-06/whats-new-in-sql-2016#json_table>
1595    /// <https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html#function_json-table>
1596    ///
1597    /// ```sql
1598    /// SELECT * FROM JSON_TABLE(
1599    ///    '[{"a": 1, "b": 2}, {"a": 3, "b": 4}]',
1600    ///    '$[*]' COLUMNS(
1601    ///        a INT PATH '$.a' DEFAULT '0' ON EMPTY,
1602    ///        b INT PATH '$.b' NULL ON ERROR
1603    ///     )
1604    /// ) AS jt;
1605    /// ````
1606    JsonTable {
1607        /// The JSON expression to be evaluated. It must evaluate to a json string
1608        json_expr: Expr,
1609        /// The path to the array or object to be iterated over.
1610        /// It must evaluate to a json array or object.
1611        json_path: ValueWithSpan,
1612        /// The columns to be extracted from each element of the array or object.
1613        /// Each column must have a name and a type.
1614        columns: Vec<JsonTableColumn>,
1615        /// The alias for the table.
1616        alias: Option<TableAlias>,
1617    },
1618    /// The MSSQL's `OPENJSON` table-valued function.
1619    ///
1620    /// ```sql
1621    /// OPENJSON( jsonExpression [ , path ] )  [ <with_clause> ]
1622    ///
1623    /// <with_clause> ::= WITH ( { colName type [ column_path ] [ AS JSON ] } [ ,...n ] )
1624    /// ````
1625    ///
1626    /// Reference: <https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16#syntax>
1627    OpenJsonTable {
1628        /// The JSON expression to be evaluated. It must evaluate to a json string
1629        json_expr: Expr,
1630        /// The path to the array or object to be iterated over.
1631        /// It must evaluate to a json array or object.
1632        json_path: Option<ValueWithSpan>,
1633        /// The columns to be extracted from each element of the array or object.
1634        /// Each column must have a name and a type.
1635        columns: Vec<OpenJsonTableColumn>,
1636        /// The alias for the table.
1637        alias: Option<TableAlias>,
1638    },
1639    /// Represents a parenthesized table factor. The SQL spec only allows a
1640    /// join expression (`(foo <JOIN> bar [ <JOIN> baz ... ])`) to be nested,
1641    /// possibly several times.
1642    ///
1643    /// The parser may also accept non-standard nesting of bare tables for some
1644    /// dialects, but the information about such nesting is stripped from AST.
1645    NestedJoin {
1646        /// The nested join expression contained in parentheses.
1647        table_with_joins: Box<TableWithJoins>,
1648        /// Optional alias for the nested join.
1649        alias: Option<TableAlias>,
1650    },
1651    /// Represents PIVOT operation on a table.
1652    /// For example `FROM monthly_sales PIVOT(sum(amount) FOR MONTH IN ('JAN', 'FEB'))`
1653    ///
1654    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#pivot_operator)
1655    /// [Snowflake](https://docs.snowflake.com/en/sql-reference/constructs/pivot)
1656    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/SELECT.html#GUID-CFA006CA-6FF1-4972-821E-6996142A51C6__GUID-68257B27-1C4C-4C47-8140-5C60E0E65D35)
1657    Pivot {
1658        /// The input table to pivot.
1659        table: Box<TableFactor>,
1660        /// Aggregate expressions used as pivot values (optionally aliased).
1661        aggregate_functions: Vec<ExprWithAlias>, // Function expression
1662        /// Columns producing the values to be pivoted.
1663        value_column: Vec<Expr>,
1664        /// Source of pivot values (e.g. list of literals or columns).
1665        value_source: PivotValueSource,
1666        /// Optional expression providing a default when a pivot produces NULL.
1667        default_on_null: Option<Expr>,
1668        /// Optional alias for the pivoted table.
1669        alias: Option<TableAlias>,
1670    },
1671    /// An UNPIVOT operation on a table.
1672    ///
1673    /// Syntax:
1674    /// ```sql
1675    /// table UNPIVOT [ { INCLUDE | EXCLUDE } NULLS ] (value FOR name IN (column1, [ column2, ... ])) [ alias ]
1676    /// ```
1677    ///
1678    /// [Snowflake](https://docs.snowflake.com/en/sql-reference/constructs/unpivot)
1679    /// [Databricks](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-qry-select-unpivot)
1680    /// [BigQuery](https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#unpivot_operator)
1681    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/SELECT.html#GUID-CFA006CA-6FF1-4972-821E-6996142A51C6__GUID-9B4E0389-413C-4014-94A1-0A0571BDF7E1)
1682    Unpivot {
1683        /// The input table to unpivot.
1684        table: Box<TableFactor>,
1685        /// Expression producing the unpivoted value.
1686        value: Expr,
1687        /// Identifier used for the generated column name.
1688        name: Ident,
1689        /// Columns or expressions to unpivot, optionally aliased.
1690        columns: Vec<ExprWithAlias>,
1691        /// Whether to include or exclude NULLs during unpivot.
1692        null_inclusion: Option<NullInclusion>,
1693        /// Optional alias for the resulting table.
1694        alias: Option<TableAlias>,
1695    },
1696    /// Object unpivoting on a SUPER expression in the FROM clause.
1697    ///
1698    /// Syntax:
1699    /// ```sql
1700    /// UNPIVOT expression AS value_alias [AT attribute_alias]
1701    /// ```
1702    /// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/query-super.html#unpivoting)
1703    UnpivotExpr {
1704        /// SUPER expression to unpivot.
1705        expression: Expr,
1706        /// Alias for the generated unpivoted value.
1707        value_alias: Ident,
1708        /// Optional alias for the generated attribute key/index.
1709        attribute_alias: Option<Ident>,
1710    },
1711    /// A `MATCH_RECOGNIZE` operation on a table.
1712    ///
1713    /// See <https://docs.snowflake.com/en/sql-reference/constructs/match_recognize>.
1714    MatchRecognize {
1715        /// The input table to apply `MATCH_RECOGNIZE` on.
1716        table: Box<TableFactor>,
1717        /// `PARTITION BY <expr> [, ... ]`
1718        partition_by: Vec<Expr>,
1719        /// `ORDER BY <expr> [, ... ]`
1720        order_by: Vec<OrderByExpr>,
1721        /// `MEASURES <expr> [AS] <alias> [, ... ]`
1722        measures: Vec<Measure>,
1723        /// `ONE ROW PER MATCH | ALL ROWS PER MATCH [ <option> ]`
1724        rows_per_match: Option<RowsPerMatch>,
1725        /// `AFTER MATCH SKIP <option>`
1726        after_match_skip: Option<AfterMatchSkip>,
1727        /// `PATTERN ( <pattern> )`
1728        pattern: MatchRecognizePattern,
1729        /// `DEFINE <symbol> AS <expr> [, ... ]`
1730        symbols: Vec<SymbolDefinition>,
1731        /// The alias for the table.
1732        alias: Option<TableAlias>,
1733    },
1734    /// The `XMLTABLE` table-valued function.
1735    /// Part of the SQL standard, supported by PostgreSQL, Oracle, and DB2.
1736    ///
1737    /// <https://www.postgresql.org/docs/15/functions-xml.html#FUNCTIONS-XML-PROCESSING>
1738    ///
1739    /// ```sql
1740    /// SELECT xmltable.*
1741    /// FROM xmldata,
1742    /// XMLTABLE('//ROWS/ROW'
1743    ///     PASSING data
1744    ///     COLUMNS id int PATH '@id',
1745    ///     ordinality FOR ORDINALITY,
1746    ///     "COUNTRY_NAME" text,
1747    ///     country_id text PATH 'COUNTRY_ID',
1748    ///     size_sq_km float PATH 'SIZE[@unit = "sq_km"]',
1749    ///     size_other text PATH 'concat(SIZE[@unit!="sq_km"], " ", SIZE[@unit!="sq_km"]/@unit)',
1750    ///     premier_name text PATH 'PREMIER_NAME' DEFAULT 'not specified'
1751    /// );
1752    /// ````
1753    XmlTable {
1754        /// Optional XMLNAMESPACES clause (empty if not present)
1755        namespaces: Vec<XmlNamespaceDefinition>,
1756        /// The row-generating XPath expression.
1757        row_expression: Expr,
1758        /// The PASSING clause specifying the document expression.
1759        passing: XmlPassingClause,
1760        /// The columns to be extracted from each generated row.
1761        columns: Vec<XmlTableColumn>,
1762        /// The alias for the table.
1763        alias: Option<TableAlias>,
1764    },
1765    /// Snowflake's SEMANTIC_VIEW function for semantic models.
1766    ///
1767    /// <https://docs.snowflake.com/en/sql-reference/constructs/semantic_view>
1768    ///
1769    /// ```sql
1770    /// SELECT * FROM SEMANTIC_VIEW(
1771    ///     tpch_analysis
1772    ///     DIMENSIONS customer.customer_market_segment
1773    ///     METRICS orders.order_average_value
1774    /// );
1775    /// ```
1776    SemanticView {
1777        /// The name of the semantic model
1778        name: ObjectName,
1779        /// List of dimensions or expression referring to dimensions (e.g. DATE_PART('year', col))
1780        dimensions: Vec<Expr>,
1781        /// List of metrics (references to objects like orders.value, value, orders.*)
1782        metrics: Vec<Expr>,
1783        /// List of facts or expressions referring to facts or dimensions.
1784        facts: Vec<Expr>,
1785        /// WHERE clause for filtering
1786        where_clause: Option<Expr>,
1787        /// The alias for the table
1788        alias: Option<TableAlias>,
1789    },
1790}
1791
1792/// The table sample modifier options
1793#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1794#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1795#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1796pub enum TableSampleKind {
1797    /// Table sample located before the table alias option
1798    BeforeTableAlias(Box<TableSample>),
1799    /// Table sample located after the table alias option
1800    AfterTableAlias(Box<TableSample>),
1801}
1802
1803#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1804#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1805#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1806/// Represents a `TABLESAMPLE` clause and its options.
1807pub struct TableSample {
1808    /// Modifier (e.g. `SAMPLE` or `TABLESAMPLE`).
1809    pub modifier: TableSampleModifier,
1810    /// Optional sampling method name (e.g. `BERNOULLI`, `SYSTEM`).
1811    pub name: Option<TableSampleMethod>,
1812    /// Optional sampling quantity (value and optional unit).
1813    pub quantity: Option<TableSampleQuantity>,
1814    /// Optional seed clause.
1815    pub seed: Option<TableSampleSeed>,
1816    /// Optional bucket specification for `BUCKET ... OUT OF ...`-style sampling.
1817    pub bucket: Option<TableSampleBucket>,
1818    /// Optional offset expression for sampling.
1819    pub offset: Option<Expr>,
1820}
1821
1822#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1823#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1824#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1825/// Modifier specifying whether `SAMPLE` or `TABLESAMPLE` keyword was used.
1826pub enum TableSampleModifier {
1827    /// `SAMPLE` modifier.
1828    Sample,
1829    /// `TABLESAMPLE` modifier.
1830    TableSample,
1831}
1832
1833impl fmt::Display for TableSampleModifier {
1834    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1835        match self {
1836            TableSampleModifier::Sample => write!(f, "SAMPLE")?,
1837            TableSampleModifier::TableSample => write!(f, "TABLESAMPLE")?,
1838        }
1839        Ok(())
1840    }
1841}
1842
1843#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1844#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1845#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1846/// Quantity for a `TABLESAMPLE` clause (e.g. `10 PERCENT` or `(10)`).
1847pub struct TableSampleQuantity {
1848    /// Whether the quantity was wrapped in parentheses.
1849    pub parenthesized: bool,
1850    /// The numeric expression specifying the quantity.
1851    pub value: Expr,
1852    /// Optional unit (e.g. `PERCENT`, `ROWS`).
1853    pub unit: Option<TableSampleUnit>,
1854}
1855
1856impl fmt::Display for TableSampleQuantity {
1857    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1858        if self.parenthesized {
1859            write!(f, "(")?;
1860        }
1861        write!(f, "{}", self.value)?;
1862        if let Some(unit) = &self.unit {
1863            write!(f, " {unit}")?;
1864        }
1865        if self.parenthesized {
1866            write!(f, ")")?;
1867        }
1868        Ok(())
1869    }
1870}
1871
1872/// The table sample method names
1873#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1874#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1875#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1876/// Sampling method used by `TABLESAMPLE`.
1877pub enum TableSampleMethod {
1878    /// `ROW` sampling method.
1879    Row,
1880    /// `BERNOULLI` sampling method.
1881    Bernoulli,
1882    /// `SYSTEM` sampling method.
1883    System,
1884    /// `BLOCK` sampling method.
1885    Block,
1886}
1887
1888impl fmt::Display for TableSampleMethod {
1889    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1890        match self {
1891            TableSampleMethod::Bernoulli => write!(f, "BERNOULLI"),
1892            TableSampleMethod::Row => write!(f, "ROW"),
1893            TableSampleMethod::System => write!(f, "SYSTEM"),
1894            TableSampleMethod::Block => write!(f, "BLOCK"),
1895        }
1896    }
1897}
1898
1899#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1900#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1901#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1902/// `SEED` or `REPEATABLE` clause used with sampling.
1903pub struct TableSampleSeed {
1904    /// Seed modifier (e.g. `REPEATABLE` or `SEED`).
1905    pub modifier: TableSampleSeedModifier,
1906    /// The seed value expression.
1907    pub value: ValueWithSpan,
1908}
1909
1910impl fmt::Display for TableSampleSeed {
1911    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1912        write!(f, "{} ({})", self.modifier, self.value)?;
1913        Ok(())
1914    }
1915}
1916
1917#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1918#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1919#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1920/// Modifier specifying how the sample seed is applied.
1921pub enum TableSampleSeedModifier {
1922    /// `REPEATABLE` modifier.
1923    Repeatable,
1924    /// `SEED` modifier.
1925    Seed,
1926}
1927
1928impl fmt::Display for TableSampleSeedModifier {
1929    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1930        match self {
1931            TableSampleSeedModifier::Repeatable => write!(f, "REPEATABLE"),
1932            TableSampleSeedModifier::Seed => write!(f, "SEED"),
1933        }
1934    }
1935}
1936
1937#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1938#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1939#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1940/// Unit used with a `TABLESAMPLE` quantity (rows or percent).
1941pub enum TableSampleUnit {
1942    /// `ROWS` unit.
1943    Rows,
1944    /// `PERCENT` unit.
1945    Percent,
1946}
1947
1948impl fmt::Display for TableSampleUnit {
1949    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1950        match self {
1951            TableSampleUnit::Percent => write!(f, "PERCENT"),
1952            TableSampleUnit::Rows => write!(f, "ROWS"),
1953        }
1954    }
1955}
1956
1957#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1958#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1959#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1960/// Bucket-based sampling clause: `BUCKET <bucket> OUT OF <total> [ON <expr>]`.
1961pub struct TableSampleBucket {
1962    /// The bucket index expression.
1963    pub bucket: ValueWithSpan,
1964    /// The total number of buckets expression.
1965    pub total: ValueWithSpan,
1966    /// Optional `ON <expr>` specification.
1967    pub on: Option<Expr>,
1968}
1969
1970impl fmt::Display for TableSampleBucket {
1971    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1972        write!(f, "BUCKET {} OUT OF {}", self.bucket, self.total)?;
1973        if let Some(on) = &self.on {
1974            write!(f, " ON {on}")?;
1975        }
1976        Ok(())
1977    }
1978}
1979impl fmt::Display for TableSample {
1980    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1981        write!(f, "{}", self.modifier)?;
1982        if let Some(name) = &self.name {
1983            write!(f, " {name}")?;
1984        }
1985        if let Some(quantity) = &self.quantity {
1986            write!(f, " {quantity}")?;
1987        }
1988        if let Some(seed) = &self.seed {
1989            write!(f, " {seed}")?;
1990        }
1991        if let Some(bucket) = &self.bucket {
1992            write!(f, " ({bucket})")?;
1993        }
1994        if let Some(offset) = &self.offset {
1995            write!(f, " OFFSET {offset}")?;
1996        }
1997        Ok(())
1998    }
1999}
2000
2001/// The source of values in a `PIVOT` operation.
2002#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2003#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2004#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2005pub enum PivotValueSource {
2006    /// Pivot on a static list of values.
2007    ///
2008    /// See <https://docs.snowflake.com/en/sql-reference/constructs/pivot#pivot-on-a-specified-list-of-column-values-for-the-pivot-column>.
2009    List(Vec<ExprWithAlias>),
2010    /// Pivot on all distinct values of the pivot column.
2011    ///
2012    /// See <https://docs.snowflake.com/en/sql-reference/constructs/pivot#pivot-on-all-distinct-column-values-automatically-with-dynamic-pivot>.
2013    Any(Vec<OrderByExpr>),
2014    /// Pivot on all values returned by a subquery.
2015    ///
2016    /// See <https://docs.snowflake.com/en/sql-reference/constructs/pivot#pivot-on-column-values-using-a-subquery-with-dynamic-pivot>.
2017    Subquery(Box<Query>),
2018}
2019
2020impl fmt::Display for PivotValueSource {
2021    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2022        match self {
2023            PivotValueSource::List(values) => write!(f, "{}", display_comma_separated(values)),
2024            PivotValueSource::Any(order_by) => {
2025                write!(f, "ANY")?;
2026                if !order_by.is_empty() {
2027                    write!(f, " ORDER BY {}", display_comma_separated(order_by))?;
2028                }
2029                Ok(())
2030            }
2031            PivotValueSource::Subquery(query) => write!(f, "{query}"),
2032        }
2033    }
2034}
2035
2036/// An item in the `MEASURES` subclause of a `MATCH_RECOGNIZE` operation.
2037///
2038/// See <https://docs.snowflake.com/en/sql-reference/constructs/match_recognize#measures-specifying-additional-output-columns>.
2039#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2040#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2041#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2042/// An item in the `MEASURES` clause of `MATCH_RECOGNIZE`.
2043pub struct Measure {
2044    /// Expression producing the measure value.
2045    pub expr: Expr,
2046    /// Alias for the measure column.
2047    pub alias: Ident,
2048}
2049
2050impl fmt::Display for Measure {
2051    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2052        write!(f, "{} AS {}", self.expr, self.alias)
2053    }
2054}
2055
2056/// The rows per match option in a `MATCH_RECOGNIZE` operation.
2057///
2058/// See <https://docs.snowflake.com/en/sql-reference/constructs/match_recognize#row-s-per-match-specifying-the-rows-to-return>.
2059#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2060#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2061#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2062pub enum RowsPerMatch {
2063    /// `ONE ROW PER MATCH`
2064    OneRow,
2065    /// `ALL ROWS PER MATCH <mode>`
2066    AllRows(Option<EmptyMatchesMode>),
2067}
2068
2069impl fmt::Display for RowsPerMatch {
2070    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2071        match self {
2072            RowsPerMatch::OneRow => write!(f, "ONE ROW PER MATCH"),
2073            RowsPerMatch::AllRows(mode) => {
2074                write!(f, "ALL ROWS PER MATCH")?;
2075                if let Some(mode) = mode {
2076                    write!(f, " {mode}")?;
2077                }
2078                Ok(())
2079            }
2080        }
2081    }
2082}
2083
2084/// The after match skip option in a `MATCH_RECOGNIZE` operation.
2085///
2086/// See <https://docs.snowflake.com/en/sql-reference/constructs/match_recognize#after-match-skip-specifying-where-to-continue-after-a-match>.
2087#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2088#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2089#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2090pub enum AfterMatchSkip {
2091    /// `PAST LAST ROW`
2092    PastLastRow,
2093    /// `TO NEXT ROW`
2094    ToNextRow,
2095    /// `TO FIRST <symbol>`
2096    ToFirst(Ident),
2097    /// `TO LAST <symbol>`
2098    ToLast(Ident),
2099}
2100
2101impl fmt::Display for AfterMatchSkip {
2102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2103        write!(f, "AFTER MATCH SKIP ")?;
2104        match self {
2105            AfterMatchSkip::PastLastRow => write!(f, "PAST LAST ROW"),
2106            AfterMatchSkip::ToNextRow => write!(f, " TO NEXT ROW"),
2107            AfterMatchSkip::ToFirst(symbol) => write!(f, "TO FIRST {symbol}"),
2108            AfterMatchSkip::ToLast(symbol) => write!(f, "TO LAST {symbol}"),
2109        }
2110    }
2111}
2112
2113#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2114#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2115#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2116/// The mode for handling empty matches in a `MATCH_RECOGNIZE` operation.
2117pub enum EmptyMatchesMode {
2118    /// `SHOW EMPTY MATCHES`
2119    Show,
2120    /// `OMIT EMPTY MATCHES`
2121    Omit,
2122    /// `WITH UNMATCHED ROWS`
2123    WithUnmatched,
2124}
2125
2126impl fmt::Display for EmptyMatchesMode {
2127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2128        match self {
2129            EmptyMatchesMode::Show => write!(f, "SHOW EMPTY MATCHES"),
2130            EmptyMatchesMode::Omit => write!(f, "OMIT EMPTY MATCHES"),
2131            EmptyMatchesMode::WithUnmatched => write!(f, "WITH UNMATCHED ROWS"),
2132        }
2133    }
2134}
2135
2136/// A symbol defined in a `MATCH_RECOGNIZE` operation.
2137///
2138/// See <https://docs.snowflake.com/en/sql-reference/constructs/match_recognize#define-defining-symbols>.
2139#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2140#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2141#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2142/// A symbol defined in a `MATCH_RECOGNIZE` operation.
2143pub struct SymbolDefinition {
2144    /// The symbol identifier.
2145    pub symbol: Ident,
2146    /// The expression defining the symbol.
2147    pub definition: Expr,
2148}
2149
2150impl fmt::Display for SymbolDefinition {
2151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2152        write!(f, "{} AS {}", self.symbol, self.definition)
2153    }
2154}
2155
2156/// A symbol in a `MATCH_RECOGNIZE` pattern.
2157#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2158#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2159#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2160pub enum MatchRecognizeSymbol {
2161    /// A named symbol, e.g. `S1`.
2162    Named(Ident),
2163    /// A virtual symbol representing the start of the of partition (`^`).
2164    Start,
2165    /// A virtual symbol representing the end of the partition (`$`).
2166    End,
2167}
2168
2169impl fmt::Display for MatchRecognizeSymbol {
2170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2171        match self {
2172            MatchRecognizeSymbol::Named(symbol) => write!(f, "{symbol}"),
2173            MatchRecognizeSymbol::Start => write!(f, "^"),
2174            MatchRecognizeSymbol::End => write!(f, "$"),
2175        }
2176    }
2177}
2178
2179/// The pattern in a `MATCH_RECOGNIZE` operation.
2180///
2181/// See <https://docs.snowflake.com/en/sql-reference/constructs/match_recognize#pattern-specifying-the-pattern-to-match>.
2182#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2183#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2184#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2185pub enum MatchRecognizePattern {
2186    /// A named symbol such as `S1` or a virtual symbol such as `^`.
2187    Symbol(MatchRecognizeSymbol),
2188    /// {- symbol -}
2189    Exclude(MatchRecognizeSymbol),
2190    /// PERMUTE(symbol_1, ..., symbol_n)
2191    Permute(Vec<MatchRecognizeSymbol>),
2192    /// pattern_1 pattern_2 ... pattern_n
2193    Concat(Vec<MatchRecognizePattern>),
2194    /// ( pattern )
2195    Group(Box<MatchRecognizePattern>),
2196    /// pattern_1 | pattern_2 | ... | pattern_n
2197    Alternation(Vec<MatchRecognizePattern>),
2198    /// e.g. pattern*
2199    Repetition(Box<MatchRecognizePattern>, RepetitionQuantifier),
2200}
2201
2202impl fmt::Display for MatchRecognizePattern {
2203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2204        use MatchRecognizePattern::*;
2205        match self {
2206            Symbol(symbol) => write!(f, "{symbol}"),
2207            Exclude(symbol) => write!(f, "{{- {symbol} -}}"),
2208            Permute(symbols) => write!(f, "PERMUTE({})", display_comma_separated(symbols)),
2209            Concat(patterns) => write!(f, "{}", display_separated(patterns, " ")),
2210            Group(pattern) => write!(f, "( {pattern} )"),
2211            Alternation(patterns) => write!(f, "{}", display_separated(patterns, " | ")),
2212            Repetition(pattern, op) => write!(f, "{pattern}{op}"),
2213        }
2214    }
2215}
2216
2217/// Determines the minimum and maximum allowed occurrences of a pattern in a
2218/// `MATCH_RECOGNIZE` operation.
2219#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2220#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2221#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2222pub enum RepetitionQuantifier {
2223    /// `*`
2224    ZeroOrMore,
2225    /// `+`
2226    OneOrMore,
2227    /// `?`
2228    AtMostOne,
2229    /// `{n}`
2230    Exactly(u32),
2231    /// `{n,}`
2232    AtLeast(u32),
2233    /// `{,n}`
2234    AtMost(u32),
2235    /// `{n,m}
2236    Range(u32, u32),
2237    /// A reluctant (non-greedy) quantifier, for example `*?` or `{n,m}?`.
2238    Reluctant(Box<RepetitionQuantifier>),
2239}
2240
2241impl fmt::Display for RepetitionQuantifier {
2242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2243        use RepetitionQuantifier::*;
2244        match self {
2245            ZeroOrMore => write!(f, "*"),
2246            OneOrMore => write!(f, "+"),
2247            AtMostOne => write!(f, "?"),
2248            Exactly(n) => write!(f, "{{{n}}}"),
2249            AtLeast(n) => write!(f, "{{{n},}}"),
2250            AtMost(n) => write!(f, "{{,{n}}}"),
2251            Range(n, m) => write!(f, "{{{n},{m}}}"),
2252            Reluctant(quantifier) => write!(f, "{quantifier}?"),
2253        }
2254    }
2255}
2256
2257impl fmt::Display for TableFactor {
2258    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2259        match self {
2260            TableFactor::Table {
2261                name,
2262                alias,
2263                args,
2264                with_hints,
2265                version,
2266                partitions,
2267                with_ordinality,
2268                json_path,
2269                sample,
2270                index_directives,
2271                inheritance,
2272            } => {
2273                match inheritance {
2274                    Some(TableInheritance::Only {
2275                        parenthesized: true,
2276                    }) => write!(f, "ONLY ({name})")?,
2277                    Some(TableInheritance::Only {
2278                        parenthesized: false,
2279                    }) => write!(f, "ONLY {name}")?,
2280                    Some(TableInheritance::IncludeDescendants) => write!(f, "{name} *")?,
2281                    None => name.fmt(f)?,
2282                }
2283                if let Some(json_path) = json_path {
2284                    json_path.fmt(f)?;
2285                }
2286                if !partitions.is_empty() {
2287                    write!(f, " PARTITION ({})", display_comma_separated(partitions))?;
2288                }
2289                if let Some(args) = args {
2290                    write!(f, "(")?;
2291                    write!(f, "{}", display_comma_separated(&args.args))?;
2292                    if let Some(ref settings) = args.settings {
2293                        if !args.args.is_empty() {
2294                            write!(f, ", ")?;
2295                        }
2296                        write!(f, "SETTINGS {}", display_comma_separated(settings))?;
2297                    }
2298                    write!(f, ")")?;
2299                }
2300                if *with_ordinality {
2301                    write!(f, " WITH ORDINALITY")?;
2302                }
2303                if let Some(TableSampleKind::BeforeTableAlias(sample)) = sample {
2304                    write!(f, " {sample}")?;
2305                }
2306                if let Some(alias) = alias {
2307                    write!(f, " {alias}")?;
2308                }
2309                if !index_directives.is_empty() {
2310                    write!(f, " {}", display_separated(index_directives, " "))?;
2311                }
2312                if !with_hints.is_empty() {
2313                    write!(f, " WITH ({})", display_comma_separated(with_hints))?;
2314                }
2315                if let Some(version) = version {
2316                    write!(f, " {version}")?;
2317                }
2318                if let Some(TableSampleKind::AfterTableAlias(sample)) = sample {
2319                    write!(f, " {sample}")?;
2320                }
2321                Ok(())
2322            }
2323            TableFactor::Derived {
2324                lateral,
2325                subquery,
2326                alias,
2327                sample,
2328            } => {
2329                if *lateral {
2330                    write!(f, "LATERAL ")?;
2331                }
2332                f.write_str("(")?;
2333                NewLine.fmt(f)?;
2334                Indent(subquery).fmt(f)?;
2335                NewLine.fmt(f)?;
2336                f.write_str(")")?;
2337                if let Some(alias) = alias {
2338                    write!(f, " {alias}")?;
2339                }
2340                if let Some(TableSampleKind::AfterTableAlias(sample)) = sample {
2341                    write!(f, " {sample}")?;
2342                }
2343                Ok(())
2344            }
2345            TableFactor::Function {
2346                lateral,
2347                name,
2348                args,
2349                with_ordinality,
2350                alias,
2351            } => {
2352                if *lateral {
2353                    write!(f, "LATERAL ")?;
2354                }
2355                write!(f, "{name}")?;
2356                write!(f, "({})", display_comma_separated(args))?;
2357                if *with_ordinality {
2358                    write!(f, " WITH ORDINALITY")?;
2359                }
2360                if let Some(alias) = alias {
2361                    write!(f, " {alias}")?;
2362                }
2363                Ok(())
2364            }
2365            TableFactor::TableFunction { expr, alias } => {
2366                write!(f, "TABLE({expr})")?;
2367                if let Some(alias) = alias {
2368                    write!(f, " {alias}")?;
2369                }
2370                Ok(())
2371            }
2372            TableFactor::UNNEST {
2373                alias,
2374                array_exprs,
2375                with_offset,
2376                with_offset_alias,
2377                with_ordinality,
2378            } => {
2379                write!(f, "UNNEST({})", display_comma_separated(array_exprs))?;
2380
2381                if *with_ordinality {
2382                    write!(f, " WITH ORDINALITY")?;
2383                }
2384
2385                if let Some(alias) = alias {
2386                    write!(f, " {alias}")?;
2387                }
2388                if *with_offset {
2389                    write!(f, " WITH OFFSET")?;
2390                }
2391                if let Some(alias) = with_offset_alias {
2392                    write!(f, " {alias}")?;
2393                }
2394                Ok(())
2395            }
2396            TableFactor::JsonTable {
2397                json_expr,
2398                json_path,
2399                columns,
2400                alias,
2401            } => {
2402                write!(
2403                    f,
2404                    "JSON_TABLE({json_expr}, {json_path} COLUMNS({columns}))",
2405                    columns = display_comma_separated(columns)
2406                )?;
2407                if let Some(alias) = alias {
2408                    write!(f, " {alias}")?;
2409                }
2410                Ok(())
2411            }
2412            TableFactor::OpenJsonTable {
2413                json_expr,
2414                json_path,
2415                columns,
2416                alias,
2417            } => {
2418                write!(f, "OPENJSON({json_expr}")?;
2419                if let Some(json_path) = json_path {
2420                    write!(f, ", {json_path}")?;
2421                }
2422                write!(f, ")")?;
2423                if !columns.is_empty() {
2424                    write!(f, " WITH ({})", display_comma_separated(columns))?;
2425                }
2426                if let Some(alias) = alias {
2427                    write!(f, " {alias}")?;
2428                }
2429                Ok(())
2430            }
2431            TableFactor::NestedJoin {
2432                table_with_joins,
2433                alias,
2434            } => {
2435                write!(f, "({table_with_joins})")?;
2436                if let Some(alias) = alias {
2437                    write!(f, " {alias}")?;
2438                }
2439                Ok(())
2440            }
2441            TableFactor::Pivot {
2442                table,
2443                aggregate_functions,
2444                value_column,
2445                value_source,
2446                default_on_null,
2447                alias,
2448            } => {
2449                write!(
2450                    f,
2451                    "{table} PIVOT({} FOR ",
2452                    display_comma_separated(aggregate_functions),
2453                )?;
2454                if value_column.len() == 1 {
2455                    write!(f, "{}", value_column[0])?;
2456                } else {
2457                    write!(f, "({})", display_comma_separated(value_column))?;
2458                }
2459                write!(f, " IN ({value_source})")?;
2460                if let Some(expr) = default_on_null {
2461                    write!(f, " DEFAULT ON NULL ({expr})")?;
2462                }
2463                write!(f, ")")?;
2464                if let Some(alias) = alias {
2465                    write!(f, " {alias}")?;
2466                }
2467                Ok(())
2468            }
2469            TableFactor::Unpivot {
2470                table,
2471                null_inclusion,
2472                value,
2473                name,
2474                columns,
2475                alias,
2476            } => {
2477                write!(f, "{table} UNPIVOT")?;
2478                if let Some(null_inclusion) = null_inclusion {
2479                    write!(f, " {null_inclusion} ")?;
2480                }
2481                write!(
2482                    f,
2483                    "({} FOR {} IN ({}))",
2484                    value,
2485                    name,
2486                    display_comma_separated(columns)
2487                )?;
2488                if let Some(alias) = alias {
2489                    write!(f, " {alias}")?;
2490                }
2491                Ok(())
2492            }
2493            TableFactor::UnpivotExpr {
2494                expression,
2495                value_alias,
2496                attribute_alias,
2497            } => {
2498                write!(f, "UNPIVOT {expression} AS {value_alias}")?;
2499                if let Some(attribute_alias) = attribute_alias {
2500                    write!(f, " AT {attribute_alias}")?;
2501                }
2502                Ok(())
2503            }
2504            TableFactor::MatchRecognize {
2505                table,
2506                partition_by,
2507                order_by,
2508                measures,
2509                rows_per_match,
2510                after_match_skip,
2511                pattern,
2512                symbols,
2513                alias,
2514            } => {
2515                write!(f, "{table} MATCH_RECOGNIZE(")?;
2516                if !partition_by.is_empty() {
2517                    write!(f, "PARTITION BY {} ", display_comma_separated(partition_by))?;
2518                }
2519                if !order_by.is_empty() {
2520                    write!(f, "ORDER BY {} ", display_comma_separated(order_by))?;
2521                }
2522                if !measures.is_empty() {
2523                    write!(f, "MEASURES {} ", display_comma_separated(measures))?;
2524                }
2525                if let Some(rows_per_match) = rows_per_match {
2526                    write!(f, "{rows_per_match} ")?;
2527                }
2528                if let Some(after_match_skip) = after_match_skip {
2529                    write!(f, "{after_match_skip} ")?;
2530                }
2531                write!(f, "PATTERN ({pattern}) ")?;
2532                write!(f, "DEFINE {})", display_comma_separated(symbols))?;
2533                if let Some(alias) = alias {
2534                    write!(f, " {alias}")?;
2535                }
2536                Ok(())
2537            }
2538            TableFactor::XmlTable {
2539                row_expression,
2540                passing,
2541                columns,
2542                alias,
2543                namespaces,
2544            } => {
2545                write!(f, "XMLTABLE(")?;
2546                if !namespaces.is_empty() {
2547                    write!(
2548                        f,
2549                        "XMLNAMESPACES({}), ",
2550                        display_comma_separated(namespaces)
2551                    )?;
2552                }
2553                write!(
2554                    f,
2555                    "{row_expression}{passing} COLUMNS {columns})",
2556                    columns = display_comma_separated(columns)
2557                )?;
2558                if let Some(alias) = alias {
2559                    write!(f, " {alias}")?;
2560                }
2561                Ok(())
2562            }
2563            TableFactor::SemanticView {
2564                name,
2565                dimensions,
2566                metrics,
2567                facts,
2568                where_clause,
2569                alias,
2570            } => {
2571                write!(f, "SEMANTIC_VIEW({name}")?;
2572
2573                if !dimensions.is_empty() {
2574                    write!(f, " DIMENSIONS {}", display_comma_separated(dimensions))?;
2575                }
2576
2577                if !metrics.is_empty() {
2578                    write!(f, " METRICS {}", display_comma_separated(metrics))?;
2579                }
2580
2581                if !facts.is_empty() {
2582                    write!(f, " FACTS {}", display_comma_separated(facts))?;
2583                }
2584
2585                if let Some(where_clause) = where_clause {
2586                    write!(f, " WHERE {where_clause}")?;
2587                }
2588
2589                write!(f, ")")?;
2590
2591                if let Some(alias) = alias {
2592                    write!(f, " {alias}")?;
2593                }
2594
2595                Ok(())
2596            }
2597        }
2598    }
2599}
2600
2601#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2602#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2603#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2604/// An alias for a table reference, optionally including an explicit `AS` and column names.
2605pub struct TableAlias {
2606    /// Tells whether the alias was introduced with an explicit, preceding "AS"
2607    /// keyword, e.g. `AS name`. Typically, the keyword is preceding the name
2608    /// (e.g. `.. FROM table AS t ..`).
2609    pub explicit: bool,
2610    /// Alias identifier for the table.
2611    pub name: Ident,
2612    /// Optional column aliases declared in parentheses after the table alias.
2613    pub columns: Vec<TableAliasColumnDef>,
2614    /// Optional PartiQL index alias declared with `AT`. For example:
2615    /// ```sql
2616    /// SELECT element, index FROM bar AS b, b.data.scalar_array AS element AT index
2617    /// ```
2618    /// See: <https://docs.aws.amazon.com/redshift/latest/dg/query-super.html>
2619    pub at: Option<Ident>,
2620}
2621
2622impl fmt::Display for TableAlias {
2623    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2624        write!(f, "{}{}", if self.explicit { "AS " } else { "" }, self.name)?;
2625        if !self.columns.is_empty() {
2626            write!(f, " ({})", display_comma_separated(&self.columns))?;
2627        }
2628        if let Some(at) = &self.at {
2629            write!(f, " AT {at}")?;
2630        }
2631        Ok(())
2632    }
2633}
2634
2635/// SQL column definition in a table expression alias.
2636/// Most of the time, the data type is not specified.
2637/// But some table-valued functions do require specifying the data type.
2638///
2639/// See <https://www.postgresql.org/docs/17/queries-table-expressions.html#QUERIES-TABLEFUNCTIONS>
2640#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2641#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2642#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2643pub struct TableAliasColumnDef {
2644    /// Column name alias
2645    pub name: Ident,
2646    /// Some table-valued functions require specifying the data type in the alias.
2647    pub data_type: Option<DataType>,
2648}
2649
2650impl TableAliasColumnDef {
2651    /// Create a new table alias column definition with only a name and no type
2652    pub fn from_name<S: Into<String>>(name: S) -> Self {
2653        TableAliasColumnDef {
2654            name: Ident::new(name),
2655            data_type: None,
2656        }
2657    }
2658}
2659
2660impl fmt::Display for TableAliasColumnDef {
2661    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2662        write!(f, "{}", self.name)?;
2663        if let Some(ref data_type) = self.data_type {
2664            write!(f, " {data_type}")?;
2665        }
2666        Ok(())
2667    }
2668}
2669
2670#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2671#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2672#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2673/// Specifies a table version selection, e.g. `FOR SYSTEM_TIME AS OF` or `AT(...)`.
2674pub enum TableVersion {
2675    /// When the table version is defined using `FOR SYSTEM_TIME AS OF`.
2676    /// For example: `SELECT * FROM tbl FOR SYSTEM_TIME AS OF TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR)`
2677    ForSystemTimeAsOf(Expr),
2678    /// When the table version is defined using `TIMESTAMP AS OF`.
2679    /// Databricks supports this syntax.
2680    /// For example: `SELECT * FROM tbl TIMESTAMP AS OF CURRENT_TIMESTAMP() - INTERVAL 1 HOUR`
2681    TimestampAsOf(Expr),
2682    /// When the table version is defined using `VERSION AS OF`.
2683    /// Databricks supports this syntax.
2684    /// For example: `SELECT * FROM tbl VERSION AS OF 2`
2685    VersionAsOf(Expr),
2686    /// When the table version is defined using a function.
2687    /// For example: `SELECT * FROM tbl AT(TIMESTAMP => '2020-08-14 09:30:00')`
2688    Function(Expr),
2689    /// Snowflake `CHANGES` clause for change tracking queries.
2690    /// For example:
2691    /// ```sql
2692    /// SELECT * FROM t
2693    ///   CHANGES(INFORMATION => DEFAULT)
2694    ///   AT(TIMESTAMP => TO_TIMESTAMP_TZ('...'))
2695    ///   END(TIMESTAMP => TO_TIMESTAMP_TZ('...'))
2696    /// ```
2697    /// <https://docs.snowflake.com/en/sql-reference/constructs/changes>
2698    Changes {
2699        /// The `CHANGES(INFORMATION => ...)` function-call expression.
2700        changes: Expr,
2701        /// The `AT(TIMESTAMP => ...)` function-call expression.
2702        at: Expr,
2703        /// The optional `END(TIMESTAMP => ...)` function-call expression.
2704        end: Option<Expr>,
2705    },
2706}
2707
2708impl Display for TableVersion {
2709    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2710        match self {
2711            TableVersion::ForSystemTimeAsOf(e) => write!(f, "FOR SYSTEM_TIME AS OF {e}")?,
2712            TableVersion::TimestampAsOf(e) => write!(f, "TIMESTAMP AS OF {e}")?,
2713            TableVersion::VersionAsOf(e) => write!(f, "VERSION AS OF {e}")?,
2714            TableVersion::Function(func) => write!(f, "{func}")?,
2715            TableVersion::Changes { changes, at, end } => {
2716                write!(f, "{changes} {at}")?;
2717                if let Some(end) = end {
2718                    write!(f, " {end}")?;
2719                }
2720            }
2721        }
2722        Ok(())
2723    }
2724}
2725
2726#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2727#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2728#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2729/// A single `JOIN` clause including relation and join operator/options.
2730pub struct Join {
2731    /// The joined table factor (table reference or derived table).
2732    pub relation: TableFactor,
2733    /// ClickHouse supports the optional `GLOBAL` keyword before the join operator.
2734    /// See [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/select/join)
2735    pub global: bool,
2736    /// The join operator and its constraint (INNER/LEFT/RIGHT/CROSS/ASOF/etc.).
2737    pub join_operator: JoinOperator,
2738}
2739
2740impl fmt::Display for Join {
2741    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2742        fn prefix(constraint: &JoinConstraint) -> &'static str {
2743            match constraint {
2744                JoinConstraint::Natural => "NATURAL ",
2745                _ => "",
2746            }
2747        }
2748        fn suffix(constraint: &'_ JoinConstraint) -> impl fmt::Display + '_ {
2749            struct Suffix<'a>(&'a JoinConstraint);
2750            impl fmt::Display for Suffix<'_> {
2751                fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2752                    match self.0 {
2753                        JoinConstraint::On(expr) => write!(f, " ON {expr}"),
2754                        JoinConstraint::Using(attrs) => {
2755                            write!(f, " USING({})", display_comma_separated(attrs))
2756                        }
2757                        JoinConstraint::UsingAlias(columns, alias) => {
2758                            write!(f, " USING({}) AS {alias}", display_comma_separated(columns))
2759                        }
2760                        _ => Ok(()),
2761                    }
2762                }
2763            }
2764            Suffix(constraint)
2765        }
2766        if self.global {
2767            write!(f, "GLOBAL ")?;
2768        }
2769
2770        match &self.join_operator {
2771            JoinOperator::Join(constraint) => f.write_fmt(format_args!(
2772                "{}JOIN {}{}",
2773                prefix(constraint),
2774                self.relation,
2775                suffix(constraint)
2776            )),
2777            JoinOperator::Inner(constraint) => f.write_fmt(format_args!(
2778                "{}INNER JOIN {}{}",
2779                prefix(constraint),
2780                self.relation,
2781                suffix(constraint)
2782            )),
2783            JoinOperator::Left(constraint) => f.write_fmt(format_args!(
2784                "{}LEFT JOIN {}{}",
2785                prefix(constraint),
2786                self.relation,
2787                suffix(constraint)
2788            )),
2789            JoinOperator::LeftOuter(constraint) => f.write_fmt(format_args!(
2790                "{}LEFT OUTER JOIN {}{}",
2791                prefix(constraint),
2792                self.relation,
2793                suffix(constraint)
2794            )),
2795            JoinOperator::Right(constraint) => f.write_fmt(format_args!(
2796                "{}RIGHT JOIN {}{}",
2797                prefix(constraint),
2798                self.relation,
2799                suffix(constraint)
2800            )),
2801            JoinOperator::RightOuter(constraint) => f.write_fmt(format_args!(
2802                "{}RIGHT OUTER JOIN {}{}",
2803                prefix(constraint),
2804                self.relation,
2805                suffix(constraint)
2806            )),
2807            JoinOperator::FullOuter(constraint) => f.write_fmt(format_args!(
2808                "{}FULL JOIN {}{}",
2809                prefix(constraint),
2810                self.relation,
2811                suffix(constraint)
2812            )),
2813            JoinOperator::CrossJoin(constraint) => f.write_fmt(format_args!(
2814                "CROSS JOIN {}{}",
2815                self.relation,
2816                suffix(constraint)
2817            )),
2818            JoinOperator::Semi(constraint) => f.write_fmt(format_args!(
2819                "{}SEMI JOIN {}{}",
2820                prefix(constraint),
2821                self.relation,
2822                suffix(constraint)
2823            )),
2824            JoinOperator::LeftSemi(constraint) => f.write_fmt(format_args!(
2825                "{}LEFT SEMI JOIN {}{}",
2826                prefix(constraint),
2827                self.relation,
2828                suffix(constraint)
2829            )),
2830            JoinOperator::RightSemi(constraint) => f.write_fmt(format_args!(
2831                "{}RIGHT SEMI JOIN {}{}",
2832                prefix(constraint),
2833                self.relation,
2834                suffix(constraint)
2835            )),
2836            JoinOperator::Anti(constraint) => f.write_fmt(format_args!(
2837                "{}ANTI JOIN {}{}",
2838                prefix(constraint),
2839                self.relation,
2840                suffix(constraint)
2841            )),
2842            JoinOperator::LeftAnti(constraint) => f.write_fmt(format_args!(
2843                "{}LEFT ANTI JOIN {}{}",
2844                prefix(constraint),
2845                self.relation,
2846                suffix(constraint)
2847            )),
2848            JoinOperator::RightAnti(constraint) => f.write_fmt(format_args!(
2849                "{}RIGHT ANTI JOIN {}{}",
2850                prefix(constraint),
2851                self.relation,
2852                suffix(constraint)
2853            )),
2854            JoinOperator::CrossApply => f.write_fmt(format_args!("CROSS APPLY {}", self.relation)),
2855            JoinOperator::OuterApply => f.write_fmt(format_args!("OUTER APPLY {}", self.relation)),
2856            JoinOperator::AsOf {
2857                match_condition,
2858                constraint,
2859            } => f.write_fmt(format_args!(
2860                "ASOF JOIN {} MATCH_CONDITION ({match_condition}){}",
2861                self.relation,
2862                suffix(constraint)
2863            )),
2864            JoinOperator::StraightJoin(constraint) => f.write_fmt(format_args!(
2865                "STRAIGHT_JOIN {}{}",
2866                self.relation,
2867                suffix(constraint)
2868            )),
2869            JoinOperator::ArrayJoin => f.write_fmt(format_args!("ARRAY JOIN {}", self.relation)),
2870            JoinOperator::LeftArrayJoin => {
2871                f.write_fmt(format_args!("LEFT ARRAY JOIN {}", self.relation))
2872            }
2873            JoinOperator::InnerArrayJoin => {
2874                f.write_fmt(format_args!("INNER ARRAY JOIN {}", self.relation))
2875            }
2876        }
2877    }
2878}
2879
2880#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2881#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2882#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2883/// The operator used for joining two tables, e.g. `INNER`, `LEFT`, `CROSS`, `ASOF`, etc.
2884pub enum JoinOperator {
2885    /// Generic `JOIN` with an optional constraint.
2886    Join(JoinConstraint),
2887    /// `INNER JOIN` with an optional constraint.
2888    Inner(JoinConstraint),
2889    /// `LEFT JOIN` with an optional constraint.
2890    Left(JoinConstraint),
2891    /// `LEFT OUTER JOIN` with an optional constraint.
2892    LeftOuter(JoinConstraint),
2893    /// `RIGHT JOIN` with an optional constraint.
2894    Right(JoinConstraint),
2895    /// `RIGHT OUTER JOIN` with an optional constraint.
2896    RightOuter(JoinConstraint),
2897    /// `FULL OUTER JOIN` with an optional constraint.
2898    FullOuter(JoinConstraint),
2899    /// `CROSS JOIN` (constraint usage is non-standard).
2900    CrossJoin(JoinConstraint),
2901    /// `SEMI JOIN` (non-standard)
2902    Semi(JoinConstraint),
2903    /// `LEFT SEMI JOIN` (non-standard)
2904    LeftSemi(JoinConstraint),
2905    /// `RIGHT SEMI JOIN` (non-standard)
2906    RightSemi(JoinConstraint),
2907    /// `ANTI JOIN` (non-standard)
2908    Anti(JoinConstraint),
2909    /// `LEFT ANTI JOIN` (non-standard)
2910    LeftAnti(JoinConstraint),
2911    /// `RIGHT ANTI JOIN` (non-standard)
2912    RightAnti(JoinConstraint),
2913    /// `CROSS APPLY` (non-standard)
2914    CrossApply,
2915    /// `OUTER APPLY` (non-standard)
2916    OuterApply,
2917    /// `ASOF` joins are used for joining time-series tables whose timestamp columns do not match exactly.
2918    ///
2919    /// See <https://docs.snowflake.com/en/sql-reference/constructs/asof-join>.
2920    AsOf {
2921        /// Condition used to match records in the `ASOF` join.
2922        match_condition: Expr,
2923        /// Additional constraint applied to the `ASOF` join.
2924        constraint: JoinConstraint,
2925    },
2926    /// `STRAIGHT_JOIN` (MySQL non-standard behavior)
2927    ///
2928    /// See <https://dev.mysql.com/doc/refman/8.4/en/join.html>.
2929    StraightJoin(JoinConstraint),
2930    /// ClickHouse: `ARRAY JOIN` for unnesting arrays inline.
2931    ///
2932    /// See <https://clickhouse.com/docs/en/sql-reference/statements/select/array-join>.
2933    ArrayJoin,
2934    /// ClickHouse: `LEFT ARRAY JOIN` for unnesting arrays inline (preserves rows with empty arrays).
2935    LeftArrayJoin,
2936    /// ClickHouse: `INNER ARRAY JOIN` for unnesting arrays inline (filters rows with empty arrays).
2937    InnerArrayJoin,
2938}
2939
2940#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2941#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2942#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2943/// Represents how two tables are constrained in a join: `ON`, `USING`, `NATURAL`, or none.
2944pub enum JoinConstraint {
2945    /// `ON <expr>` join condition.
2946    On(Expr),
2947    /// `USING(...)` list of column names.
2948    Using(Vec<ObjectName>),
2949    /// `USING(...) AS alias` list of column names with an alias for the joined columns.
2950    UsingAlias(Vec<ObjectName>, Ident),
2951    /// `NATURAL` join (columns matched automatically).
2952    Natural,
2953    /// No constraint specified (e.g. `CROSS JOIN`).
2954    None,
2955}
2956
2957#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2958#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2959#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2960/// The kind of `ORDER BY` clause: either `ALL` with modifiers or a list of expressions.
2961pub enum OrderByKind {
2962    /// `GROUP BY ALL`/`ORDER BY ALL` syntax with optional modifiers.
2963    ///
2964    /// [DuckDB]:  <https://duckdb.org/docs/sql/query_syntax/orderby>
2965    /// [ClickHouse]: <https://clickhouse.com/docs/en/sql-reference/statements/select/order-by>
2966    All(OrderByOptions),
2967
2968    /// A standard list of ordering expressions.
2969    Expressions(Vec<OrderByExpr>),
2970}
2971
2972#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2973#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2974#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2975#[cfg_attr(feature = "visitor", visit(with = "visit_order_by"))]
2976/// Represents an `ORDER BY` clause with its kind and optional `INTERPOLATE`.
2977pub struct OrderBy {
2978    /// The kind of ordering (expressions or `ALL`).
2979    pub kind: OrderByKind,
2980
2981    /// Optional `INTERPOLATE` clause (ClickHouse extension).
2982    pub interpolate: Option<Interpolate>,
2983}
2984
2985impl fmt::Display for OrderBy {
2986    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2987        write!(f, "ORDER BY")?;
2988        match &self.kind {
2989            OrderByKind::Expressions(exprs) => {
2990                write!(f, " {}", display_comma_separated(exprs))?;
2991            }
2992            OrderByKind::All(all) => {
2993                write!(f, " ALL{all}")?;
2994            }
2995        }
2996
2997        if let Some(ref interpolate) = self.interpolate {
2998            match &interpolate.exprs {
2999                Some(exprs) => write!(f, " INTERPOLATE ({})", display_comma_separated(exprs))?,
3000                None => write!(f, " INTERPOLATE")?,
3001            }
3002        }
3003
3004        Ok(())
3005    }
3006}
3007
3008/// An `ORDER BY` expression
3009#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3010#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3011#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3012#[cfg_attr(feature = "visitor", visit(with = "visit_order_by_expr"))]
3013pub struct OrderByExpr {
3014    /// The expression to order by.
3015    pub expr: Expr,
3016    /// Ordering options such as `ASC`/`DESC`/`USING <operator>` and `NULLS` behavior.
3017    pub options: OrderByOptions,
3018    /// Optional `WITH FILL` clause (ClickHouse extension) which specifies how to fill gaps.
3019    pub with_fill: Option<WithFill>,
3020}
3021
3022impl From<Ident> for OrderByExpr {
3023    fn from(ident: Ident) -> Self {
3024        OrderByExpr {
3025            expr: Expr::Identifier(ident),
3026            options: OrderByOptions::default(),
3027            with_fill: None,
3028        }
3029    }
3030}
3031
3032impl fmt::Display for OrderByExpr {
3033    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3034        write!(f, "{}", self.expr)?;
3035        self.fmt_sort_modifiers(f)
3036    }
3037}
3038
3039impl OrderByExpr {
3040    /// Writes the modifiers that follow the sort expression (`ASC`/`DESC`, `NULLS`, `WITH FILL`).
3041    pub(crate) fn fmt_sort_modifiers(&self, f: &mut fmt::Formatter) -> fmt::Result {
3042        write!(f, "{}", self.options)?;
3043        if let Some(with_fill) = &self.with_fill {
3044            write!(f, " {with_fill}")?
3045        }
3046        Ok(())
3047    }
3048}
3049
3050/// ClickHouse `WITH FILL` modifier for `ORDER BY` clause.
3051/// Supported by [ClickHouse syntax]
3052///
3053/// [ClickHouse syntax]: <https://clickhouse.com/docs/en/sql-reference/statements/select/order-by#order-by-expr-with-fill-modifier>
3054#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3055#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3056#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3057/// `WITH FILL` options for ClickHouse `ORDER BY` expressions.
3058pub struct WithFill {
3059    /// Optional lower bound expression for the fill range (`FROM <expr>`).
3060    pub from: Option<Expr>,
3061    /// Optional upper bound expression for the fill range (`TO <expr>`).
3062    pub to: Option<Expr>,
3063    /// Optional step expression specifying interpolation step (`STEP <expr>`).
3064    pub step: Option<Expr>,
3065}
3066
3067impl fmt::Display for WithFill {
3068    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3069        write!(f, "WITH FILL")?;
3070        if let Some(ref from) = self.from {
3071            write!(f, " FROM {from}")?;
3072        }
3073        if let Some(ref to) = self.to {
3074            write!(f, " TO {to}")?;
3075        }
3076        if let Some(ref step) = self.step {
3077            write!(f, " STEP {step}")?;
3078        }
3079        Ok(())
3080    }
3081}
3082
3083/// ClickHouse `INTERPOLATE` clause for use in `ORDER BY` clause when using `WITH FILL` modifier.
3084/// Supported by [ClickHouse syntax]
3085///
3086/// [ClickHouse syntax]: <https://clickhouse.com/docs/en/sql-reference/statements/select/order-by#order-by-expr-with-fill-modifier>
3087#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3088#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3089#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3090/// An expression used by `WITH FILL`/`INTERPOLATE` to specify interpolation for a column.
3091pub struct InterpolateExpr {
3092    /// The column to interpolate.
3093    pub column: Ident,
3094    /// Optional `AS <expr>` expression specifying how to compute interpolated values.
3095    pub expr: Option<Expr>,
3096}
3097
3098#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3099#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3100#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3101/// `INTERPOLATE` clause used with ClickHouse `WITH FILL` to compute missing values.
3102pub struct Interpolate {
3103    /// Optional list of interpolation expressions.
3104    pub exprs: Option<Vec<InterpolateExpr>>,
3105}
3106
3107impl fmt::Display for InterpolateExpr {
3108    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3109        write!(f, "{}", self.column)?;
3110        if let Some(ref expr) = self.expr {
3111            write!(f, " AS {expr}")?;
3112        }
3113        Ok(())
3114    }
3115}
3116
3117/// The sort order for an `ORDER BY` expression.
3118///
3119/// See PostgreSQL `USING` operator:
3120/// <https://www.postgresql.org/docs/current/sql-select.html>
3121#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3122#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3123#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3124pub enum OrderBySort {
3125    /// `ASC`
3126    Asc,
3127    /// `DESC`
3128    Desc,
3129    /// PostgreSQL `USING <operator>` ordering.
3130    ///
3131    /// See <https://www.postgresql.org/docs/current/sql-select.html>
3132    Using(ObjectName),
3133}
3134
3135#[derive(Default, Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3136#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3137#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3138/// Options for an `ORDER BY` expression.
3139pub struct OrderByOptions {
3140    /// Optional sort order: `ASC`, `DESC`, or `USING <operator>`.
3141    pub sort: Option<OrderBySort>,
3142    /// Optional `NULLS FIRST` (`Some(true)`) or `NULLS LAST` (`Some(false)`).
3143    pub nulls_first: Option<bool>,
3144}
3145
3146impl fmt::Display for OrderByOptions {
3147    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3148        match &self.sort {
3149            Some(OrderBySort::Asc) => write!(f, " ASC")?,
3150            Some(OrderBySort::Desc) => write!(f, " DESC")?,
3151            Some(OrderBySort::Using(op)) => {
3152                if op.0.len() > 1 {
3153                    write!(f, " USING OPERATOR({op})")?;
3154                } else {
3155                    write!(f, " USING {op}")?;
3156                }
3157            }
3158            None => (),
3159        }
3160        match self.nulls_first {
3161            Some(true) => write!(f, " NULLS FIRST")?,
3162            Some(false) => write!(f, " NULLS LAST")?,
3163            None => (),
3164        }
3165        Ok(())
3166    }
3167}
3168
3169#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3170#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3171#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3172/// Represents the different syntactic forms of `LIMIT` clauses.
3173pub enum LimitClause {
3174    /// Standard SQL `LIMIT` syntax (optionally `BY` and `OFFSET`).
3175    ///
3176    /// `LIMIT <limit> [BY <expr>,<expr>,...] [OFFSET <offset>]`
3177    LimitOffset {
3178        /// `LIMIT { <N> | ALL }` expression.
3179        limit: Option<Expr>,
3180        /// Optional `OFFSET` expression with optional `ROW(S)` keyword.
3181        offset: Option<Offset>,
3182        /// Optional `BY { <expr>,... }` list used by some dialects (ClickHouse).
3183        limit_by: Vec<Expr>,
3184    },
3185    /// MySQL-specific syntax: `LIMIT <offset>, <limit>` (order reversed).
3186    OffsetCommaLimit {
3187        /// The offset expression.
3188        offset: Expr,
3189        /// The limit expression.
3190        limit: Expr,
3191    },
3192}
3193
3194impl fmt::Display for LimitClause {
3195    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3196        match self {
3197            LimitClause::LimitOffset {
3198                limit,
3199                limit_by,
3200                offset,
3201            } => {
3202                if let Some(ref limit) = limit {
3203                    write!(f, " LIMIT {limit}")?;
3204                }
3205                if let Some(ref offset) = offset {
3206                    write!(f, " {offset}")?;
3207                }
3208                if !limit_by.is_empty() {
3209                    debug_assert!(limit.is_some());
3210                    write!(f, " BY {}", display_separated(limit_by, ", "))?;
3211                }
3212                Ok(())
3213            }
3214            LimitClause::OffsetCommaLimit { offset, limit } => {
3215                write!(f, " LIMIT {offset}, {limit}")
3216            }
3217        }
3218    }
3219}
3220
3221#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3222#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3223#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3224/// `OFFSET` clause consisting of a value and a rows specifier.
3225pub struct Offset {
3226    /// The numeric expression following `OFFSET`.
3227    pub value: Expr,
3228    /// Whether the offset uses `ROW`/`ROWS` or omits it.
3229    pub rows: OffsetRows,
3230}
3231
3232impl fmt::Display for Offset {
3233    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3234        write!(f, "OFFSET {}{}", self.value, self.rows)
3235    }
3236}
3237
3238/// Stores the keyword after `OFFSET <number>`
3239#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3240#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3241#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3242pub enum OffsetRows {
3243    /// Omitting `ROW`/`ROWS` entirely (non-standard MySQL quirk).
3244    None,
3245    /// `ROW` keyword present.
3246    Row,
3247    /// `ROWS` keyword present.
3248    Rows,
3249}
3250
3251impl fmt::Display for OffsetRows {
3252    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3253        match self {
3254            OffsetRows::None => Ok(()),
3255            OffsetRows::Row => write!(f, " ROW"),
3256            OffsetRows::Rows => write!(f, " ROWS"),
3257        }
3258    }
3259}
3260
3261/// Pipe syntax, first introduced in Google BigQuery.
3262/// Example:
3263///
3264/// ```sql
3265/// FROM Produce
3266/// |> WHERE sales > 0
3267/// |> AGGREGATE SUM(sales) AS total_sales, COUNT(*) AS num_sales
3268///    GROUP BY item;
3269/// ```
3270///
3271/// See <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#pipe_syntax>
3272#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3273#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3274#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3275pub enum PipeOperator {
3276    /// Limits the number of rows to return in a query, with an optional OFFSET clause to skip over rows.
3277    ///
3278    /// Syntax: `|> LIMIT <n> [OFFSET <m>]`
3279    ///
3280    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#limit_pipe_operator>
3281    Limit {
3282        /// The expression specifying the number of rows to return.
3283        expr: Expr,
3284        /// Optional offset expression provided inline with `LIMIT`.
3285        offset: Option<Expr>,
3286    },
3287    /// Filters the results of the input table.
3288    ///
3289    /// Syntax: `|> WHERE <condition>`
3290    ///
3291    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#where_pipe_operator>
3292    Where {
3293        /// The filter expression.
3294        expr: Expr,
3295    },
3296    /// `ORDER BY <expr> [ASC|DESC], ...`
3297    OrderBy {
3298        /// The ordering expressions.
3299        exprs: Vec<OrderByExpr>,
3300    },
3301    /// Produces a new table with the listed columns, similar to the outermost SELECT clause in a table subquery in standard syntax.
3302    ///
3303    /// Syntax `|> SELECT <expr> [[AS] alias], ...`
3304    ///
3305    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#select_pipe_operator>
3306    Select {
3307        /// The select items to produce.
3308        exprs: Vec<SelectItem>,
3309    },
3310    /// Propagates the existing table and adds computed columns, similar to SELECT *, new_column in standard syntax.
3311    ///
3312    /// Syntax: `|> EXTEND <expr> [[AS] alias], ...`
3313    ///
3314    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#extend_pipe_operator>
3315    Extend {
3316        /// Expressions defining added columns.
3317        exprs: Vec<SelectItem>,
3318    },
3319    /// Replaces the value of a column in the current table, similar to SELECT * REPLACE (expression AS column) in standard syntax.
3320    ///
3321    /// Syntax: `|> SET <column> = <expression>, ...`
3322    ///
3323    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#set_pipe_operator>
3324    Set {
3325        /// Assignments to apply (`column = expr`).
3326        assignments: Vec<Assignment>,
3327    },
3328    /// Removes listed columns from the current table, similar to SELECT * EXCEPT (column) in standard syntax.
3329    ///
3330    /// Syntax: `|> DROP <column>, ...`
3331    ///
3332    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#drop_pipe_operator>
3333    Drop {
3334        /// Columns to drop.
3335        columns: Vec<Ident>,
3336    },
3337    /// Introduces a table alias for the input table, similar to applying the AS alias clause on a table subquery in standard syntax.
3338    ///
3339    /// Syntax: `|> AS <alias>`
3340    ///
3341    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#as_pipe_operator>
3342    As {
3343        /// Alias to assign to the input table.
3344        alias: Ident,
3345    },
3346    /// Performs aggregation on data across grouped rows or an entire table.
3347    ///
3348    /// Syntax: `|> AGGREGATE <agg_expr> [[AS] alias], ...`
3349    ///
3350    /// Syntax:
3351    /// ```norust
3352    /// |> AGGREGATE [<agg_expr> [[AS] alias], ...]
3353    /// GROUP BY <grouping_expr> [AS alias], ...
3354    /// ```
3355    ///
3356    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#aggregate_pipe_operator>
3357    Aggregate {
3358        /// Expressions computed for each row prior to grouping.
3359        full_table_exprs: Vec<ExprWithAliasAndOrderBy>,
3360        /// Grouping expressions for aggregation.
3361        group_by_expr: Vec<ExprWithAliasAndOrderBy>,
3362    },
3363    /// Selects a random sample of rows from the input table.
3364    /// Syntax: `|> TABLESAMPLE SYSTEM (10 PERCENT)
3365    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#tablesample_pipe_operator>
3366    TableSample {
3367        /// Sampling clause describing the sample.
3368        sample: Box<TableSample>,
3369    },
3370    /// Renames columns in the input table.
3371    ///
3372    /// Syntax: `|> RENAME old_name AS new_name, ...`
3373    ///
3374    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#rename_pipe_operator>
3375    Rename {
3376        /// Mappings of old to new identifiers.
3377        mappings: Vec<IdentWithAlias>,
3378    },
3379    /// Combines the input table with one or more tables using UNION.
3380    ///
3381    /// Syntax: `|> UNION [ALL|DISTINCT] (<query>), (<query>), ...`
3382    ///
3383    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#union_pipe_operator>
3384    Union {
3385        /// Set quantifier (`ALL` or `DISTINCT`).
3386        set_quantifier: SetQuantifier,
3387        /// The queries to combine with `UNION`.
3388        queries: Vec<Query>,
3389    },
3390    /// Returns only the rows that are present in both the input table and the specified tables.
3391    ///
3392    /// Syntax: `|> INTERSECT [DISTINCT] (<query>), (<query>), ...`
3393    ///
3394    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#intersect_pipe_operator>
3395    Intersect {
3396        /// Set quantifier for the `INTERSECT` operator.
3397        set_quantifier: SetQuantifier,
3398        /// The queries to intersect.
3399        queries: Vec<Query>,
3400    },
3401    /// Returns only the rows that are present in the input table but not in the specified tables.
3402    ///
3403    /// Syntax: `|> EXCEPT DISTINCT (<query>), (<query>), ...`
3404    ///
3405    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#except_pipe_operator>
3406    Except {
3407        /// Set quantifier for the `EXCEPT` operator.
3408        set_quantifier: SetQuantifier,
3409        /// The queries to exclude from the input set.
3410        queries: Vec<Query>,
3411    },
3412    /// Calls a table function or procedure that returns a table.
3413    ///
3414    /// Syntax: `|> CALL function_name(args) [AS alias]`
3415    ///
3416    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#call_pipe_operator>
3417    Call {
3418        /// The function or procedure to call which returns a table.
3419        function: Function,
3420        /// Optional alias for the result table.
3421        alias: Option<Ident>,
3422    },
3423    /// Pivots data from rows to columns.
3424    ///
3425    /// Syntax: `|> PIVOT(aggregate_function(column) FOR pivot_column IN (value1, value2, ...)) [AS alias]`
3426    ///
3427    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#pivot_pipe_operator>
3428    Pivot {
3429        /// Aggregate functions to compute during pivot.
3430        aggregate_functions: Vec<ExprWithAlias>,
3431        /// Column(s) that provide the pivot values.
3432        value_column: Vec<Ident>,
3433        /// The source of pivot values (literal list or subquery).
3434        value_source: PivotValueSource,
3435        /// Optional alias for the output.
3436        alias: Option<Ident>,
3437    },
3438    /// The `UNPIVOT` pipe operator transforms columns into rows.
3439    ///
3440    /// Syntax:
3441    /// ```sql
3442    /// |> UNPIVOT(value_column FOR name_column IN (column1, column2, ...)) [alias]
3443    /// ```
3444    ///
3445    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#unpivot_pipe_operator>
3446    Unpivot {
3447        /// Output column that will receive the unpivoted value.
3448        value_column: Ident,
3449        /// Column name holding the unpivoted column name.
3450        name_column: Ident,
3451        /// Columns to unpivot.
3452        unpivot_columns: Vec<Ident>,
3453        /// Optional alias for the unpivot result.
3454        alias: Option<Ident>,
3455    },
3456    /// Joins the input table with another table.
3457    ///
3458    /// Syntax: `|> [JOIN_TYPE] JOIN <table> [alias] ON <condition>` or `|> [JOIN_TYPE] JOIN <table> [alias] USING (<columns>)`
3459    ///
3460    /// See more at <https://cloud.google.com/bigquery/docs/reference/standard-sql/pipe-syntax#join_pipe_operator>
3461    Join(Join),
3462}
3463
3464impl fmt::Display for PipeOperator {
3465    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3466        match self {
3467            PipeOperator::Select { exprs } => {
3468                write!(f, "SELECT {}", display_comma_separated(exprs.as_slice()))
3469            }
3470            PipeOperator::Extend { exprs } => {
3471                write!(f, "EXTEND {}", display_comma_separated(exprs.as_slice()))
3472            }
3473            PipeOperator::Set { assignments } => {
3474                write!(f, "SET {}", display_comma_separated(assignments.as_slice()))
3475            }
3476            PipeOperator::Drop { columns } => {
3477                write!(f, "DROP {}", display_comma_separated(columns.as_slice()))
3478            }
3479            PipeOperator::As { alias } => {
3480                write!(f, "AS {alias}")
3481            }
3482            PipeOperator::Limit { expr, offset } => {
3483                write!(f, "LIMIT {expr}")?;
3484                if let Some(offset) = offset {
3485                    write!(f, " OFFSET {offset}")?;
3486                }
3487                Ok(())
3488            }
3489            PipeOperator::Aggregate {
3490                full_table_exprs,
3491                group_by_expr,
3492            } => {
3493                write!(f, "AGGREGATE")?;
3494                if !full_table_exprs.is_empty() {
3495                    write!(
3496                        f,
3497                        " {}",
3498                        display_comma_separated(full_table_exprs.as_slice())
3499                    )?;
3500                }
3501                if !group_by_expr.is_empty() {
3502                    write!(f, " GROUP BY {}", display_comma_separated(group_by_expr))?;
3503                }
3504                Ok(())
3505            }
3506
3507            PipeOperator::Where { expr } => {
3508                write!(f, "WHERE {expr}")
3509            }
3510            PipeOperator::OrderBy { exprs } => {
3511                write!(f, "ORDER BY {}", display_comma_separated(exprs.as_slice()))
3512            }
3513
3514            PipeOperator::TableSample { sample } => {
3515                write!(f, "{sample}")
3516            }
3517            PipeOperator::Rename { mappings } => {
3518                write!(f, "RENAME {}", display_comma_separated(mappings))
3519            }
3520            PipeOperator::Union {
3521                set_quantifier,
3522                queries,
3523            } => Self::fmt_set_operation(f, "UNION", set_quantifier, queries),
3524            PipeOperator::Intersect {
3525                set_quantifier,
3526                queries,
3527            } => Self::fmt_set_operation(f, "INTERSECT", set_quantifier, queries),
3528            PipeOperator::Except {
3529                set_quantifier,
3530                queries,
3531            } => Self::fmt_set_operation(f, "EXCEPT", set_quantifier, queries),
3532            PipeOperator::Call { function, alias } => {
3533                write!(f, "CALL {function}")?;
3534                Self::fmt_optional_alias(f, alias)
3535            }
3536            PipeOperator::Pivot {
3537                aggregate_functions,
3538                value_column,
3539                value_source,
3540                alias,
3541            } => {
3542                write!(
3543                    f,
3544                    "PIVOT({} FOR {} IN ({}))",
3545                    display_comma_separated(aggregate_functions),
3546                    Expr::CompoundIdentifier(value_column.to_vec()),
3547                    value_source
3548                )?;
3549                Self::fmt_optional_alias(f, alias)
3550            }
3551            PipeOperator::Unpivot {
3552                value_column,
3553                name_column,
3554                unpivot_columns,
3555                alias,
3556            } => {
3557                write!(
3558                    f,
3559                    "UNPIVOT({} FOR {} IN ({}))",
3560                    value_column,
3561                    name_column,
3562                    display_comma_separated(unpivot_columns)
3563                )?;
3564                Self::fmt_optional_alias(f, alias)
3565            }
3566            PipeOperator::Join(join) => write!(f, "{join}"),
3567        }
3568    }
3569}
3570
3571impl PipeOperator {
3572    /// Helper function to format optional alias for pipe operators
3573    fn fmt_optional_alias(f: &mut fmt::Formatter<'_>, alias: &Option<Ident>) -> fmt::Result {
3574        if let Some(alias) = alias {
3575            write!(f, " AS {alias}")?;
3576        }
3577        Ok(())
3578    }
3579
3580    /// Helper function to format set operations (UNION, INTERSECT, EXCEPT) with queries
3581    fn fmt_set_operation(
3582        f: &mut fmt::Formatter<'_>,
3583        operation: &str,
3584        set_quantifier: &SetQuantifier,
3585        queries: &[Query],
3586    ) -> fmt::Result {
3587        write!(f, "{operation}")?;
3588        match set_quantifier {
3589            SetQuantifier::None => {}
3590            _ => {
3591                write!(f, " {set_quantifier}")?;
3592            }
3593        }
3594        write!(f, " ")?;
3595        let parenthesized_queries: Vec<String> =
3596            queries.iter().map(|query| format!("({query})")).collect();
3597        write!(f, "{}", display_comma_separated(&parenthesized_queries))
3598    }
3599}
3600
3601#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3602#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3603#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3604/// `FETCH` clause options.
3605pub struct Fetch {
3606    /// `WITH TIES` option is present.
3607    pub with_ties: bool,
3608    /// `PERCENT` modifier is present.
3609    pub percent: bool,
3610    /// Optional quantity expression (e.g. `FETCH FIRST 10 ROWS`).
3611    pub quantity: Option<Expr>,
3612}
3613
3614impl fmt::Display for Fetch {
3615    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3616        let extension = if self.with_ties { "WITH TIES" } else { "ONLY" };
3617        if let Some(ref quantity) = self.quantity {
3618            let percent = if self.percent { " PERCENT" } else { "" };
3619            write!(f, "FETCH FIRST {quantity}{percent} ROWS {extension}")
3620        } else {
3621            write!(f, "FETCH FIRST ROWS {extension}")
3622        }
3623    }
3624}
3625
3626#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3627#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3628#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3629/// `FOR ...` locking clause.
3630pub struct LockClause {
3631    /// The kind of lock requested (e.g. `SHARE`, `UPDATE`).
3632    pub lock_type: LockType,
3633    /// Optional object name after `OF` (e.g. `FOR UPDATE OF t1`).
3634    pub of: Option<ObjectName>,
3635    /// Optional non-blocking behavior (`NOWAIT` / `SKIP LOCKED`).
3636    pub nonblock: Option<NonBlock>,
3637}
3638
3639impl fmt::Display for LockClause {
3640    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3641        write!(f, "FOR {}", self.lock_type)?;
3642        if let Some(ref of) = self.of {
3643            write!(f, " OF {of}")?;
3644        }
3645        if let Some(ref nb) = self.nonblock {
3646            write!(f, " {nb}")?;
3647        }
3648        Ok(())
3649    }
3650}
3651
3652#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3653#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3654#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3655/// The lock type used in `FOR <lock>` clauses (e.g. `FOR SHARE`, `FOR UPDATE`).
3656pub enum LockType {
3657    /// `SHARE` lock (shared lock).
3658    Share,
3659    /// `UPDATE` lock (exclusive/update lock).
3660    Update,
3661}
3662
3663impl fmt::Display for LockType {
3664    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3665        let select_lock = match self {
3666            LockType::Share => "SHARE",
3667            LockType::Update => "UPDATE",
3668        };
3669        write!(f, "{select_lock}")
3670    }
3671}
3672
3673#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3674#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3675#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3676/// Non-blocking lock options for `FOR ...` clauses.
3677pub enum NonBlock {
3678    /// `NOWAIT` — do not wait for the lock.
3679    Nowait,
3680    /// `SKIP LOCKED` — skip rows that are locked.
3681    SkipLocked,
3682}
3683
3684impl fmt::Display for NonBlock {
3685    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3686        let nonblock = match self {
3687            NonBlock::Nowait => "NOWAIT",
3688            NonBlock::SkipLocked => "SKIP LOCKED",
3689        };
3690        write!(f, "{nonblock}")
3691    }
3692}
3693
3694#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3695#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3696#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3697/// `ALL`, `DISTINCT`, or `DISTINCT ON (...)` modifiers for `SELECT` lists.
3698pub enum Distinct {
3699    /// `ALL` (keep duplicate rows)
3700    ///
3701    /// Generally this is the default if omitted, but omission should be represented as
3702    /// `None::<Option<Distinct>>`
3703    All,
3704
3705    /// `DISTINCT` (remove duplicate rows)
3706    Distinct,
3707
3708    /// `DISTINCT ON (...)` (Postgres extension)
3709    On(Vec<Expr>),
3710}
3711
3712impl fmt::Display for Distinct {
3713    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3714        match self {
3715            Distinct::All => write!(f, "ALL"),
3716            Distinct::Distinct => write!(f, "DISTINCT"),
3717            Distinct::On(col_names) => {
3718                let col_names = display_comma_separated(col_names);
3719                write!(f, "DISTINCT ON ({col_names})")
3720            }
3721        }
3722    }
3723}
3724
3725#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3726#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3727#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3728/// MSSQL `TOP` clause options.
3729pub struct Top {
3730    /// SQL semantic equivalent of LIMIT but with same structure as FETCH.
3731    /// MSSQL only.
3732    pub with_ties: bool,
3733    /// Apply `PERCENT` extension.
3734    pub percent: bool,
3735    /// The optional quantity (expression or constant) following `TOP`.
3736    pub quantity: Option<TopQuantity>,
3737}
3738
3739#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3740#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3741#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3742/// Quantity used in a `TOP` clause: either an expression or a constant.
3743pub enum TopQuantity {
3744    /// A parenthesized expression (MSSQL syntax: `TOP (expr)`).
3745    Expr(Expr),
3746    /// An unparenthesized integer constant: `TOP 10`.
3747    Constant(u64),
3748}
3749
3750impl fmt::Display for Top {
3751    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3752        let extension = if self.with_ties { " WITH TIES" } else { "" };
3753        if let Some(ref quantity) = self.quantity {
3754            let percent = if self.percent { " PERCENT" } else { "" };
3755            match quantity {
3756                TopQuantity::Expr(quantity) => write!(f, "TOP ({quantity}){percent}{extension}"),
3757                TopQuantity::Constant(quantity) => {
3758                    write!(f, "TOP {quantity}{percent}{extension}")
3759                }
3760            }
3761        } else {
3762            write!(f, "TOP{extension}")
3763        }
3764    }
3765}
3766
3767#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3768#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3769#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3770/// An explicit `VALUES` clause and its rows.
3771pub struct Values {
3772    /// Was there an explicit `ROW` keyword (MySQL)?
3773    /// <https://dev.mysql.com/doc/refman/8.0/en/values.html>
3774    pub explicit_row: bool,
3775    /// `true` if `VALUE` (singular) keyword was used instead of `VALUES`.
3776    /// <https://dev.mysql.com/doc/refman/9.2/en/insert.html>
3777    pub value_keyword: bool,
3778    /// The list of rows, each row is a list of expressions.
3779    pub rows: Vec<Parens<Vec<Expr>>>,
3780}
3781
3782impl fmt::Display for Values {
3783    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3784        match self.value_keyword {
3785            true => f.write_str("VALUE")?,
3786            false => f.write_str("VALUES")?,
3787        };
3788        let prefix = if self.explicit_row { "ROW" } else { "" };
3789        let mut delim = "";
3790        for row in &self.rows {
3791            f.write_str(delim)?;
3792            delim = ",";
3793            SpaceOrNewline.fmt(f)?;
3794            Indent(format_args!("{prefix}({})", display_comma_separated(row))).fmt(f)?;
3795        }
3796        Ok(())
3797    }
3798}
3799
3800#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3801#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3802#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3803/// `SELECT INTO` clause options.
3804pub struct SelectInto {
3805    /// `TEMPORARY` modifier.
3806    pub temporary: bool,
3807    /// `UNLOGGED` modifier.
3808    pub unlogged: bool,
3809    /// `TABLE` keyword present.
3810    pub table: bool,
3811    /// Target(s) of the `INTO` clause.
3812    ///
3813    /// [Postgres]: https://www.postgresql.org/docs/current/sql-selectinto.html
3814    /// [MySQL]: https://dev.mysql.com/doc/refman/9.7/en/select-into.html
3815    pub targets: Vec<Expr>,
3816}
3817
3818impl fmt::Display for SelectInto {
3819    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3820        let temporary = if self.temporary { " TEMPORARY" } else { "" };
3821        let unlogged = if self.unlogged { " UNLOGGED" } else { "" };
3822        let table = if self.table { " TABLE" } else { "" };
3823
3824        write!(
3825            f,
3826            "INTO{}{}{} {}",
3827            temporary,
3828            unlogged,
3829            table,
3830            display_comma_separated(&self.targets)
3831        )
3832    }
3833}
3834
3835/// ClickHouse supports GROUP BY WITH modifiers(includes ROLLUP|CUBE|TOTALS).
3836/// e.g. GROUP BY year WITH ROLLUP WITH TOTALS
3837///
3838/// [ClickHouse]: <https://clickhouse.com/docs/en/sql-reference/statements/select/group-by#rollup-modifier>
3839#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3840#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3841#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3842/// Modifiers used with `GROUP BY` such as `WITH ROLLUP` or `WITH CUBE`.
3843pub enum GroupByWithModifier {
3844    /// `WITH ROLLUP` modifier.
3845    Rollup,
3846    /// `WITH CUBE` modifier.
3847    Cube,
3848    /// `WITH TOTALS` modifier (ClickHouse).
3849    Totals,
3850    /// Hive supports GROUPING SETS syntax, e.g. `GROUP BY GROUPING SETS(...)`.
3851    ///
3852    /// [Hive]: <https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=30151323#EnhancedAggregation,Cube,GroupingandRollup-GROUPINGSETSclause>
3853    GroupingSets(Expr),
3854}
3855
3856impl fmt::Display for GroupByWithModifier {
3857    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3858        match self {
3859            GroupByWithModifier::Rollup => write!(f, "WITH ROLLUP"),
3860            GroupByWithModifier::Cube => write!(f, "WITH CUBE"),
3861            GroupByWithModifier::Totals => write!(f, "WITH TOTALS"),
3862            GroupByWithModifier::GroupingSets(expr) => {
3863                write!(f, "{expr}")
3864            }
3865        }
3866    }
3867}
3868
3869#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3870#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3871#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3872#[cfg_attr(feature = "visitor", visit(with = "visit_group_by"))]
3873/// Represents the two syntactic forms that `GROUP BY` can take, including
3874/// `GROUP BY ALL` with optional modifiers and ordinary `GROUP BY <exprs>`.
3875pub enum GroupByExpr {
3876    /// ALL syntax of [Snowflake], [DuckDB] and [ClickHouse].
3877    ///
3878    /// [Snowflake]: <https://docs.snowflake.com/en/sql-reference/constructs/group-by#label-group-by-all-columns>
3879    /// [DuckDB]:  <https://duckdb.org/docs/sql/query_syntax/groupby.html>
3880    /// [ClickHouse]: <https://clickhouse.com/docs/en/sql-reference/statements/select/group-by#group-by-all>
3881    ///
3882    /// ClickHouse also supports WITH modifiers after GROUP BY ALL and expressions.
3883    ///
3884    /// [ClickHouse]: <https://clickhouse.com/docs/en/sql-reference/statements/select/group-by#rollup-modifier>
3885    All(Vec<GroupByWithModifier>),
3886    /// `GROUP BY <expressions>` with optional modifiers.
3887    Expressions(Vec<Expr>, Vec<GroupByWithModifier>),
3888}
3889
3890impl fmt::Display for GroupByExpr {
3891    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3892        match self {
3893            GroupByExpr::All(modifiers) => {
3894                write!(f, "GROUP BY ALL")?;
3895                if !modifiers.is_empty() {
3896                    write!(f, " {}", display_separated(modifiers, " "))?;
3897                }
3898                Ok(())
3899            }
3900            GroupByExpr::Expressions(col_names, modifiers) => {
3901                f.write_str("GROUP BY")?;
3902                SpaceOrNewline.fmt(f)?;
3903                Indent(display_comma_separated(col_names)).fmt(f)?;
3904                if !modifiers.is_empty() {
3905                    write!(f, " {}", display_separated(modifiers, " "))?;
3906                }
3907                Ok(())
3908            }
3909        }
3910    }
3911}
3912
3913/// `FORMAT` identifier or `FORMAT NULL` clause, specific to ClickHouse.
3914///
3915/// [ClickHouse]: <https://clickhouse.com/docs/en/sql-reference/statements/select/format>
3916#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3917#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3918#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3919pub enum FormatClause {
3920    /// The format identifier.
3921    Identifier(Ident),
3922    /// `FORMAT NULL` clause.
3923    Null,
3924}
3925
3926impl fmt::Display for FormatClause {
3927    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3928        match self {
3929            FormatClause::Identifier(ident) => write!(f, "FORMAT {ident}"),
3930            FormatClause::Null => write!(f, "FORMAT NULL"),
3931        }
3932    }
3933}
3934
3935/// FORMAT identifier in input context, specific to ClickHouse.
3936///
3937/// [ClickHouse]: <https://clickhouse.com/docs/en/interfaces/formats>
3938#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3939#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3940#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3941pub struct InputFormatClause {
3942    /// The format identifier.
3943    pub ident: Ident,
3944    /// Optional format parameters.
3945    pub values: Vec<Expr>,
3946}
3947
3948impl fmt::Display for InputFormatClause {
3949    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3950        write!(f, "FORMAT {}", self.ident)?;
3951
3952        if !self.values.is_empty() {
3953            write!(f, " {}", display_comma_separated(self.values.as_slice()))?;
3954        }
3955
3956        Ok(())
3957    }
3958}
3959
3960/// `FOR XML` or `FOR JSON` clause (MSSQL): formats the output of a query as XML or JSON.
3961#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3962#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3963#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3964pub enum ForClause {
3965    /// `FOR BROWSE` clause.
3966    Browse,
3967    /// `FOR JSON ...` clause and its options.
3968    Json {
3969        /// JSON mode (`AUTO` or `PATH`).
3970        for_json: ForJson,
3971        /// Optional `ROOT('...')` parameter.
3972        root: Option<String>,
3973        /// `INCLUDE_NULL_VALUES` flag.
3974        include_null_values: bool,
3975        /// `WITHOUT_ARRAY_WRAPPER` flag.
3976        without_array_wrapper: bool,
3977    },
3978    /// `FOR XML ...` clause and its options.
3979    Xml {
3980        /// XML mode (`RAW`, `AUTO`, `EXPLICIT`, `PATH`).
3981        for_xml: ForXml,
3982        /// `ELEMENTS` flag.
3983        elements: bool,
3984        /// `BINARY BASE64` flag.
3985        binary_base64: bool,
3986        /// Optional `ROOT('...')` parameter.
3987        root: Option<String>,
3988        /// `TYPE` flag.
3989        r#type: bool,
3990    },
3991}
3992
3993impl fmt::Display for ForClause {
3994    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3995        match self {
3996            ForClause::Browse => write!(f, "FOR BROWSE"),
3997            ForClause::Json {
3998                for_json,
3999                root,
4000                include_null_values,
4001                without_array_wrapper,
4002            } => {
4003                write!(f, "FOR JSON ")?;
4004                write!(f, "{for_json}")?;
4005                if let Some(root) = root {
4006                    write!(f, ", ROOT('{root}')")?;
4007                }
4008                if *include_null_values {
4009                    write!(f, ", INCLUDE_NULL_VALUES")?;
4010                }
4011                if *without_array_wrapper {
4012                    write!(f, ", WITHOUT_ARRAY_WRAPPER")?;
4013                }
4014                Ok(())
4015            }
4016            ForClause::Xml {
4017                for_xml,
4018                elements,
4019                binary_base64,
4020                root,
4021                r#type,
4022            } => {
4023                write!(f, "FOR XML ")?;
4024                write!(f, "{for_xml}")?;
4025                if *binary_base64 {
4026                    write!(f, ", BINARY BASE64")?;
4027                }
4028                if *r#type {
4029                    write!(f, ", TYPE")?;
4030                }
4031                if let Some(root) = root {
4032                    write!(f, ", ROOT('{root}')")?;
4033                }
4034                if *elements {
4035                    write!(f, ", ELEMENTS")?;
4036                }
4037                Ok(())
4038            }
4039        }
4040    }
4041}
4042
4043#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4044#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4045#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4046/// Modes for `FOR XML` clause.
4047pub enum ForXml {
4048    /// `RAW` mode with optional root name: `RAW('root')`.
4049    Raw(Option<String>),
4050    /// `AUTO` mode.
4051    Auto,
4052    /// `EXPLICIT` mode.
4053    Explicit,
4054    /// `PATH` mode with optional root: `PATH('root')`.
4055    Path(Option<String>),
4056}
4057
4058impl fmt::Display for ForXml {
4059    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4060        match self {
4061            ForXml::Raw(root) => {
4062                write!(f, "RAW")?;
4063                if let Some(root) = root {
4064                    write!(f, "('{root}')")?;
4065                }
4066                Ok(())
4067            }
4068            ForXml::Auto => write!(f, "AUTO"),
4069            ForXml::Explicit => write!(f, "EXPLICIT"),
4070            ForXml::Path(root) => {
4071                write!(f, "PATH")?;
4072                if let Some(root) = root {
4073                    write!(f, "('{root}')")?;
4074                }
4075                Ok(())
4076            }
4077        }
4078    }
4079}
4080
4081#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4082#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4083#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4084/// Modes for `FOR JSON` clause.
4085pub enum ForJson {
4086    /// `AUTO` mode.
4087    Auto,
4088    /// `PATH` mode.
4089    Path,
4090}
4091
4092impl fmt::Display for ForJson {
4093    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4094        match self {
4095            ForJson::Auto => write!(f, "AUTO"),
4096            ForJson::Path => write!(f, "PATH"),
4097        }
4098    }
4099}
4100
4101/// A single column definition in MySQL's `JSON_TABLE` table valued function.
4102///
4103/// See
4104/// - [MySQL's JSON_TABLE documentation](https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html#function_json-table)
4105/// - [Oracle's JSON_TABLE documentation](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/JSON_TABLE.html)
4106/// - [MariaDB's JSON_TABLE documentation](https://mariadb.com/kb/en/json_table/)
4107///
4108/// ```sql
4109/// SELECT *
4110/// FROM JSON_TABLE(
4111///     '["a", "b"]',
4112///     '$[*]' COLUMNS (
4113///         name FOR ORDINALITY,
4114///         value VARCHAR(20) PATH '$',
4115///         NESTED PATH '$[*]' COLUMNS (
4116///             value VARCHAR(20) PATH '$'
4117///         )
4118///     )
4119/// ) AS jt;
4120/// ```
4121#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4122#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4123#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4124pub enum JsonTableColumn {
4125    /// A named column with a JSON path
4126    Named(JsonTableNamedColumn),
4127    /// The FOR ORDINALITY column, which is a special column that returns the index of the current row in a JSON array.
4128    ForOrdinality(Ident),
4129    /// A set of nested columns, which extracts data from a nested JSON array.
4130    Nested(JsonTableNestedColumn),
4131}
4132
4133impl fmt::Display for JsonTableColumn {
4134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4135        match self {
4136            JsonTableColumn::Named(json_table_named_column) => {
4137                write!(f, "{json_table_named_column}")
4138            }
4139            JsonTableColumn::ForOrdinality(ident) => write!(f, "{ident} FOR ORDINALITY"),
4140            JsonTableColumn::Nested(json_table_nested_column) => {
4141                write!(f, "{json_table_nested_column}")
4142            }
4143        }
4144    }
4145}
4146
4147/// A nested column in a JSON_TABLE column list
4148///
4149/// See <https://mariadb.com/kb/en/json_table/#nested-paths>
4150#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4151#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4152#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4153/// A nested column in a `JSON_TABLE` column list.
4154pub struct JsonTableNestedColumn {
4155    /// JSON path expression (must be a literal `Value`).
4156    pub path: ValueWithSpan,
4157    /// Columns extracted from the matched nested array.
4158    pub columns: Vec<JsonTableColumn>,
4159}
4160
4161impl fmt::Display for JsonTableNestedColumn {
4162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4163        write!(
4164            f,
4165            "NESTED PATH {} COLUMNS ({})",
4166            self.path,
4167            display_comma_separated(&self.columns)
4168        )
4169    }
4170}
4171
4172/// A single column definition in MySQL's `JSON_TABLE` table valued function.
4173///
4174/// See <https://mariadb.com/kb/en/json_table/#path-columns>
4175///
4176/// ```sql
4177///         value VARCHAR(20) PATH '$'
4178/// ```
4179#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4180#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4181#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4182pub struct JsonTableNamedColumn {
4183    /// The name of the column to be extracted.
4184    pub name: Ident,
4185    /// The type of the column to be extracted.
4186    pub r#type: DataType,
4187    /// The path to the column to be extracted. Must be a literal string.
4188    pub path: ValueWithSpan,
4189    /// true if the column is a boolean set to true if the given path exists
4190    pub exists: bool,
4191    /// The empty handling clause of the column
4192    pub on_empty: Option<JsonTableColumnErrorHandling>,
4193    /// The error handling clause of the column
4194    pub on_error: Option<JsonTableColumnErrorHandling>,
4195}
4196
4197impl fmt::Display for JsonTableNamedColumn {
4198    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4199        write!(
4200            f,
4201            "{} {}{} PATH {}",
4202            self.name,
4203            self.r#type,
4204            if self.exists { " EXISTS" } else { "" },
4205            self.path
4206        )?;
4207        if let Some(on_empty) = &self.on_empty {
4208            write!(f, " {on_empty} ON EMPTY")?;
4209        }
4210        if let Some(on_error) = &self.on_error {
4211            write!(f, " {on_error} ON ERROR")?;
4212        }
4213        Ok(())
4214    }
4215}
4216
4217/// Stores the error handling clause of a `JSON_TABLE` table valued function:
4218/// {NULL | DEFAULT json_string | ERROR} ON {ERROR | EMPTY }
4219#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4220#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4221#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4222/// Error/empty-value handling for `JSON_TABLE` columns.
4223pub enum JsonTableColumnErrorHandling {
4224    /// `NULL` — return NULL when the path does not match.
4225    Null,
4226    /// `DEFAULT <value>` — use the provided `Value` as a default.
4227    Default(ValueWithSpan),
4228    /// `ERROR` — raise an error.
4229    Error,
4230}
4231
4232impl fmt::Display for JsonTableColumnErrorHandling {
4233    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4234        match self {
4235            JsonTableColumnErrorHandling::Null => write!(f, "NULL"),
4236            JsonTableColumnErrorHandling::Default(json_string) => {
4237                write!(f, "DEFAULT {json_string}")
4238            }
4239            JsonTableColumnErrorHandling::Error => write!(f, "ERROR"),
4240        }
4241    }
4242}
4243
4244/// A single column definition in MSSQL's `OPENJSON WITH` clause.
4245///
4246/// ```sql
4247/// colName type [ column_path ] [ AS JSON ]
4248/// ```
4249///
4250/// Reference: <https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16#syntax>
4251#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4252#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4253#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4254pub struct OpenJsonTableColumn {
4255    /// The name of the column to be extracted.
4256    pub name: Ident,
4257    /// The type of the column to be extracted.
4258    pub r#type: DataType,
4259    /// The path to the column to be extracted. Must be a literal string.
4260    pub path: Option<String>,
4261    /// The `AS JSON` option.
4262    pub as_json: bool,
4263}
4264
4265impl fmt::Display for OpenJsonTableColumn {
4266    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4267        write!(f, "{} {}", self.name, self.r#type)?;
4268        if let Some(path) = &self.path {
4269            write!(f, " '{}'", value::escape_single_quote_string(path))?;
4270        }
4271        if self.as_json {
4272            write!(f, " AS JSON")?;
4273        }
4274        Ok(())
4275    }
4276}
4277
4278/// BigQuery supports ValueTables which have 2 modes:
4279/// `SELECT [ALL | DISTINCT] AS STRUCT`
4280/// `SELECT [ALL | DISTINCT] AS VALUE`
4281///
4282/// <https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#value_tables>
4283/// <https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#select_list>
4284#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4285#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4286#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4287/// Mode of BigQuery value tables, e.g. `AS STRUCT` or `AS VALUE`.
4288pub enum ValueTableMode {
4289    /// `AS STRUCT`
4290    AsStruct,
4291    /// `AS VALUE`
4292    AsValue,
4293    /// `DISTINCT AS STRUCT`
4294    DistinctAsStruct,
4295    /// `DISTINCT AS VALUE`
4296    DistinctAsValue,
4297}
4298
4299impl fmt::Display for ValueTableMode {
4300    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4301        match self {
4302            ValueTableMode::AsStruct => write!(f, "AS STRUCT"),
4303            ValueTableMode::AsValue => write!(f, "AS VALUE"),
4304            ValueTableMode::DistinctAsStruct => write!(f, "DISTINCT AS STRUCT"),
4305            ValueTableMode::DistinctAsValue => write!(f, "DISTINCT AS VALUE"),
4306        }
4307    }
4308}
4309
4310/// The `FROM` clause of an `UPDATE TABLE` statement
4311#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4312#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4313#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4314pub enum UpdateTableFromKind {
4315    /// Update Statement where the 'FROM' clause is before the 'SET' keyword (Supported by Snowflake)
4316    /// For Example: `UPDATE FROM t1 SET t1.name='aaa'`
4317    BeforeSet(Vec<TableWithJoins>),
4318    /// Update Statement where the 'FROM' clause is after the 'SET' keyword (Which is the standard way)
4319    /// For Example: `UPDATE SET t1.name='aaa' FROM t1`
4320    AfterSet(Vec<TableWithJoins>),
4321}
4322
4323/// Defines the options for an XmlTable column: Named or ForOrdinality
4324#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4325#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4326#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4327pub enum XmlTableColumnOption {
4328    /// A named column with a type, optional path, and default value.
4329    NamedInfo {
4330        /// The type of the column to be extracted.
4331        r#type: DataType,
4332        /// The path to the column to be extracted. If None, defaults to the column name.
4333        path: Option<Expr>,
4334        /// Default value if path does not match
4335        default: Option<Expr>,
4336        /// Whether the column is nullable (NULL=true, NOT NULL=false)
4337        nullable: bool,
4338    },
4339    /// The FOR ORDINALITY marker
4340    ForOrdinality,
4341}
4342
4343/// A single column definition in XMLTABLE
4344///
4345/// ```sql
4346/// COLUMNS
4347///     id int PATH '@id',
4348///     ordinality FOR ORDINALITY,
4349///     "COUNTRY_NAME" text,
4350///     country_id text PATH 'COUNTRY_ID',
4351///     size_sq_km float PATH 'SIZE[@unit = "sq_km"]',
4352///     size_other text PATH 'concat(SIZE[@unit!="sq_km"], " ", SIZE[@unit!="sq_km"]/@unit)',
4353///     premier_name text PATH 'PREMIER_NAME' DEFAULT 'not specified'
4354/// ```
4355#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4356#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4357#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4358pub struct XmlTableColumn {
4359    /// The name of the column.
4360    pub name: Ident,
4361    /// Column options: type/path/default or FOR ORDINALITY
4362    pub option: XmlTableColumnOption,
4363}
4364
4365impl fmt::Display for XmlTableColumn {
4366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4367        write!(f, "{}", self.name)?;
4368        match &self.option {
4369            XmlTableColumnOption::NamedInfo {
4370                r#type,
4371                path,
4372                default,
4373                nullable,
4374            } => {
4375                write!(f, " {type}")?;
4376                if let Some(p) = path {
4377                    write!(f, " PATH {p}")?;
4378                }
4379                if let Some(d) = default {
4380                    write!(f, " DEFAULT {d}")?;
4381                }
4382                if !*nullable {
4383                    write!(f, " NOT NULL")?;
4384                }
4385                Ok(())
4386            }
4387            XmlTableColumnOption::ForOrdinality => {
4388                write!(f, " FOR ORDINALITY")
4389            }
4390        }
4391    }
4392}
4393
4394/// Argument passed in the XMLTABLE PASSING clause
4395#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4396#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4397#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4398/// Argument passed in the `XMLTABLE PASSING` clause.
4399pub struct XmlPassingArgument {
4400    /// Expression to pass to the XML table.
4401    pub expr: Expr,
4402    /// Optional alias for the argument.
4403    pub alias: Option<Ident>,
4404    /// `true` if `BY VALUE` is specified for the argument.
4405    pub by_value: bool,
4406}
4407
4408impl fmt::Display for XmlPassingArgument {
4409    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4410        if self.by_value {
4411            write!(f, "BY VALUE ")?;
4412        }
4413        write!(f, "{}", self.expr)?;
4414        if let Some(alias) = &self.alias {
4415            write!(f, " AS {alias}")?;
4416        }
4417        Ok(())
4418    }
4419}
4420
4421/// The PASSING clause for XMLTABLE
4422#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4423#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4424#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4425/// The PASSING clause for `XMLTABLE`.
4426pub struct XmlPassingClause {
4427    /// The list of passed arguments.
4428    pub arguments: Vec<XmlPassingArgument>,
4429}
4430
4431impl fmt::Display for XmlPassingClause {
4432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4433        if !self.arguments.is_empty() {
4434            write!(f, " PASSING {}", display_comma_separated(&self.arguments))?;
4435        }
4436        Ok(())
4437    }
4438}
4439
4440/// Represents a single XML namespace definition in the XMLNAMESPACES clause.
4441///
4442/// `namespace_uri AS namespace_name`
4443#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4444#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4445#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4446pub struct XmlNamespaceDefinition {
4447    /// The namespace URI (a text expression).
4448    pub uri: Expr,
4449    /// The alias for the namespace (a simple identifier).
4450    pub name: Ident,
4451}
4452
4453impl fmt::Display for XmlNamespaceDefinition {
4454    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4455        write!(f, "{} AS {}", self.uri, self.name)
4456    }
4457}