Skip to main content

risingwave_sqlparser/ast/
query.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12
13use crate::ast::*;
14
15/// The most complete variant of a `SELECT` query expression, optionally
16/// including `WITH`, `UNION` / other set operations, and `ORDER BY`.
17#[derive(Debug, Clone, PartialEq, Eq, Hash)]
18pub struct Query {
19    /// WITH (common table expressions, or CTEs)
20    pub with: Option<With>,
21    /// SELECT or UNION / EXCEPT / INTERSECT
22    pub body: SetExpr,
23    /// ORDER BY
24    pub order_by: Vec<OrderByExpr>,
25    /// `LIMIT { <N> | ALL }`
26    pub limit: Option<Expr>,
27    /// `OFFSET <N> [ { ROW | ROWS } ]`
28    ///
29    /// `ROW` and `ROWS` are noise words that don't influence the effect of the clause.
30    /// They are provided for ANSI compatibility.
31    pub offset: Option<String>,
32    /// `FETCH { FIRST | NEXT } <N> [ PERCENT ] { ROW | ROWS } | { ONLY | WITH TIES }`
33    ///
34    /// `ROW` and `ROWS` as well as `FIRST` and `NEXT` are noise words that don't influence the
35    /// effect of the clause. They are provided for ANSI compatibility.
36    pub fetch: Option<Fetch>,
37}
38
39impl Query {
40    /// Simple `VALUES` without other clauses.
41    pub fn as_simple_values(&self) -> Option<&Values> {
42        match &self {
43            Query {
44                with: None,
45                body: SetExpr::Values(values),
46                order_by,
47                limit: None,
48                offset: None,
49                fetch: None,
50            } if order_by.is_empty() => Some(values),
51            _ => None,
52        }
53    }
54
55    /// `SELECT <expr>` without other clauses.
56    pub fn as_single_select_item(&self) -> Option<&Expr> {
57        match &self {
58            Query {
59                with: None,
60                body: SetExpr::Select(select),
61                order_by,
62                limit: None,
63                offset: None,
64                fetch: None,
65            } if order_by.is_empty() => match select.as_ref() {
66                Select {
67                    distinct: Distinct::All,
68                    projection,
69                    from,
70                    lateral_views,
71                    selection: None,
72                    group_by,
73                    having: None,
74                    window,
75                } if projection.len() == 1
76                    && from.is_empty()
77                    && lateral_views.is_empty()
78                    && group_by.is_empty()
79                    && window.is_empty() =>
80                {
81                    match &projection[0] {
82                        SelectItem::UnnamedExpr(expr) => Some(expr),
83                        SelectItem::ExprWithAlias { expr, .. } => Some(expr),
84                        _ => None,
85                    }
86                }
87                _ => None,
88            },
89            _ => None,
90        }
91    }
92}
93
94impl fmt::Display for Query {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        if let Some(ref with) = self.with {
97            write!(f, "{} ", with)?;
98        }
99        write!(f, "{}", self.body)?;
100        if !self.order_by.is_empty() {
101            write!(f, " ORDER BY {}", display_comma_separated(&self.order_by))?;
102        }
103        if let Some(ref limit) = self.limit {
104            write!(f, " LIMIT {}", limit)?;
105        }
106        if let Some(ref offset) = self.offset {
107            write!(f, " OFFSET {}", offset)?;
108        }
109        if let Some(ref fetch) = self.fetch {
110            write!(f, " {}", fetch)?;
111        }
112        Ok(())
113    }
114}
115
116/// A node in a tree, representing a "query body" expression, roughly:
117/// `SELECT ... [ {UNION|EXCEPT|INTERSECT} SELECT ...]`
118
119#[derive(Debug, Clone, PartialEq, Eq, Hash)]
120pub enum SetExpr {
121    /// Restricted SELECT .. FROM .. HAVING (no ORDER BY or set operations)
122    Select(Box<Select>),
123    /// Parenthesized SELECT subquery, which may include more set operations
124    /// in its body and an optional ORDER BY / LIMIT.
125    Query(Box<Query>),
126    /// UNION/EXCEPT/INTERSECT of two queries
127    SetOperation {
128        op: SetOperator,
129        all: bool,
130        corresponding: Corresponding,
131        left: Box<SetExpr>,
132        right: Box<SetExpr>,
133    },
134    Values(Values),
135}
136
137impl fmt::Display for SetExpr {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        match self {
140            SetExpr::Select(s) => write!(f, "{}", s),
141            SetExpr::Query(q) => write!(f, "({})", q),
142            SetExpr::Values(v) => write!(f, "{}", v),
143            SetExpr::SetOperation {
144                left,
145                right,
146                op,
147                all,
148                corresponding,
149            } => {
150                let all_str = if *all { " ALL" } else { "" };
151                write!(f, "{} {}{}{} {}", left, op, all_str, corresponding, right)
152            }
153        }
154    }
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
158pub enum SetOperator {
159    Union,
160    Except,
161    Intersect,
162}
163
164impl fmt::Display for SetOperator {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.write_str(match self {
167            SetOperator::Union => "UNION",
168            SetOperator::Except => "EXCEPT",
169            SetOperator::Intersect => "INTERSECT",
170        })
171    }
172}
173
174/// `CORRESPONDING [ BY <left paren> <corresponding column list> <right paren> ]`
175#[derive(Debug, Clone, PartialEq, Eq, Hash)]
176pub struct Corresponding {
177    pub corresponding: bool,
178    pub column_list: Option<Vec<Ident>>,
179}
180
181impl Corresponding {
182    pub fn with_column_list(column_list: Option<Vec<Ident>>) -> Self {
183        Self {
184            corresponding: true,
185            column_list,
186        }
187    }
188
189    pub fn none() -> Self {
190        Self {
191            corresponding: false,
192            column_list: None,
193        }
194    }
195
196    pub fn is_corresponding(&self) -> bool {
197        self.corresponding
198    }
199
200    pub fn column_list(&self) -> Option<&[Ident]> {
201        self.column_list.as_deref()
202    }
203}
204
205impl fmt::Display for Corresponding {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        if self.corresponding {
208            write!(f, " CORRESPONDING")?;
209            if let Some(column_list) = &self.column_list {
210                write!(f, " BY ({})", display_comma_separated(column_list))?;
211            }
212        }
213        Ok(())
214    }
215}
216
217/// A restricted variant of `SELECT` (without CTEs/`ORDER BY`), which may
218/// appear either as the only body item of an `SQLQuery`, or as an operand
219/// to a set operation like `UNION`.
220#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
221pub struct Select {
222    pub distinct: Distinct,
223    /// projection expressions
224    pub projection: Vec<SelectItem>,
225    /// FROM
226    pub from: Vec<TableWithJoins>,
227    /// LATERAL VIEWs
228    pub lateral_views: Vec<LateralView>,
229    /// WHERE
230    pub selection: Option<Expr>,
231    /// GROUP BY
232    pub group_by: Vec<Expr>,
233    /// HAVING
234    pub having: Option<Expr>,
235    /// WINDOW
236    pub window: Vec<NamedWindow>,
237}
238
239impl fmt::Display for Select {
240    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
241        write!(f, "SELECT{}", self.distinct)?;
242        write!(f, " {}", display_comma_separated(&self.projection))?;
243        if !self.from.is_empty() {
244            write!(f, " FROM {}", display_comma_separated(&self.from))?;
245        }
246        if !self.lateral_views.is_empty() {
247            for lv in &self.lateral_views {
248                write!(f, "{}", lv)?;
249            }
250        }
251        if let Some(ref selection) = self.selection {
252            write!(f, " WHERE {}", selection)?;
253        }
254        if !self.group_by.is_empty() {
255            write!(f, " GROUP BY {}", display_comma_separated(&self.group_by))?;
256        }
257        if let Some(ref having) = self.having {
258            write!(f, " HAVING {}", having)?;
259        }
260        if !self.window.is_empty() {
261            write!(f, " WINDOW {}", display_comma_separated(&self.window))?;
262        }
263        Ok(())
264    }
265}
266
267/// An `ALL`, `DISTINCT` or `DISTINCT ON (expr, ...)` after `SELECT`.
268#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
269#[expect(clippy::enum_variant_names)]
270pub enum Distinct {
271    /// An optional parameter that returns all matching rows.
272    #[default]
273    All,
274    /// A parameter that removes duplicates from the result-set.
275    Distinct,
276    /// An optional parameter that eliminates duplicate data based on the expressions.
277    DistinctOn(Vec<Expr>),
278}
279
280impl Distinct {
281    pub const fn is_all(&self) -> bool {
282        matches!(self, Distinct::All)
283    }
284
285    pub const fn is_distinct(&self) -> bool {
286        matches!(self, Distinct::Distinct)
287    }
288}
289
290impl fmt::Display for Distinct {
291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292        match self {
293            Distinct::All => write!(f, ""),
294            Distinct::Distinct => write!(f, " DISTINCT"),
295            Distinct::DistinctOn(exprs) => {
296                write!(f, " DISTINCT ON ({})", display_comma_separated(exprs))
297            }
298        }
299    }
300}
301
302/// A hive LATERAL VIEW with potential column aliases
303#[derive(Debug, Clone, PartialEq, Eq, Hash)]
304pub struct LateralView {
305    /// LATERAL VIEW
306    pub lateral_view: Expr,
307    /// LATERAL VIEW table name
308    pub lateral_view_name: ObjectName,
309    /// LATERAL VIEW optional column aliases
310    pub lateral_col_alias: Vec<Ident>,
311    /// LATERAL VIEW OUTER
312    pub outer: bool,
313}
314
315impl fmt::Display for LateralView {
316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317        write!(
318            f,
319            " LATERAL VIEW{outer} {} {}",
320            self.lateral_view,
321            self.lateral_view_name,
322            outer = if self.outer { " OUTER" } else { "" }
323        )?;
324        if !self.lateral_col_alias.is_empty() {
325            write!(
326                f,
327                " AS {}",
328                display_comma_separated(&self.lateral_col_alias)
329            )?;
330        }
331        Ok(())
332    }
333}
334
335#[derive(Debug, Clone, PartialEq, Eq, Hash)]
336pub struct With {
337    pub recursive: bool,
338    pub cte_tables: Vec<Cte>,
339}
340
341impl fmt::Display for With {
342    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343        write!(
344            f,
345            "WITH {}{}",
346            if self.recursive { "RECURSIVE " } else { "" },
347            display_comma_separated(&self.cte_tables)
348        )
349    }
350}
351
352/// A single CTE (used after `WITH`): `alias [(col1, col2, ...)] AS ( query )`
353///
354/// The names in the column list before `AS`, when specified, replace the names
355/// of the columns returned by the query. The parser does not validate that the
356/// number of columns in the query matches the number of columns in the query.
357#[derive(Debug, Clone, PartialEq, Eq, Hash)]
358pub struct Cte {
359    pub alias: TableAlias,
360    pub cte_inner: CteInner,
361}
362
363impl fmt::Display for Cte {
364    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
365        match &self.cte_inner {
366            CteInner::Query(query) => write!(f, "{} AS ({})", self.alias, query)?,
367            CteInner::ChangeLog {
368                from,
369                key,
370                distributed_by,
371            } => {
372                write!(f, "{} AS changelog from {}", self.alias, from)?;
373
374                if let Some(key) = key {
375                    write!(f, " KEY ({})", display_comma_separated(key))?;
376                }
377                if let Some(columns) = distributed_by {
378                    write!(f, " DISTRIBUTED BY ({})", display_comma_separated(columns))?;
379                }
380            }
381        }
382        Ok(())
383    }
384}
385
386#[derive(Debug, Clone, PartialEq, Eq, Hash)]
387pub enum CteInner {
388    Query(Box<Query>),
389    ChangeLog {
390        from: ObjectName,
391        key: Option<Vec<Ident>>,
392        distributed_by: Option<Vec<Ident>>,
393    },
394}
395
396/// One item of the comma-separated list following `SELECT`
397#[derive(Debug, Clone, PartialEq, Eq, Hash)]
398pub enum SelectItem {
399    /// Any expression, not followed by `[ AS ] alias`
400    UnnamedExpr(Expr),
401    /// Expr is an arbitrary expression, returning either a table or a column.
402    /// Idents are the prefix of `*`, which are consecutive field accesses.
403    /// e.g. `(table.v1).*` or `(table).v1.*`
404    ExprQualifiedWildcard(Expr, Vec<Ident>),
405    /// An expression, followed by `[ AS ] alias`
406    ExprWithAlias { expr: Expr, alias: Ident },
407    /// `alias.*` or even `schema.table.*` followed by optional except
408    QualifiedWildcard(ObjectName, Option<Vec<Expr>>),
409    /// An unqualified `*`, or `* except (exprs)`
410    Wildcard(Option<Vec<Expr>>),
411}
412
413impl fmt::Display for SelectItem {
414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415        match &self {
416            SelectItem::UnnamedExpr(expr) => write!(f, "{}", expr),
417            SelectItem::ExprWithAlias { expr, alias } => write!(f, "{} AS {}", expr, alias),
418            SelectItem::ExprQualifiedWildcard(expr, prefix) => write!(
419                f,
420                "({}){}.*",
421                expr,
422                prefix
423                    .iter()
424                    .format_with("", |i, f| f(&format_args!(".{i}")))
425            ),
426            SelectItem::QualifiedWildcard(prefix, except) => match except {
427                Some(cols) => write!(
428                    f,
429                    "{}.* EXCEPT ({})",
430                    prefix,
431                    cols.iter()
432                        .map(|v| v.to_string())
433                        .collect::<Vec<String>>()
434                        .as_slice()
435                        .join(", ")
436                ),
437                None => write!(f, "{}.*", prefix),
438            },
439            SelectItem::Wildcard(except) => match except {
440                Some(cols) => write!(
441                    f,
442                    "* EXCEPT ({})",
443                    cols.iter()
444                        .map(|v| v.to_string())
445                        .collect::<Vec<String>>()
446                        .as_slice()
447                        .join(", ")
448                ),
449                None => write!(f, "*"),
450            },
451        }
452    }
453}
454
455#[derive(Debug, Clone, PartialEq, Eq, Hash)]
456pub struct TableWithJoins {
457    pub relation: TableFactor,
458    pub joins: Vec<Join>,
459}
460
461impl fmt::Display for TableWithJoins {
462    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463        write!(f, "{}", self.relation)?;
464        for join in &self.joins {
465            write!(f, "{}", join)?;
466        }
467        Ok(())
468    }
469}
470
471/// A table name or a parenthesized subquery with an optional alias
472#[derive(Debug, Clone, PartialEq, Eq, Hash)]
473pub enum TableFactor {
474    Table {
475        name: ObjectName,
476        alias: Option<TableAlias>,
477        as_of: Option<AsOf>,
478    },
479    Derived {
480        lateral: bool,
481        subquery: Box<Query>,
482        alias: Option<TableAlias>,
483    },
484    /// `<expr>(args)[ AS <alias> ]`
485    ///
486    /// Note that scalar functions can also be used in this way.
487    TableFunction {
488        name: ObjectName,
489        alias: Option<TableAlias>,
490        args: Vec<FunctionArg>,
491        with_ordinality: bool,
492    },
493    /// Represents a parenthesized table factor. The SQL spec only allows a
494    /// join expression (`(foo <JOIN> bar [ <JOIN> baz ... ])`) to be nested,
495    /// possibly several times.
496    ///
497    /// The parser may also accept non-standard nesting of bare tables for some
498    /// dialects, but the information about such nesting is stripped from AST.
499    NestedJoin(Box<TableWithJoins>),
500    /// `<table> MATCH_RECOGNIZE (...)`: SQL:2016 row pattern recognition applied
501    /// to an input table factor.
502    MatchRecognize {
503        /// The input the pattern is matched over.
504        table: Box<TableFactor>,
505        /// `PARTITION BY <expr>, ...` — empty when omitted.
506        partition_by: Vec<Expr>,
507        /// `ORDER BY <expr> [ASC|DESC], ...` — empty when omitted.
508        order_by: Vec<OrderByExpr>,
509        /// `MEASURES <expr> AS <alias>, ...` — empty when omitted.
510        measures: Vec<Measure>,
511        /// `ONE ROW PER MATCH` | `ALL ROWS PER MATCH` — `None` when omitted.
512        rows_per_match: Option<RowsPerMatch>,
513        /// `AFTER MATCH SKIP ...` — `None` when omitted.
514        after_match_skip: Option<AfterMatchSkip>,
515        /// `PATTERN ( <pattern> )` — required.
516        pattern: MatchRecognizePattern,
517        /// `WITHIN <interval>` — bounds a match's time span; `None` when omitted.
518        within: Option<Expr>,
519        /// `SUBSET <name> = (<vars>), ...` — empty when omitted.
520        subsets: Vec<SubsetDefinition>,
521        /// `DEFINE <symbol> AS <condition>, ...` — required.
522        symbols: Vec<SymbolDefinition>,
523        /// Optional alias for the row-pattern output.
524        alias: Option<TableAlias>,
525    },
526}
527
528/// A single `MEASURES` item: `<expr> AS <alias>`.
529#[derive(Debug, Clone, PartialEq, Eq, Hash)]
530pub struct Measure {
531    pub expr: Expr,
532    pub alias: Ident,
533}
534
535impl fmt::Display for Measure {
536    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537        write!(f, "{} AS {}", self.expr, self.alias)
538    }
539}
540
541/// The output mode of a `MATCH_RECOGNIZE` clause.
542#[derive(Debug, Clone, PartialEq, Eq, Hash)]
543pub enum RowsPerMatch {
544    /// `ONE ROW PER MATCH`
545    OneRow,
546    /// `ALL ROWS PER MATCH`
547    AllRows,
548}
549
550impl fmt::Display for RowsPerMatch {
551    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552        match self {
553            RowsPerMatch::OneRow => write!(f, "ONE ROW PER MATCH"),
554            RowsPerMatch::AllRows => write!(f, "ALL ROWS PER MATCH"),
555        }
556    }
557}
558
559/// The `AFTER MATCH SKIP` strategy of a `MATCH_RECOGNIZE` clause.
560#[derive(Debug, Clone, PartialEq, Eq, Hash)]
561pub enum AfterMatchSkip {
562    /// `AFTER MATCH SKIP PAST LAST ROW`
563    PastLastRow,
564    /// `AFTER MATCH SKIP TO NEXT ROW`
565    ToNextRow,
566    /// `AFTER MATCH SKIP TO FIRST <symbol>`
567    ToFirst(Ident),
568    /// `AFTER MATCH SKIP TO LAST <symbol>`
569    ToLast(Ident),
570}
571
572impl fmt::Display for AfterMatchSkip {
573    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
574        write!(f, "AFTER MATCH SKIP ")?;
575        match self {
576            AfterMatchSkip::PastLastRow => write!(f, "PAST LAST ROW"),
577            AfterMatchSkip::ToNextRow => write!(f, "TO NEXT ROW"),
578            AfterMatchSkip::ToFirst(symbol) => write!(f, "TO FIRST {}", symbol),
579            AfterMatchSkip::ToLast(symbol) => write!(f, "TO LAST {}", symbol),
580        }
581    }
582}
583
584/// A single `DEFINE` item: `<symbol> AS <condition>`.
585#[derive(Debug, Clone, PartialEq, Eq, Hash)]
586pub struct SymbolDefinition {
587    pub symbol: Ident,
588    pub definition: Expr,
589}
590
591impl fmt::Display for SymbolDefinition {
592    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593        write!(f, "{} AS {}", self.symbol, self.definition)
594    }
595}
596
597/// A single `SUBSET` item: `<name> = (<pattern variable>, ...)` — a union variable.
598#[derive(Debug, Clone, PartialEq, Eq, Hash)]
599pub struct SubsetDefinition {
600    pub name: Ident,
601    pub members: Vec<Ident>,
602}
603
604impl fmt::Display for SubsetDefinition {
605    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
606        write!(
607            f,
608            "{} = ({})",
609            self.name,
610            display_comma_separated(&self.members)
611        )
612    }
613}
614
615/// A row-pattern variable, or one of the row-pattern anchors.
616#[derive(Debug, Clone, PartialEq, Eq, Hash)]
617pub enum MatchRecognizeSymbol {
618    /// A named pattern variable, defined (or referenced) in `DEFINE`.
619    Named(Ident),
620    /// The start anchor `^`.
621    Start,
622    /// The end anchor `$`.
623    End,
624}
625
626impl fmt::Display for MatchRecognizeSymbol {
627    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628        match self {
629            MatchRecognizeSymbol::Named(symbol) => write!(f, "{}", symbol),
630            MatchRecognizeSymbol::Start => write!(f, "^"),
631            MatchRecognizeSymbol::End => write!(f, "$"),
632        }
633    }
634}
635
636/// A row-pattern expression inside `PATTERN ( ... )`.
637#[derive(Debug, Clone, PartialEq, Eq, Hash)]
638pub enum MatchRecognizePattern {
639    /// A single symbol, e.g. `A`, `^`, `$`.
640    Symbol(MatchRecognizeSymbol),
641    /// An exclusion `{- <pattern> -}`.
642    Exclude(MatchRecognizeSymbol),
643    /// `PERMUTE(<symbol>, ...)`.
644    Permute(Vec<MatchRecognizeSymbol>),
645    /// Concatenation, e.g. `A B C`.
646    Concat(Vec<MatchRecognizePattern>),
647    /// A parenthesized sub-pattern `( <pattern> )`.
648    Group(Box<MatchRecognizePattern>),
649    /// Alternation, e.g. `A | B | C`.
650    Alternation(Vec<MatchRecognizePattern>),
651    /// A quantified sub-pattern, e.g. `A*`, `A+`, `A?`, `A{1,3}`. The bool is `reluctant` (a trailing
652    /// `?`, e.g. `A*?`, which prefers the fewest matches).
653    Repetition(Box<MatchRecognizePattern>, RepetitionQuantifier, bool),
654}
655
656impl fmt::Display for MatchRecognizePattern {
657    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
658        use MatchRecognizePattern::*;
659        match self {
660            Symbol(symbol) => write!(f, "{}", symbol),
661            Exclude(symbol) => write!(f, "{{- {} -}}", symbol),
662            Permute(symbols) => write!(f, "PERMUTE({})", display_comma_separated(symbols)),
663            Concat(patterns) => write!(f, "{}", display_separated(patterns, " ")),
664            Group(pattern) => write!(f, "({})", pattern),
665            Alternation(patterns) => write!(f, "{}", display_separated(patterns, " | ")),
666            Repetition(pattern, quantifier, reluctant) => {
667                write!(
668                    f,
669                    "{}{}{}",
670                    pattern,
671                    quantifier,
672                    if *reluctant { "?" } else { "" }
673                )
674            }
675        }
676    }
677}
678
679/// A quantifier applied to a row-pattern, e.g. `*`, `+`, `?`, `{n,m}`.
680#[derive(Debug, Clone, PartialEq, Eq, Hash)]
681pub enum RepetitionQuantifier {
682    /// `*`
683    ZeroOrMore,
684    /// `+`
685    OneOrMore,
686    /// `?`
687    AtMostOne,
688    /// `{n}`
689    Exactly(u32),
690    /// `{n,}`
691    AtLeast(u32),
692    /// `{,m}`
693    AtMost(u32),
694    /// `{n,m}`
695    Range(u32, u32),
696}
697
698impl fmt::Display for RepetitionQuantifier {
699    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
700        use RepetitionQuantifier::*;
701        match self {
702            ZeroOrMore => write!(f, "*"),
703            OneOrMore => write!(f, "+"),
704            AtMostOne => write!(f, "?"),
705            Exactly(n) => write!(f, "{{{}}}", n),
706            AtLeast(n) => write!(f, "{{{},}}", n),
707            AtMost(m) => write!(f, "{{,{}}}", m),
708            Range(n, m) => write!(f, "{{{},{}}}", n, m),
709        }
710    }
711}
712
713impl fmt::Display for TableFactor {
714    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
715        match self {
716            TableFactor::Table { name, alias, as_of } => {
717                write!(f, "{}", name)?;
718                if let Some(as_of) = as_of {
719                    write!(f, "{}", as_of)?
720                }
721                if let Some(alias) = alias {
722                    write!(f, " AS {}", alias)?;
723                }
724                Ok(())
725            }
726            TableFactor::Derived {
727                lateral,
728                subquery,
729                alias,
730            } => {
731                if *lateral {
732                    write!(f, "LATERAL ")?;
733                }
734                write!(f, "({})", subquery)?;
735                if let Some(alias) = alias {
736                    write!(f, " AS {}", alias)?;
737                }
738                Ok(())
739            }
740            TableFactor::TableFunction {
741                name,
742                alias,
743                args,
744                with_ordinality,
745            } => {
746                write!(f, "{}({})", name, display_comma_separated(args))?;
747                if *with_ordinality {
748                    write!(f, " WITH ORDINALITY")?;
749                }
750                if let Some(alias) = alias {
751                    write!(f, " AS {}", alias)?;
752                }
753                Ok(())
754            }
755            TableFactor::NestedJoin(table_reference) => write!(f, "({})", table_reference),
756            TableFactor::MatchRecognize {
757                table,
758                partition_by,
759                order_by,
760                measures,
761                rows_per_match,
762                after_match_skip,
763                pattern,
764                within,
765                subsets,
766                symbols,
767                alias,
768            } => {
769                write!(f, "{} MATCH_RECOGNIZE (", table)?;
770                if !partition_by.is_empty() {
771                    write!(f, "PARTITION BY {} ", display_comma_separated(partition_by))?;
772                }
773                if !order_by.is_empty() {
774                    write!(f, "ORDER BY {} ", display_comma_separated(order_by))?;
775                }
776                if !measures.is_empty() {
777                    write!(f, "MEASURES {} ", display_comma_separated(measures))?;
778                }
779                if let Some(rows_per_match) = rows_per_match {
780                    write!(f, "{} ", rows_per_match)?;
781                }
782                if let Some(after_match_skip) = after_match_skip {
783                    write!(f, "{} ", after_match_skip)?;
784                }
785                write!(f, "PATTERN ({}) ", pattern)?;
786                if let Some(within) = within {
787                    write!(f, "WITHIN {} ", within)?;
788                }
789                if !subsets.is_empty() {
790                    write!(f, "SUBSET {} ", display_comma_separated(subsets))?;
791                }
792                write!(f, "DEFINE {})", display_comma_separated(symbols))?;
793                if let Some(alias) = alias {
794                    write!(f, " AS {}", alias)?;
795                }
796                Ok(())
797            }
798        }
799    }
800}
801
802#[derive(Debug, Clone, PartialEq, Eq, Hash)]
803pub struct TableAlias {
804    pub name: Ident,
805    pub columns: Vec<Ident>,
806}
807
808impl fmt::Display for TableAlias {
809    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
810        write!(f, "{}", self.name)?;
811        if !self.columns.is_empty() {
812            write!(f, " ({})", display_comma_separated(&self.columns))?;
813        }
814        Ok(())
815    }
816}
817
818#[derive(Debug, Clone, PartialEq, Eq, Hash)]
819pub struct Join {
820    pub relation: TableFactor,
821    pub join_operator: JoinOperator,
822}
823
824impl fmt::Display for Join {
825    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
826        fn prefix(constraint: &JoinConstraint) -> &'static str {
827            match constraint {
828                JoinConstraint::Natural => "NATURAL ",
829                _ => "",
830            }
831        }
832        fn suffix(constraint: &'_ JoinConstraint) -> impl fmt::Display + '_ {
833            struct Suffix<'a>(&'a JoinConstraint);
834            impl fmt::Display for Suffix<'_> {
835                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
836                    match self.0 {
837                        JoinConstraint::On(expr) => write!(f, " ON {}", expr),
838                        JoinConstraint::Using(attrs) => {
839                            write!(f, " USING({})", display_comma_separated(attrs))
840                        }
841                        _ => Ok(()),
842                    }
843                }
844            }
845            Suffix(constraint)
846        }
847        let broadcast = if matches!(
848            self.relation,
849            TableFactor::Table {
850                as_of: Some(AsOf::ProcessTimeBroadcast),
851                ..
852            }
853        ) {
854            "BROADCAST "
855        } else {
856            ""
857        };
858        match &self.join_operator {
859            JoinOperator::Inner(constraint) => write!(
860                f,
861                " {}{}JOIN {}{}",
862                prefix(constraint),
863                broadcast,
864                self.relation,
865                suffix(constraint)
866            ),
867            JoinOperator::LeftOuter(constraint) => write!(
868                f,
869                " {}{}LEFT JOIN {}{}",
870                prefix(constraint),
871                broadcast,
872                self.relation,
873                suffix(constraint)
874            ),
875            JoinOperator::RightOuter(constraint) => write!(
876                f,
877                " {}RIGHT JOIN {}{}",
878                prefix(constraint),
879                self.relation,
880                suffix(constraint)
881            ),
882            JoinOperator::FullOuter(constraint) => write!(
883                f,
884                " {}FULL JOIN {}{}",
885                prefix(constraint),
886                self.relation,
887                suffix(constraint)
888            ),
889            JoinOperator::CrossJoin => write!(f, " CROSS JOIN {}", self.relation),
890            JoinOperator::AsOfInner(constraint) => write!(
891                f,
892                " {}ASOF JOIN {}{}",
893                prefix(constraint),
894                self.relation,
895                suffix(constraint)
896            ),
897            JoinOperator::AsOfLeft(constraint) => write!(
898                f,
899                " {}ASOF LEFT JOIN {}{}",
900                prefix(constraint),
901                self.relation,
902                suffix(constraint)
903            ),
904        }
905    }
906}
907
908#[derive(Debug, Clone, PartialEq, Eq, Hash)]
909pub enum JoinOperator {
910    Inner(JoinConstraint),
911    LeftOuter(JoinConstraint),
912    RightOuter(JoinConstraint),
913    FullOuter(JoinConstraint),
914    CrossJoin,
915    AsOfInner(JoinConstraint),
916    AsOfLeft(JoinConstraint),
917}
918
919#[derive(Debug, Clone, PartialEq, Eq, Hash)]
920pub enum JoinConstraint {
921    On(Expr),
922    Using(Vec<Ident>),
923    Natural,
924    None,
925}
926
927/// An `ORDER BY` expression
928#[derive(Debug, Clone, PartialEq, Eq, Hash)]
929pub struct OrderByExpr {
930    pub expr: Expr,
931    /// Optional `ASC` or `DESC`
932    pub asc: Option<bool>,
933    /// Optional `NULLS FIRST` or `NULLS LAST`
934    pub nulls_first: Option<bool>,
935}
936
937impl fmt::Display for OrderByExpr {
938    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
939        write!(f, "{}", self.expr)?;
940        match self.asc {
941            Some(true) => write!(f, " ASC")?,
942            Some(false) => write!(f, " DESC")?,
943            None => (),
944        }
945        match self.nulls_first {
946            Some(true) => write!(f, " NULLS FIRST")?,
947            Some(false) => write!(f, " NULLS LAST")?,
948            None => (),
949        }
950        Ok(())
951    }
952}
953
954#[derive(Debug, Clone, PartialEq, Eq, Hash)]
955pub struct Fetch {
956    pub with_ties: bool,
957    pub quantity: Option<String>,
958}
959
960impl fmt::Display for Fetch {
961    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
962        let extension = if self.with_ties { "WITH TIES" } else { "ONLY" };
963        if let Some(ref quantity) = self.quantity {
964            write!(f, "FETCH FIRST {} ROWS {}", quantity, extension)
965        } else {
966            write!(f, "FETCH FIRST ROWS {}", extension)
967        }
968    }
969}
970
971#[derive(Debug, Clone, PartialEq, Eq, Hash)]
972pub struct Top {
973    /// SQL semantic equivalent of LIMIT but with same structure as FETCH.
974    pub with_ties: bool,
975    pub percent: bool,
976    pub quantity: Option<Expr>,
977}
978
979impl fmt::Display for Top {
980    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
981        let extension = if self.with_ties { " WITH TIES" } else { "" };
982        if let Some(ref quantity) = self.quantity {
983            let percent = if self.percent { " PERCENT" } else { "" };
984            write!(f, "TOP ({}){}{}", quantity, percent, extension)
985        } else {
986            write!(f, "TOP{}", extension)
987        }
988    }
989}
990
991#[derive(Debug, Clone, PartialEq, Eq, Hash)]
992pub struct Values(pub Vec<Vec<Expr>>);
993
994impl fmt::Display for Values {
995    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
996        write!(f, "VALUES ")?;
997        let mut delim = "";
998        for row in &self.0 {
999            write!(f, "{}", delim)?;
1000            delim = ", ";
1001            write!(f, "({})", display_comma_separated(row))?;
1002        }
1003        Ok(())
1004    }
1005}
1006
1007/// A named window definition in the WINDOW clause
1008#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1009pub struct NamedWindow {
1010    pub name: Ident,
1011    pub window_spec: WindowSpec,
1012}
1013
1014impl fmt::Display for NamedWindow {
1015    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1016        write!(f, "{} AS ({})", self.name, self.window_spec)
1017    }
1018}