orql 0.1.0

A toy SQL parser for a subset of the Oracle dialect.
Documentation
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
use super::{Error, MetaTracker, ParserInner, Result};
use crate::{
    ast::{
        AliasedQueryTable, ApplyJoinTable, ApplyTableJoin, AsAlias, ComposeOperation,
        ComposeOperator, ContainersTable, CrossInnerJoinedTable, CteSubQuery, CteTable, Duplicates,
        Expr, GroupBy, GroupByExprs, GroupByType, HavingCondition, Ident, Identifier,
        InnerJoinedTable, InnerTableJoin, NaturalInnerJoinedTable, Node, OuterJoinCondition,
        OuterTableJoin, ProjectionItem, ProjectionWildcard, QueryBlock, QueryBody, QuerySelect,
        QueryTable, QueryTableAlias, QueryTableExpression, QueryTableType, QueryTableWithJoins,
        QueryTables, QueryWindow, QueryWindows, ShardsTable, SubQuery, TableCollection, TableJoin,
        WhereCondition, With,
    },
    parser::{
        OpenedParen,
        condition::ParseConditionContext,
        expression::{ParseCaseIdent, ParseExprContext},
        parse_comma_separated, parse_opened_parens, parse_parens,
        window::WindowSpecMode,
    },
    scanner::{Keyword, Reserved, Token, TokenType},
};

impl<'s, M> ParserInner<'s, M>
where
    M: MetaTracker<'s>,
{
    pub(super) fn parse_query_body(&mut self) -> Result<QueryBody<'s, M::NodeId>> {
        let mut block = self.parse_query_block()?;
        // "[..] All set operators have equal precedence. If a SQL statement
        // contains multiple set operators, then Oracle Database evaluates
        // them from the left to right unless parentheses explicitly specify
        // another order. [..]"
        // <https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/The-UNION-ALL-INTERSECT-MINUS-Operators.html>:
        while let Some(Token {
            ttype: TokenType::Keyword(kw),
            loc: kw_loc,
        }) = self.peek_token()?
        {
            let op = match kw {
                Keyword::UNION => ComposeOperation::Union,
                Keyword::INTERSECT => ComposeOperation::Intersect,
                Keyword::MINUS => ComposeOperation::Minus,
                Keyword::EXCEPT => ComposeOperation::Except,
                _ => break,
            };
            let operation = {
                let loc = *kw_loc;
                self.next_token()?; // ~ consume the peeked keyword
                Node(op, self.meta_tracker.on_node_start(loc))
            };
            let all_token = if matches!(
                self.peek_token()?,
                Some(Token {
                    ttype: TokenType::Keyword(Keyword::ALL),
                    ..
                })
            ) {
                let_next_token!(self, Token { ttype: _, loc });
                Some(Node((), self.meta_tracker.on_node_start(loc)))
            } else {
                None
            };

            let right = self.parse_query_block()?;
            block = QueryBlock::Composed(
                block.into(),
                ComposeOperator {
                    operation,
                    all_token,
                },
                right.into(),
            );
        }
        let order_by = self.parse_order_by()?;
        let row_limit = self.parse_row_limit(if order_by.is_some() {
            None
        } else {
            block_table_alias_mut_if_last_token(&mut block)
        })?;
        Ok(QueryBody {
            block,
            order_by,
            row_limit,
        })
    }

    /// Parse a `WITH ...` block with all CTEs including
    pub(super) fn parse_query_with(&mut self) -> Result<Option<With<'s, M::NodeId>>> {
        if let Some(Token {
            ttype: TokenType::Keyword(Keyword::WITH),
            loc,
        }) = self.peek_token()?
        {
            let t_loc = *loc;
            self.consume_token()?;
            Ok(Some(With {
                with_keyword: Node((), self.meta_tracker.on_node_start(t_loc)),
                ctes: parse_comma_separated(self, |parser| parser.parse_query_with_cte())?,
            }))
        } else {
            Ok(None)
        }
    }

    /// Parses a single CTE, ie. [`subquery_factoring_clause` or `subav_factoring_clause`](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/SELECT.html#GUID-CFA006CA-6FF1-4972-821E-6996142A51C6__BABFAFID)
    fn parse_query_with_cte(&mut self) -> Result<CteTable<'s, M::NodeId>> {
        // XXX subav_factoring_clause

        // ~ assuming a subquery_factoring_clause as of here
        let name = expect_token!(|t = self.next_token() | "an identifier" match {
            TokenType::Identifier(ident, _) => Node(ident, self.meta_tracker.on_node_start(t.loc)),
        });
        // ~ are there any column aliases
        let column_aliases = if let Some(Token {
            ttype: TokenType::LeftParen,
            ..
        }) = self.peek_token()?
        {
            let_next_token!(self, opened_paren);
            parse_opened_parens(self, opened_paren.into(), |parser, node_id| {
                let aliases = parse_comma_separated(parser, |parser| {
                    expect_token!(|t = parser.next_token()| "an identifier" match {
                        TokenType::Identifier(ident, _) => {
                            Ok(Node(ident, parser.meta_tracker.on_node_start(t.loc)))
                        }
                    })
                })?;
                Ok(Some(Node(aliases, node_id)))
            })?
        } else {
            None
        };
        let as_token = expect_token!(|t = self.next_token()| "the AS keyword" match {
            TokenType::Keyword(Keyword::AS) => Node((), self.meta_tracker.on_node_start(t.loc)),
        });
        let query = expect_token!(|t = self.next_token()| "an opening parenthesis" match {
            TokenType::LeftParen => {
                parse_opened_parens(self, t.into(), |parser, node_id| {
                    Ok(Node(parser.parse_query_body()?.into(), node_id))
                })
            }
        })?;
        // XXX search_clause
        // XXX cycle_clause
        Ok(CteTable::SubQuery(CteSubQuery {
            name,
            column_aliases,
            as_token,
            query,
        }))
    }

    fn parse_query_block(&mut self) -> Result<QueryBlock<'s, M::NodeId>> {
        expect_token!(
        |t = self.next_token()| "a query block" match {
            TokenType::LeftParen => parse_opened_parens(self, t.into(), |parser, node_id| {
                Ok(QueryBlock::Nested(Node(parser.parse_query_body()?.into(), node_id)))
            }),
            TokenType::Keyword(Keyword::SELECT) => {
                Ok(QueryBlock::Select(self.parse_query_select(t)?))
            }
        })
    }

    fn parse_query_select(
        &mut self,
        select_token: Token<'s>,
    ) -> Result<QuerySelect<'s, M::NodeId>> {
        let select_token_id = self.meta_tracker.on_node_start(select_token.loc);
        // ~ query optimizer hint
        let hint = self.parse_hint()?;
        // ~ distinct / unique / all
        let filter_token = self.parse_query_duplicates()?;
        let projection = self.parse_query_projection()?;
        let from = self.parse_query_tables()?;

        let mut query_select = QuerySelect {
            select_token: Node((), select_token_id),
            hint,
            duplicates: filter_token,
            projection,
            from,
            selection: None,
            group_by: None,
            windows: None,
        };
        query_select.selection = self.parse_where_condition()?;
        // XXX connect by
        query_select.group_by = self.parse_group_by()?;
        // XXX model_clause (Note: You cannot use the model_clause with window_clause; https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/SELECT.html#GUID-CFA006CA-6FF1-4972-821E-6996142A51C6__GUID-1B520407-DD06-4568-8E64-25F90F4C0B59)
        query_select.windows =
            self.parse_query_windows(query_select_alias_mut_if_last_token(&mut query_select))?;
        Ok(query_select)
    }

    fn parse_query_projection(&mut self) -> Result<Vec<ProjectionItem<'s, M::NodeId>>> {
        let mut items = Vec::new();
        items.push(self.parse_query_projection_item()?);
        while let Some(Token {
            ttype: TokenType::Comma,
            ..
        }) = self.peek_token()?
        {
            self.consume_token()?;
            self.meta_tracker.on_node_end();
            items.push(self.parse_query_projection_item()?);
        }
        if items.is_empty() {
            if let Some(t) = self.peek_token()? {
                Err(Error::unexpected_token(t, "at least one projection item"))
            } else {
                unexpected_eof_err!(self, "at least one projection item")
            }
        } else {
            Ok(items)
        }
    }

    fn parse_query_projection_item(&mut self) -> Result<ProjectionItem<'s, M::NodeId>> {
        let (expr, mut ctx) = expect_token!(|t = self.peek_token()| "a projection item" match {
            TokenType::Star => {
                let loc = t.loc;
                self.consume_token()?;
                let wildcard = Node((), self.meta_tracker.on_node_start(loc));
                return Ok(ProjectionItem::Wildcard(ProjectionWildcard::Simple(wildcard)));
            }
            TokenType::Identifier(_, _) => {
                let_next_token!(self, Token { ttype: TokenType::Identifier(ident, reserved), loc });
                match reserved {
                    Some(Reserved::CASE) => {
                        let case_ident = Node(ident, self.meta_tracker.on_node_start(loc));
                        let mut parser = self.expr_parser().with_context(ParseExprContext::for_projection_item());
                        match parser.parse_case_ident(case_ident)? {
                            ParseCaseIdent::Ident(ident) => {
                                // ~ it was not a case_expr, maybe it's a `case.*`?
                                if parser.context().has_left_over_ident() {
                                    (
                                        Expr::Identifier(Identifier::Simple(ident)),
                                        parser.into_context()
                                    )
                                } else {
                                    match self.parse_identifier_or_wildcard(ident)? {
                                        IdentifierOrWildcard::Wildcard(wildcard) => {
                                            return Ok(ProjectionItem::Wildcard(wildcard));
                                        }
                                        IdentifierOrWildcard::Identifier(ident) => {
                                            // ~ maybe it's a compound identifier
                                            // or a function call following by
                                            // something to make an expression
                                            // starting with the identifier `case`
                                            // .. oh, my!
                                            let mut parser = self.expr_parser().with_context(ParseExprContext::for_projection_item());
                                            (parser.parse_with_identifier(ident, loc)?, parser.into_context())
                                        }
                                    }
                                }
                            }
                            ParseCaseIdent::Expr(expr) => {
                                (expr, parser.into_context())
                            }
                        }
                    }
                    _ => {
                        let ident = Node(ident, self.meta_tracker.on_node_start(loc));
                        match self.parse_identifier_or_wildcard(ident)? {
                            IdentifierOrWildcard::Wildcard(wildcard) => {
                                return Ok(ProjectionItem::Wildcard(wildcard));
                            }
                            IdentifierOrWildcard::Identifier(ident) => {
                                let mut parser = self.expr_parser().with_context(ParseExprContext::for_projection_item());
                                (parser.parse_with_identifier(ident, loc)?, parser.into_context())
                            }
                        }
                    }
                }
            }
            _ => {
                let mut parser = self.expr_parser().with_context(ParseExprContext::for_projection_item());
                let expr = parser.parse()?;
                (expr, parser.into_context())
            }
        });
        let alias = match ctx.take_left_over_ident().map(|ident| AsAlias {
            as_token: None,
            name: Some(ident),
        }) {
            Some(alias) => Some(alias),
            None => self.parse_projection_item_alias()?,
        };
        Ok(ProjectionItem::Expr(expr, alias))
    }

    fn parse_projection_item_alias(&mut self) -> Result<Option<AsAlias<'s, M::NodeId>>> {
        // ~ as strange as it is, Oracle makes the name after the AS keyword
        // optional; that makes this following impl rather straight forward
        let as_token = if let Some(Token {
            ttype: TokenType::Keyword(Keyword::AS),
            loc,
        }) = self.peek_token()?
        {
            let loc = *loc;
            self.consume_token()?; // ~ consume the "AS" keyword
            Some(Node((), self.meta_tracker.on_node_start(loc)))
        } else {
            None
        };
        let name = if matches!(
            self.peek_token()?,
            Some(Token {
                ttype: TokenType::Identifier(_, _),
                ..
            })
        ) {
            let_next_token!(
                self,
                Token {
                    ttype: TokenType::Identifier(ident, _),
                    loc,
                }
            );
            Some(Node(ident, self.meta_tracker.on_node_start(loc)))
        } else {
            None
        };
        Ok(match (as_token, name) {
            (None, None) => None,
            (as_token, name) => Some(AsAlias { as_token, name }),
        })
    }

    fn parse_identifier_or_wildcard(
        &mut self,
        init_ident: Node<Ident<'s>, M::NodeId>,
    ) -> Result<IdentifierOrWildcard<'s, M::NodeId>> {
        if !matches!(
            self.peek_token()?,
            Some(Token {
                ttype: TokenType::Dot,
                ..
            })
        ) {
            // ~ simple identifier followed by something
            return Ok(IdentifierOrWildcard::Identifier(Identifier::Simple(
                init_ident,
            )));
        }
        // ~ consume the DOT
        self.consume_token()?;
        self.meta_tracker.on_node_end();
        let (next_ident, next_ident_id) = expect_token! {
            |t = self.peek_token()| "an asterisk or identifier" match {
                // ~ qualified wildcard via simple ident
                TokenType::Star => {
                    let loc = t.loc;
                    self.consume_token()?;
                    let star_id = self.meta_tracker.on_node_start(loc);
                    return Ok(IdentifierOrWildcard::Wildcard(
                        ProjectionWildcard::Qualified(
                            Identifier::Simple(init_ident),
                            Node((), star_id))));
                }
                // ~ continue parsing below
                TokenType::Identifier(_, _) => {
                    let_next_token!(self, Token { ttype: TokenType::Identifier(ident, _), loc });
                    (ident, self.meta_tracker.on_node_start(loc))
                }
            }
        };
        // ~ qualified identifier or qualified wildcard
        let mut idents = Vec::with_capacity(3);
        idents.push(init_ident);
        idents.push(Node(next_ident, next_ident_id));
        while let Some(Token {
            ttype: TokenType::Dot,
            ..
        }) = self.peek_token()?
        {
            // ~ consume the DOT
            self.consume_token()?;
            self.meta_tracker.on_node_end();
            // ~ see what's next
            expect_token! {
                |t = self.next_token()| "an asterisk or identifier" match {
                    TokenType::Star => return Ok(
                        IdentifierOrWildcard::Wildcard(
                            ProjectionWildcard::Qualified(
                                Identifier::Qualified(idents),
                                Node((), self.meta_tracker.on_node_start(t.loc))))),
                    TokenType::Identifier(ident, _) => {
                        idents.push(Node(ident, self.meta_tracker.on_node_start(t.loc)));
                    }
                }
            };
        }
        Ok(IdentifierOrWildcard::Identifier(Identifier::Qualified(
            idents,
        )))
    }

    /// Parses `DISTINCT | UNIQUE | ALL`
    fn parse_query_duplicates(&mut self) -> Result<Option<Node<Duplicates, M::NodeId>>> {
        if let Some(t) = self.peek_token()? {
            let filter = match t.ttype {
                TokenType::Keyword(Keyword::DISTINCT) => Duplicates::Distinct,
                TokenType::Keyword(Keyword::UNIQUE) => Duplicates::Unique,
                TokenType::Keyword(Keyword::ALL) => Duplicates::All,
                _ => return Ok(None),
            };
            let loc = t.loc;
            self.consume_token()?;
            Ok(Some(Node(filter, self.meta_tracker.on_node_start(loc))))
        } else {
            Ok(None)
        }
    }

    /// Parses `FROM ...`
    fn parse_query_tables(&mut self) -> Result<QueryTables<'s, M::NodeId>> {
        let from_token = expect_token! {
            |t = self.next_token()| "FROM" match {
                TokenType::Keyword(Keyword::FROM) => Node((), self.meta_tracker.on_node_start(t.loc)),
            }
        };
        let mut tables = Vec::new();
        tables.push(self.parse_query_table()?);
        while let Some(Token {
            ttype: TokenType::Comma,
            ..
        }) = self.peek_token()?
        {
            self.consume_token()?;
            self.meta_tracker.on_node_end();
            tables.push(self.parse_query_table()?);
        }
        Ok(QueryTables { from_token, tables })
    }

    /// Parses a "table reference" with an optional "join_clause"
    ///
    /// See <https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/SELECT.html#GUID-CFA006CA-6FF1-4972-821E-6996142A51C6__I2126863>
    /// and <https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/SELECT.html#GUID-CFA006CA-6FF1-4972-821E-6996142A51C6__CHDIJFDJ>
    fn parse_query_table(&mut self) -> Result<QueryTable<'s, M::NodeId>> {
        // XXX InlineAnalyticalView (without joins)

        let mut table = self.parse_aliased_query_table()?;
        let mut joins = Vec::<TableJoin<_>>::new();

        // ~ the alias of the last table expression may actually be one of the
        // reserved words for the join. if it was such a word and together
        // with the token following it would parse as a join clause, steel the
        // alias; this is how oracle appears to behave.
        // ~ the benefit of this cumbersome trick is that we're then OK with
        // only one lookahead token.
        let mut last_alias = Some(&mut table.alias);
        while let Some(join) = self.parse_query_join(last_alias)? {
            joins.push(join);
            last_alias = joins
                .last_mut()
                .and_then(join_table_alias_mut_if_last_token);
        }
        Ok(QueryTable::Table(QueryTableWithJoins { table, joins }))
    }

    /// Parses a `<table-expression> [<alias>]`.
    pub(super) fn parse_aliased_query_table(&mut self) -> Result<AliasedQueryTable<'s, M::NodeId>> {
        let first_token =
            expect_token! { |t = self.next_token()| "a QUERY table" match { _ => t } };
        let first_token_id = self.meta_tracker.on_node_start(first_token.loc);

        let table = match first_token.ttype {
            TokenType::LeftParen => {
                parse_opened_parens(
                    self,
                    OpenedParen::NodeId(first_token_id),
                    |parser, node_id| {
                        if parser.can_parse_query()? {
                            Ok(QueryTableType::Expr(QueryTableExpression::SubQuery(
                                SubQuery {
                                    lateral_token: None,
                                    query: Node(parser.parse_query()?.into(), node_id),
                                },
                            )))
                        } else {
                            // ~ this is not stricly correct due to us
                            // accepting an alias afterwards; oracle, however,
                            // would reject the alias if it already found one
                            // within the nested query table expression
                            let nested = parser.parse_query_table()?;
                            Ok(QueryTableType::Nested(Node(nested.into(), node_id)))
                        }
                    },
                )?
            }
            TokenType::Identifier(_, reserved) => {
                let next_is_paren = matches!(
                    self.peek_token()?,
                    Some(Token {
                        ttype: TokenType::LeftParen,
                        ..
                    })
                );
                if next_is_paren && let Some(reserved) = reserved {
                    match reserved {
                        Reserved::ONLY => parse_parens(self, |parser, node_id| {
                            Ok(QueryTableType::Only {
                                only_token: Node((), first_token_id),
                                expression: Node(
                                    parser.parse_query_table_expression(None)?,
                                    node_id,
                                ),
                            })
                        })?,
                        Reserved::CONTAINERS => parse_parens(self, |parser, node_id| {
                            let ident = parser.parse_identifier()?;
                            Ok(QueryTableType::Containers(ContainersTable {
                                containers_token: Node((), first_token_id),
                                table: Node(ident, node_id),
                            }))
                        })?,
                        Reserved::SHARDS => parse_parens(self, |parser, node_id| {
                            let ident = parser.parse_identifier()?;
                            Ok(QueryTableType::Shards(ShardsTable {
                                shards_token: Node((), first_token_id),
                                table: Node(ident, node_id),
                            }))
                        })?,
                        _ => {
                            // ~ normal expression
                            QueryTableType::Expr(self.parse_query_table_expression(Some(Node(
                                first_token,
                                first_token_id,
                            )))?)
                        }
                    }
                } else {
                    // ~ normal expression
                    QueryTableType::Expr(
                        self.parse_query_table_expression(Some(Node(first_token, first_token_id)))?,
                    )
                }
            }
            TokenType::Keyword(Keyword::TABLE) => QueryTableType::Expr(
                self.parse_query_table_expression(Some(Node(first_token, first_token_id)))?,
            ),
            _ => {
                return Err(Error::unexpected_token(
                    first_token,
                    "an opening parenthesis or an identifier",
                ));
            }
        };
        let alias = if let Some(Token {
            ttype: TokenType::Identifier(_, _),
            ..
        }) = self.peek_token()?
        {
            Some(self.parse_ident()?)
        } else {
            None
        };
        Ok(AliasedQueryTable { table, alias })
    }

    fn parse_query_table_expression(
        &mut self,
        token: Option<Node<Token<'s>, M::NodeId>>,
    ) -> Result<QueryTableExpression<'s, M::NodeId>> {
        let Node(token, token_id) = if let Some(token_node) = token {
            token_node
        } else {
            let t = self
                .next_token()
                .transpose()
                .unwrap_or_else(|| unexpected_eof_err!(self, "a query table expression"))?;
            let t_id = self.meta_tracker.on_node_start(t.loc);
            Node(t, t_id)
        };
        match token.ttype {
            TokenType::Keyword(Keyword::TABLE) => {
                let collection = parse_parens(self, |parser, node_id| {
                    Ok(Node(parser.parse_expr()?, node_id))
                })?;
                let as_outer_join = if let Some(Token {
                    ttype: TokenType::LeftParen,
                    ..
                }) = self.peek_token()?
                {
                    Some(parse_parens(self, |parser, node_id| {
                        expect_token!(|t = parser.next_token()| "a PLUS symbol" match {
                            TokenType::Plus => Ok(Node(Node((), parser.meta_tracker.on_node_start(t.loc)), node_id))
                        })
                    })?)
                } else {
                    None
                };
                Ok(QueryTableExpression::Table(TableCollection {
                    table_token: Node((), token_id),
                    expr: collection,
                    as_outer_join,
                }))
            }
            TokenType::Identifier(ident, reserved) => {
                if let Some(Reserved::LATERAL) = reserved {
                    parse_parens(self, |parser, node_id| {
                        Ok(QueryTableExpression::SubQuery(SubQuery {
                            lateral_token: Some(Node((), token_id)),
                            query: Node(parser.parse_query()?.into(), node_id),
                        }))
                    })
                } else {
                    let name = self.parse_identifier_(Node(ident, token_id))?;
                    Ok(QueryTableExpression::Name(name))
                }
            }
            TokenType::LeftParen => {
                parse_opened_parens(self, OpenedParen::NodeId(token_id), |parser, node_id| {
                    Ok(QueryTableExpression::SubQuery(SubQuery {
                        lateral_token: None,
                        query: Node(parser.parse_query()?.into(), node_id),
                    }))
                })
            }
            // XXX see <https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/SELECT.html#GUID-CFA006CA-6FF1-4972-821E-6996142A51C6__I2126073>
            _ => Err(Error::unexpected_token(
                token,
                "an identifier or a sub-query",
            )),
        }
    }

    fn parse_where_condition(&mut self) -> Result<Option<WhereCondition<'s, M::NodeId>>> {
        if let Some(Token {
            ttype: TokenType::Keyword(Keyword::WHERE),
            loc,
        }) = self.peek_token()?
        {
            let loc = *loc;
            let where_id = self.meta_tracker.on_node_start(loc);
            self.consume_token()?;
            let condition = self.condition_parser().parse_condition()?;
            Ok(Some(WhereCondition {
                where_token: Node((), where_id),
                condition,
            }))
        } else {
            Ok(None)
        }
    }

    fn parse_group_by(&mut self) -> Result<Option<GroupBy<'s, M::NodeId>>> {
        if let Some(Token {
            ttype: TokenType::Keyword(Keyword::GROUP),
            loc,
        }) = self.peek_token()?
        {
            let group_token = {
                let loc = *loc;
                self.consume_token()?;
                Node((), self.meta_tracker.on_node_start(loc))
            };
            let by_token = expect_token!(|t = self.next_token()| "the BY keyword" match {
                TokenType::Keyword(Keyword::BY) => Node((), self.meta_tracker.on_node_start(t.loc)),
            });
            // XXX ROLLUP / CUBE
            // XXX GROUPING SETS
            let group_type = GroupByType::Exprs(
                if let Some(Token {
                    ttype: TokenType::LeftParen,
                    ..
                }) = self.peek_token()?
                {
                    let paren_token = self.next_token()?.expect("missing token");
                    parse_opened_parens(self, paren_token.into(), |parser, node_id| {
                        if let Some(Token {
                            ttype: TokenType::RightParen,
                            loc: right_paren_loc,
                        }) = parser.peek_token()?
                        {
                            // ~ we use the closing paren as an anchor for
                            // comments within the empty list; we start a node
                            // on the right paren (associating it with
                            // preceeding comments) and immediately end it,
                            // meaning to _not_ associated succeeding comments
                            // with it
                            let right_paren_loc = *right_paren_loc;
                            let right_paren_id = parser.meta_tracker.on_node_start(right_paren_loc);
                            parser.meta_tracker.on_node_end();
                            Ok(GroupByExprs::All(Node(Node((), right_paren_id), node_id)))
                        } else {
                            Ok(GroupByExprs::Nested(Node(
                                parse_comma_separated(parser, |parser| parser.parse_expr())?,
                                node_id,
                            )))
                        }
                    })?
                } else {
                    GroupByExprs::Exprs(parse_comma_separated(self, |parser| parser.parse_expr())?)
                },
            );
            let having = if let Some(Token {
                ttype: TokenType::Keyword(Keyword::HAVING),
                ..
            }) = self.peek_token()?
            {
                let having_token = self.next_token()?.expect("missing token");
                let having_token = Node((), self.meta_tracker.on_node_start(having_token.loc));
                let condition = self
                    .condition_parser()
                    .with_context(ParseConditionContext::ForHaving)
                    .parse_condition()?;
                Some(HavingCondition {
                    having_token,
                    condition,
                })
            } else {
                None
            };
            Ok(Some(GroupBy {
                group_token,
                by_token,
                group_type,
                having,
            }))
        } else {
            Ok(None)
        }
    }

    fn parse_query_windows<'a>(
        &mut self,
        steal_alias_if_needed: Option<&'a mut QueryTableAlias<'s, M::NodeId>>,
    ) -> Result<Option<QueryWindows<'s, M::NodeId>>> {
        let window_token = if let Some(Token {
            ttype: TokenType::Identifier(_, maybe_reserved),
            loc,
        }) = self.peek_token()?
        {
            if let Some(Reserved::WINDOW) = *maybe_reserved {
                let loc = *loc;
                self.consume_token()?;
                Node((), self.meta_tracker.on_node_start(loc))
            } else if let Some(steal_alias_if_needed) = steal_alias_if_needed
                && let Some(Node(alias, _)) = steal_alias_if_needed
                && Reserved::WINDOW.matches(alias)
            {
                // ~ wrt expect: we just verified about it's `Some(..)`
                let Node(_, alias_id) = steal_alias_if_needed.take().expect("missing alias");
                Node((), alias_id)
            } else {
                return Ok(None);
            }
        } else {
            return Ok(None);
        };
        let mut windows = Vec::new();
        loop {
            let name = self.parse_ident()?;
            let as_token = expect_token!(|t = self.next_token()| "the AS keyword" match {
                TokenType::Keyword(Keyword::AS) => Node((), self.meta_tracker.on_node_start(t.loc)),
            });
            let window = self.parse_window_spec(WindowSpecMode::Query)?;
            windows.push(QueryWindow {
                name,
                as_token,
                window,
            });

            if let Some(Token {
                ttype: TokenType::Comma,
                ..
            }) = self.peek_token()?
            {
                self.consume_token()?;
                self.meta_tracker.on_node_end();
            } else {
                break;
            }
        }
        Ok(Some(QueryWindows {
            window_token,
            windows,
        }))
    }
}

/// Return value of [ParserInner::parse_identifier_or_wildcard]
enum IdentifierOrWildcard<'s, ID> {
    Identifier(Identifier<'s, ID>),
    Wildcard(ProjectionWildcard<'s, ID>),
}

/// Gets a mutable reference to the join table reference's alias (if any)
/// if and only if it was the last token of the (join) clause.
fn join_table_alias_mut_if_last_token<'j, 's, ID>(
    join: &'j mut TableJoin<'s, ID>,
) -> Option<&'j mut QueryTableAlias<'s, ID>> {
    match join {
        // ~ inner joins are always followed by a condition, hence, the
        // table alias cannot be the last token in the clause
        TableJoin::Inner(InnerTableJoin::Inner(InnerJoinedTable { .. })) => None,
        TableJoin::Inner(InnerTableJoin::Cross(CrossInnerJoinedTable {
            cross_token: _,
            join_token: _,
            table,
        })) => Some(&mut table.alias),
        TableJoin::Inner(InnerTableJoin::Natural(NaturalInnerJoinedTable {
            natural_token: _,
            inner_token: _,
            join_token: _,
            table,
        })) => Some(&mut table.alias),
        TableJoin::Outer(OuterTableJoin {
            type_token: _,
            outer_token: _,
            join_token: _,
            table,
            partition_by,
            condition,
        }) => {
            if partition_by.is_some() {
                None
            } else {
                match condition {
                    OuterJoinCondition::Natural { .. } => Some(&mut table.alias),
                    OuterJoinCondition::Regular(None) => Some(&mut table.alias),
                    OuterJoinCondition::Regular(Some(_)) => None,
                }
            }
        }
        TableJoin::Apply(ApplyTableJoin { table, .. }) => match table {
            ApplyJoinTable::Table(table) => Some(&mut table.alias),
            ApplyJoinTable::Expr(_) => None,
        },
    }
}

fn block_table_alias_mut_if_last_token<'b, 's, ID>(
    mut block: &'b mut QueryBlock<'s, ID>,
) -> Option<&'b mut QueryTableAlias<'s, ID>> {
    let last_block = loop {
        match block {
            QueryBlock::Nested(_) => {
                return None;
            }
            QueryBlock::Composed(_, _, last) => {
                block = &mut **last;
            }
            QueryBlock::Select(_) => break block,
        }
    };
    if let QueryBlock::Select(query_select) = last_block {
        query_select_alias_mut_if_last_token(query_select)
    } else {
        None
    }
}

fn query_select_alias_mut_if_last_token<'b, 's, ID>(
    query_select: &'b mut QuerySelect<'s, ID>,
) -> Option<&'b mut QueryTableAlias<'s, ID>> {
    let QuerySelect {
        select_token: _,
        hint: _,
        duplicates: _,
        projection: _,
        from,
        selection,
        group_by,
        windows,
    } = query_select;
    if selection.is_none()
        && group_by.is_none()
        && windows.is_none()
        && let Some(t) = from.tables.last_mut()
    {
        match t {
            QueryTable::Table(table_with_joins) => {
                if let Some(join) = table_with_joins.joins.last_mut() {
                    join_table_alias_mut_if_last_token(join)
                } else {
                    Some(&mut table_with_joins.table.alias)
                }
            }
        }
    } else {
        None
    }
}