1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
// Copyright 2018 sqlparser-rs contributors. All rights reserved.
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// This file is derived from the sqlparser-rs project, available at
// https://github.com/andygrove/sqlparser-rs. It was incorporated
// directly into Materialize on December 21, 2019.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file at the
// root of this repository, or online at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt::{self, Debug};
use std::hash::Hash;
use std::mem;

use crate::ast::display::{self, AstDisplay, AstFormatter, WithOptionName};
use crate::ast::{AstInfo, Expr, Function, Ident, ShowStatement, WithOptionValue};

/// The most complete variant of a `SELECT` query expression, optionally
/// including `WITH`, `UNION` / other set operations, and `ORDER BY`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Query<T: AstInfo> {
    /// WITH (common table expressions, or CTEs)
    pub ctes: CteBlock<T>,
    /// SELECT or UNION / EXCEPT / INTERSECT
    pub body: SetExpr<T>,
    /// ORDER BY
    pub order_by: Vec<OrderByExpr<T>>,
    /// `LIMIT { <N> | ALL }`
    /// `FETCH { FIRST | NEXT } <N> { ROW | ROWS } | { ONLY | WITH TIES }`
    pub limit: Option<Limit<T>>,
    /// `OFFSET <N> { ROW | ROWS }`
    pub offset: Option<Expr<T>>,
}

impl<T: AstInfo> AstDisplay for Query<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_node(&self.ctes);
        f.write_node(&self.body);
        if !self.order_by.is_empty() {
            f.write_str(" ORDER BY ");
            f.write_node(&display::comma_separated(&self.order_by));
        }

        let write_offset = |f: &mut AstFormatter<W>| {
            if let Some(offset) = &self.offset {
                f.write_str(" OFFSET ");
                f.write_node(offset);
            }
        };

        if let Some(limit) = &self.limit {
            if limit.with_ties {
                write_offset(f);
                f.write_str(" FETCH FIRST ");
                f.write_node(&limit.quantity);
                f.write_str(" ROWS WITH TIES");
            } else {
                f.write_str(" LIMIT ");
                f.write_node(&limit.quantity);
                write_offset(f);
            }
        } else {
            write_offset(f);
        }
    }
}
impl_display_t!(Query);

impl<T: AstInfo> Query<T> {
    pub fn select(select: Select<T>) -> Query<T> {
        Query {
            ctes: CteBlock::empty(),
            body: SetExpr::Select(Box::new(select)),
            order_by: vec![],
            limit: None,
            offset: None,
        }
    }

    pub fn query(query: Query<T>) -> Query<T> {
        Query {
            ctes: CteBlock::empty(),
            body: SetExpr::Query(Box::new(query)),
            order_by: vec![],
            limit: None,
            offset: None,
        }
    }

    pub fn take(&mut self) -> Query<T> {
        mem::replace(
            self,
            Query::<T> {
                ctes: CteBlock::empty(),
                order_by: vec![],
                body: SetExpr::Values(Values(vec![])),
                limit: None,
                offset: None,
            },
        )
    }
}

/// A node in a tree, representing a "query body" expression, roughly:
/// `SELECT ... [ {UNION|EXCEPT|INTERSECT} SELECT ...]`
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SetExpr<T: AstInfo> {
    /// Restricted SELECT .. FROM .. HAVING (no ORDER BY or set operations)
    Select(Box<Select<T>>),
    /// Parenthesized SELECT subquery, which may include more set operations
    /// in its body and an optional ORDER BY / LIMIT.
    Query(Box<Query<T>>),
    /// UNION/EXCEPT/INTERSECT of two queries
    SetOperation {
        op: SetOperator,
        all: bool,
        left: Box<SetExpr<T>>,
        right: Box<SetExpr<T>>,
    },
    Values(Values<T>),
    Show(ShowStatement<T>),
    Table(T::ItemName),
}

impl<T: AstInfo> AstDisplay for SetExpr<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        match self {
            SetExpr::Select(s) => f.write_node(s),
            SetExpr::Query(q) => {
                f.write_str("(");
                f.write_node(q);
                f.write_str(")")
            }
            SetExpr::Values(v) => f.write_node(v),
            SetExpr::Show(v) => f.write_node(v),
            SetExpr::Table(t) => {
                f.write_str("TABLE ");
                f.write_node(t)
            }
            SetExpr::SetOperation {
                left,
                right,
                op,
                all,
            } => {
                f.write_node(left);
                f.write_str(" ");
                f.write_node(op);
                f.write_str(" ");
                if *all {
                    f.write_str("ALL ");
                }
                f.write_node(right);
            }
        }
    }
}
impl_display_t!(SetExpr);

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SetOperator {
    Union,
    Except,
    Intersect,
}

impl AstDisplay for SetOperator {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_str(match self {
            SetOperator::Union => "UNION",
            SetOperator::Except => "EXCEPT",
            SetOperator::Intersect => "INTERSECT",
        })
    }
}
impl_display!(SetOperator);

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SelectOptionName {
    ExpectedGroupSize,
    AggregateInputGroupSize,
    DistinctOnInputGroupSize,
    LimitInputGroupSize,
}

impl AstDisplay for SelectOptionName {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_str(match self {
            SelectOptionName::ExpectedGroupSize => "EXPECTED GROUP SIZE",
            SelectOptionName::AggregateInputGroupSize => "AGGREGATE INPUT GROUP SIZE",
            SelectOptionName::DistinctOnInputGroupSize => "DISTINCT ON INPUT GROUP SIZE",
            SelectOptionName::LimitInputGroupSize => "LIMIT INPUT GROUP SIZE",
        })
    }
}
impl_display!(SelectOptionName);

impl WithOptionName for SelectOptionName {
    /// # WARNING
    ///
    /// Whenever implementing this trait consider very carefully whether or not
    /// this value could contain sensitive user data. If you're uncertain, err
    /// on the conservative side and return `true`.
    fn redact_value(&self) -> bool {
        match self {
            SelectOptionName::ExpectedGroupSize
            | SelectOptionName::AggregateInputGroupSize
            | SelectOptionName::DistinctOnInputGroupSize
            | SelectOptionName::LimitInputGroupSize => false,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SelectOption<T: AstInfo> {
    pub name: SelectOptionName,
    pub value: Option<WithOptionValue<T>>,
}
impl_display_for_with_option!(SelectOption);

/// A restricted variant of `SELECT` (without CTEs/`ORDER BY`), which may
/// appear either as the only body item of an `SQLQuery`, or as an operand
/// to a set operation like `UNION`.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Select<T: AstInfo> {
    pub distinct: Option<Distinct<T>>,
    /// projection expressions
    pub projection: Vec<SelectItem<T>>,
    /// FROM
    pub from: Vec<TableWithJoins<T>>,
    /// WHERE
    pub selection: Option<Expr<T>>,
    /// GROUP BY
    pub group_by: Vec<Expr<T>>,
    /// HAVING
    pub having: Option<Expr<T>>,
    /// OPTION
    pub options: Vec<SelectOption<T>>,
}

impl<T: AstInfo> AstDisplay for Select<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_str("SELECT");
        if let Some(distinct) = &self.distinct {
            f.write_str(" ");
            f.write_node(distinct);
        }
        if !self.projection.is_empty() {
            f.write_str(" ");
            f.write_node(&display::comma_separated(&self.projection));
        }
        if !self.from.is_empty() {
            f.write_str(" FROM ");
            f.write_node(&display::comma_separated(&self.from));
        }
        if let Some(ref selection) = self.selection {
            f.write_str(" WHERE ");
            f.write_node(selection);
        }
        if !self.group_by.is_empty() {
            f.write_str(" GROUP BY ");
            f.write_node(&display::comma_separated(&self.group_by));
        }
        if let Some(ref having) = self.having {
            f.write_str(" HAVING ");
            f.write_node(having);
        }
        if !self.options.is_empty() {
            f.write_str(" OPTIONS (");
            f.write_node(&display::comma_separated(&self.options));
            f.write_str(")");
        }
    }
}
impl_display_t!(Select);

impl<T: AstInfo> Select<T> {
    pub fn from(mut self, twj: TableWithJoins<T>) -> Select<T> {
        self.from.push(twj);
        self
    }

    pub fn project(mut self, select_item: SelectItem<T>) -> Select<T> {
        self.projection.push(select_item);
        self
    }

    pub fn selection(mut self, selection: Option<Expr<T>>) -> Select<T> {
        self.selection = selection;
        self
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Distinct<T: AstInfo> {
    EntireRow,
    On(Vec<Expr<T>>),
}
impl_display_t!(Distinct);

impl<T: AstInfo> AstDisplay for Distinct<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        match self {
            Distinct::EntireRow => f.write_str("DISTINCT"),
            Distinct::On(cols) => {
                f.write_str("DISTINCT ON (");
                f.write_node(&display::comma_separated(cols));
                f.write_str(")");
            }
        }
    }
}

/// A block of common table expressions (CTEs).
///
/// The block can either be entirely "simple" (traditional SQL `WITH` block),
/// or "mutually recursive", which introduce their bindings before the block
/// and may result in mutually recursive definitions.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum CteBlock<T: AstInfo> {
    Simple(Vec<Cte<T>>),
    MutuallyRecursive(MutRecBlock<T>),
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MutRecBlock<T: AstInfo> {
    pub options: Vec<MutRecBlockOption<T>>,
    pub ctes: Vec<CteMutRec<T>>,
}

impl<T: AstInfo> CteBlock<T> {
    /// Returns an empty (simple) CTE block.
    pub fn empty() -> Self {
        CteBlock::Simple(Vec::new())
    }
    /// True if there are no bindings in the block.
    pub fn is_empty(&self) -> bool {
        match self {
            CteBlock::Simple(list) => list.is_empty(),
            CteBlock::MutuallyRecursive(list) => list.ctes.is_empty(),
        }
    }
    /// Iterates through the identifiers used in bindings.
    pub fn bound_identifiers(&self) -> impl Iterator<Item = &Ident> {
        let mut names = Vec::new();
        match self {
            CteBlock::Simple(list) => {
                for cte in list.iter() {
                    names.push(&cte.alias.name);
                }
            }
            CteBlock::MutuallyRecursive(MutRecBlock { options: _, ctes }) => {
                for cte in ctes.iter() {
                    names.push(&cte.name);
                }
            }
        }
        names.into_iter()
    }
}

impl<T: AstInfo> AstDisplay for CteBlock<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        if !self.is_empty() {
            match self {
                CteBlock::Simple(list) => {
                    f.write_str("WITH ");
                    f.write_node(&display::comma_separated(list));
                }
                CteBlock::MutuallyRecursive(MutRecBlock { options, ctes }) => {
                    f.write_str("WITH MUTUALLY RECURSIVE ");
                    if !options.is_empty() {
                        f.write_str("(");
                        f.write_node(&display::comma_separated(options));
                        f.write_str(") ");
                    }
                    f.write_node(&display::comma_separated(ctes));
                }
            }
            f.write_str(" ");
        }
    }
}

/// A single CTE (used after `WITH`): `alias [(col1, col2, ...)] AS ( query )`
/// The names in the column list before `AS`, when specified, replace the names
/// of the columns returned by the query. The parser does not validate that the
/// number of columns in the query matches the number of columns in the query.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Cte<T: AstInfo> {
    pub alias: TableAlias,
    pub id: T::CteId,
    pub query: Query<T>,
}

impl<T: AstInfo> AstDisplay for Cte<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_node(&self.alias);
        f.write_str(" AS (");
        f.write_node(&self.query);
        f.write_str(")");
    }
}
impl_display_t!(Cte);

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CteMutRec<T: AstInfo> {
    pub name: Ident,
    pub columns: Vec<CteMutRecColumnDef<T>>,
    pub id: T::CteId,
    pub query: Query<T>,
}

impl<T: AstInfo> AstDisplay for CteMutRec<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_node(&self.name);
        if !self.columns.is_empty() {
            f.write_str(" (");
            f.write_node(&display::comma_separated(&self.columns));
            f.write_str(")");
        }
        f.write_str(" AS (");
        f.write_node(&self.query);
        f.write_str(")");
    }
}
impl_display_t!(CteMutRec);

/// A column definition in a [`CteMutRec`].
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CteMutRecColumnDef<T: AstInfo> {
    pub name: Ident,
    pub data_type: T::DataType,
}

impl<T: AstInfo> AstDisplay for CteMutRecColumnDef<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_node(&self.name);
        f.write_str(" ");
        f.write_node(&self.data_type);
    }
}
impl_display_t!(CteMutRecColumnDef);

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum MutRecBlockOptionName {
    RecursionLimit,
    ErrorAtRecursionLimit,
    ReturnAtRecursionLimit,
}

impl AstDisplay for MutRecBlockOptionName {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_str(match self {
            MutRecBlockOptionName::RecursionLimit => "RECURSION LIMIT",
            MutRecBlockOptionName::ErrorAtRecursionLimit => "ERROR AT RECURSION LIMIT",
            MutRecBlockOptionName::ReturnAtRecursionLimit => "RETURN AT RECURSION LIMIT",
        })
    }
}
impl_display!(MutRecBlockOptionName);

impl WithOptionName for MutRecBlockOptionName {
    /// # WARNING
    ///
    /// Whenever implementing this trait consider very carefully whether or not
    /// this value could contain sensitive user data. If you're uncertain, err
    /// on the conservative side and return `true`.
    fn redact_value(&self) -> bool {
        match self {
            MutRecBlockOptionName::RecursionLimit
            | MutRecBlockOptionName::ErrorAtRecursionLimit
            | MutRecBlockOptionName::ReturnAtRecursionLimit => false,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MutRecBlockOption<T: AstInfo> {
    pub name: MutRecBlockOptionName,
    pub value: Option<WithOptionValue<T>>,
}
impl_display_for_with_option!(MutRecBlockOption);

/// One item of the comma-separated list following `SELECT`
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SelectItem<T: AstInfo> {
    /// An expression, optionally followed by `[ AS ] alias`.
    Expr { expr: Expr<T>, alias: Option<Ident> },
    /// An unqualified `*`.
    Wildcard,
}

impl<T: AstInfo> AstDisplay for SelectItem<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        match &self {
            SelectItem::Expr { expr, alias } => {
                f.write_node(expr);
                if let Some(alias) = alias {
                    f.write_str(" AS ");
                    f.write_node(alias);
                }
            }
            SelectItem::Wildcard => f.write_str("*"),
        }
    }
}
impl_display_t!(SelectItem);

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TableWithJoins<T: AstInfo> {
    pub relation: TableFactor<T>,
    pub joins: Vec<Join<T>>,
}

impl<T: AstInfo> AstDisplay for TableWithJoins<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_node(&self.relation);
        for join in &self.joins {
            f.write_node(join)
        }
    }
}
impl_display_t!(TableWithJoins);

impl<T: AstInfo> TableWithJoins<T> {
    pub fn subquery(query: Query<T>, alias: TableAlias) -> TableWithJoins<T> {
        TableWithJoins {
            relation: TableFactor::Derived {
                lateral: false,
                subquery: Box::new(query),
                alias: Some(alias),
            },
            joins: vec![],
        }
    }
}

/// A table name or a parenthesized subquery with an optional alias
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum TableFactor<T: AstInfo> {
    Table {
        name: T::ItemName,
        alias: Option<TableAlias>,
    },
    Function {
        function: Function<T>,
        alias: Option<TableAlias>,
        with_ordinality: bool,
    },
    RowsFrom {
        functions: Vec<Function<T>>,
        alias: Option<TableAlias>,
        with_ordinality: bool,
    },
    Derived {
        lateral: bool,
        subquery: Box<Query<T>>,
        alias: Option<TableAlias>,
    },
    /// Represents a parenthesized join expression, such as
    /// `(foo <JOIN> bar [ <JOIN> baz ... ])`.
    /// The inner `TableWithJoins` can have no joins only if its
    /// `relation` is itself a `TableFactor::NestedJoin`.
    NestedJoin {
        join: Box<TableWithJoins<T>>,
        alias: Option<TableAlias>,
    },
}

impl<T: AstInfo> AstDisplay for TableFactor<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        match self {
            TableFactor::Table { name, alias } => {
                f.write_node(name);
                if let Some(alias) = alias {
                    f.write_str(" AS ");
                    f.write_node(alias);
                }
            }
            TableFactor::Function {
                function,
                alias,
                with_ordinality,
            } => {
                f.write_node(function);
                if let Some(alias) = &alias {
                    f.write_str(" AS ");
                    f.write_node(alias);
                }
                if *with_ordinality {
                    f.write_str(" WITH ORDINALITY");
                }
            }
            TableFactor::RowsFrom {
                functions,
                alias,
                with_ordinality,
            } => {
                f.write_str("ROWS FROM (");
                f.write_node(&display::comma_separated(functions));
                f.write_str(")");
                if let Some(alias) = alias {
                    f.write_str(" AS ");
                    f.write_node(alias);
                }
                if *with_ordinality {
                    f.write_str(" WITH ORDINALITY");
                }
            }
            TableFactor::Derived {
                lateral,
                subquery,
                alias,
            } => {
                if *lateral {
                    f.write_str("LATERAL ");
                }
                f.write_str("(");
                f.write_node(subquery);
                f.write_str(")");
                if let Some(alias) = alias {
                    f.write_str(" AS ");
                    f.write_node(alias);
                }
            }
            TableFactor::NestedJoin { join, alias } => {
                f.write_str("(");
                f.write_node(join);
                f.write_str(")");
                if let Some(alias) = alias {
                    f.write_str(" AS ");
                    f.write_node(alias);
                }
            }
        }
    }
}
impl_display_t!(TableFactor);

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TableAlias {
    pub name: Ident,
    pub columns: Vec<Ident>,
    /// Whether the number of aliased columns must exactly match the number of
    /// columns in the underlying table.
    ///
    /// TODO(benesch): this shouldn't really live in the AST (it's a HIR
    /// concern), but it will have to do for now.
    pub strict: bool,
}

impl AstDisplay for TableAlias {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_node(&self.name);
        if !self.columns.is_empty() {
            f.write_str(" (");
            f.write_node(&display::comma_separated(&self.columns));
            f.write_str(")");
        }
    }
}
impl_display!(TableAlias);

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Join<T: AstInfo> {
    pub relation: TableFactor<T>,
    pub join_operator: JoinOperator<T>,
}

impl<T: AstInfo> AstDisplay for Join<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        fn prefix<T: AstInfo>(constraint: &JoinConstraint<T>) -> &'static str {
            match constraint {
                JoinConstraint::Natural => "NATURAL ",
                _ => "",
            }
        }
        fn suffix<'a, T: AstInfo>(constraint: &'a JoinConstraint<T>) -> impl AstDisplay + 'a {
            struct Suffix<'a, T: AstInfo>(&'a JoinConstraint<T>);
            impl<'a, T: AstInfo> AstDisplay for Suffix<'a, T> {
                fn fmt<W>(&self, f: &mut AstFormatter<W>)
                where
                    W: fmt::Write,
                {
                    match self.0 {
                        JoinConstraint::On(expr) => {
                            f.write_str(" ON ");
                            f.write_node(expr);
                        }
                        JoinConstraint::Using { columns, alias } => {
                            f.write_str(" USING (");
                            f.write_node(&display::comma_separated(columns));
                            f.write_str(")");

                            if let Some(join_using_alias) = alias {
                                f.write_str(" AS ");
                                f.write_node(join_using_alias);
                            }
                        }
                        _ => {}
                    }
                }
            }
            Suffix(constraint)
        }
        match &self.join_operator {
            JoinOperator::Inner(constraint) => {
                f.write_str(" ");
                f.write_str(prefix(constraint));
                f.write_str("JOIN ");
                f.write_node(&self.relation);
                f.write_node(&suffix(constraint));
            }
            JoinOperator::LeftOuter(constraint) => {
                f.write_str(" ");
                f.write_str(prefix(constraint));
                f.write_str("LEFT JOIN ");
                f.write_node(&self.relation);
                f.write_node(&suffix(constraint));
            }
            JoinOperator::RightOuter(constraint) => {
                f.write_str(" ");
                f.write_str(prefix(constraint));
                f.write_str("RIGHT JOIN ");
                f.write_node(&self.relation);
                f.write_node(&suffix(constraint));
            }
            JoinOperator::FullOuter(constraint) => {
                f.write_str(" ");
                f.write_str(prefix(constraint));
                f.write_str("FULL JOIN ");
                f.write_node(&self.relation);
                f.write_node(&suffix(constraint));
            }
            JoinOperator::CrossJoin => {
                f.write_str(" CROSS JOIN ");
                f.write_node(&self.relation);
            }
        }
    }
}
impl_display_t!(Join);

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum JoinOperator<T: AstInfo> {
    Inner(JoinConstraint<T>),
    LeftOuter(JoinConstraint<T>),
    RightOuter(JoinConstraint<T>),
    FullOuter(JoinConstraint<T>),
    CrossJoin,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum JoinConstraint<T: AstInfo> {
    On(Expr<T>),
    Using {
        columns: Vec<Ident>,
        alias: Option<Ident>,
    },
    Natural,
}

/// SQL ORDER BY expression
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct OrderByExpr<T: AstInfo> {
    pub expr: Expr<T>,
    pub asc: Option<bool>,
    pub nulls_last: Option<bool>,
}

impl<T: AstInfo> AstDisplay for OrderByExpr<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_node(&self.expr);
        match self.asc {
            Some(true) => f.write_str(" ASC"),
            Some(false) => f.write_str(" DESC"),
            None => {}
        }
        match self.nulls_last {
            Some(true) => f.write_str(" NULLS LAST"),
            Some(false) => f.write_str(" NULLS FIRST"),
            None => {}
        }
    }
}
impl_display_t!(OrderByExpr);

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Limit<T: AstInfo> {
    pub with_ties: bool,
    pub quantity: Expr<T>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Values<T: AstInfo>(pub Vec<Vec<Expr<T>>>);

impl<T: AstInfo> AstDisplay for Values<T> {
    fn fmt<W: fmt::Write>(&self, f: &mut AstFormatter<W>) {
        f.write_str("VALUES ");
        let mut delim = "";
        for row in &self.0 {
            f.write_str(delim);
            delim = ", ";
            f.write_str("(");
            f.write_node(&display::comma_separated(row));
            f.write_str(")");
        }
    }
}
impl_display_t!(Values);