Skip to main content

kumosql_sql/
parser.rs

1//! Recursive-descent parser for GoogleSQL (BigQuery) statements, queries and expressions.
2//!
3//! Expressions use precedence climbing with BigQuery's operator precedence. Statements the AST
4//! does not model (`GRANT`, `CREATE MODEL`, ...) parse to [`Statement::Raw`] holding their text;
5//! a statement the parser does model but cannot read is an error.
6
7use crate::ast::*;
8use crate::error::{Result, SqlError};
9use crate::token::{is_reserved_keyword, tokenize, Punct, Span, Token, TokenKind};
10use serde::{Deserialize, Serialize};
11
12const MAX_DEPTH: usize = 200;
13
14/// What a significant token turned out to be, as the parser read it. Used by the formatter to
15/// change the case of keywords, function names, type names and literals only.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
17pub enum TokenRole {
18    Keyword,
19    Function,
20    Type,
21    /// `NULL`, `TRUE`, `FALSE`
22    Literal,
23    Identifier,
24    Other,
25}
26
27/// Statements with the tokens they were read from.
28#[derive(Debug, Clone)]
29pub struct ParsedScript {
30    pub statements: Vec<Statement>,
31    /// The significant tokens.
32    pub tokens: Vec<Token>,
33    /// The role of each significant token.
34    pub roles: Vec<TokenRole>,
35    /// The source span of each statement (without its semicolon).
36    pub spans: Vec<Span>,
37}
38
39/// Parse every statement of `sql` (separated by semicolons; a trailing one is optional).
40pub fn parse_statements(sql: &str) -> Result<Vec<Statement>> {
41    Ok(parse_script(sql)?.statements)
42}
43
44/// Parse `sql` keeping its tokens, their roles and each statement's span.
45pub fn parse_script(sql: &str) -> Result<ParsedScript> {
46    let tokens = tokenize(sql)?;
47    let mut parser = Parser::new(sql, tokens);
48    let (statements, spans) = parser.parse_statement_list()?;
49    Ok(ParsedScript {
50        statements,
51        roles: parser.roles,
52        tokens: parser.tokens,
53        spans,
54    })
55}
56
57/// Parse exactly one statement.
58pub fn parse_statement(sql: &str) -> Result<Statement> {
59    let mut statements = parse_statements(sql)?;
60    match statements.len() {
61        1 => Ok(statements.remove(0)),
62        0 => Err(SqlError::parse(
63            sql,
64            Span::new(0, sql.len()),
65            "expected a statement",
66        )),
67        n => Err(SqlError::parse(
68            sql,
69            Span::new(0, sql.len()),
70            format!("expected one statement, found {n}"),
71        )),
72    }
73}
74
75/// Parse exactly one query (a trailing semicolon is allowed).
76pub fn parse_query(sql: &str) -> Result<Query> {
77    match parse_statement(sql)? {
78        Statement::Query(q) => Ok(*q),
79        _ => Err(SqlError::parse(
80            sql,
81            Span::new(0, sql.len()),
82            "expected a query",
83        )),
84    }
85}
86
87/// Parse every statement of `sql` accepting the Spark/Calcite constructs BigQuery lacks, each
88/// desugared to plain BigQuery syntax with the same meaning:
89///
90/// * `a LEFT SEMI JOIN b ON c` and `a LEFT ANTI JOIN b ON c` (`a` one aliased or named factor
91///   that has no joins before) become `(SELECT * FROM a WHERE [NOT] EXISTS (SELECT 1 FROM b
92///   WHERE c)) AS a`;
93/// * `(VALUES (1, 2), (3, 4)) AS t(x, y)` becomes `(SELECT 1 AS x, 2 AS y UNION ALL SELECT 3, 4) AS t`
94///   (columns without a list are named `EXPR$0`, `EXPR$1`, ...);
95/// * `SUBSTRING(x FROM a FOR b)` becomes `SUBSTRING(x, a, b)`;
96/// * `$` inside identifiers (`EXPR$0`) and at the start of one (`$f1`).
97///
98/// Queries BigQuery accepts parse exactly as with [`parse_statements`].
99pub fn parse_statements_extended(sql: &str) -> Result<Vec<Statement>> {
100    let tokens = crate::token::tokenize_extended(sql)?;
101    let mut parser = Parser::new(sql, tokens).with_extended_syntax();
102    Ok(parser.parse_statement_list()?.0)
103}
104
105/// Parse exactly one query accepting the constructs of [`parse_statements_extended`].
106pub fn parse_query_extended(sql: &str) -> Result<Query> {
107    let mut statements = parse_statements_extended(sql)?;
108    match (statements.len(), statements.pop()) {
109        (1, Some(Statement::Query(q))) => Ok(*q),
110        _ => Err(SqlError::parse(
111            sql,
112            Span::new(0, sql.len()),
113            "expected one query",
114        )),
115    }
116}
117
118/// Parse one expression.
119pub fn parse_expr(sql: &str) -> Result<Expr> {
120    let tokens = tokenize(sql)?;
121    let mut parser = Parser::new(sql, tokens);
122    let expr = parser.parse_expr()?;
123    parser.expect_end()?;
124    Ok(expr)
125}
126
127/// Parse one data type (`ARRAY<STRUCT<a INT64>>`).
128pub fn parse_data_type(sql: &str) -> Result<DataType> {
129    let tokens = tokenize(sql)?;
130    let mut parser = Parser::new(sql, tokens);
131    let ty = parser.parse_data_type()?;
132    parser.expect_end()?;
133    Ok(ty)
134}
135
136/// Words that may name a function even though they are reserved.
137const RESERVED_FUNCTIONS: &[&str] = &[
138    "IF", "LEFT", "RIGHT", "GROUPING", "RANGE", "COLLATE", "CONTAINS",
139];
140
141/// Functions BigQuery accepts without parentheses.
142const NO_PAREN_FUNCTIONS: &[&str] = &[
143    "CURRENT_DATE",
144    "CURRENT_DATETIME",
145    "CURRENT_TIME",
146    "CURRENT_TIMESTAMP",
147];
148
149/// Words that end a block of statements.
150const BLOCK_TERMINATORS: &[&str] = &["END", "ELSE", "ELSEIF", "WHEN", "UNTIL", "EXCEPTION"];
151
152/// The recursive-descent parser over significant tokens.
153pub struct Parser<'a> {
154    src: &'a str,
155    tokens: Vec<Token>,
156    roles: Vec<TokenRole>,
157    pos: usize,
158    depth: usize,
159    /// One past the highest token index whose role was set.
160    touched: usize,
161    /// Tokens split by [`Parser::expect_gt`], with their original form, so a failed attempt can undo them.
162    splits: Vec<(usize, Token)>,
163    /// Spark/Calcite constructs BigQuery lacks are accepted and desugared (see
164    /// [`parse_query_extended`]).
165    extended: bool,
166}
167
168impl<'a> Parser<'a> {
169    pub fn new(src: &'a str, tokens: Vec<Token>) -> Self {
170        let roles = vec![TokenRole::Other; tokens.len()];
171        Parser {
172            src,
173            tokens,
174            roles,
175            pos: 0,
176            depth: 0,
177            touched: 0,
178            splits: Vec::new(),
179            extended: false,
180        }
181    }
182
183    /// Accept the Spark/Calcite constructs listed at [`parse_query_extended`].
184    pub fn with_extended_syntax(mut self) -> Self {
185        self.extended = true;
186        self
187    }
188
189    // ------------------------------------------------------------------ token helpers
190
191    fn peek(&self) -> Option<&Token> {
192        self.tokens.get(self.pos)
193    }
194
195    fn peek_nth(&self, n: usize) -> Option<&Token> {
196        self.tokens.get(self.pos + n)
197    }
198
199    fn at_end(&self) -> bool {
200        self.pos >= self.tokens.len()
201    }
202
203    fn peek_keyword(&self, keyword: &str) -> bool {
204        self.peek().is_some_and(|t| t.is_keyword(keyword))
205    }
206
207    fn peek_nth_keyword(&self, n: usize, keyword: &str) -> bool {
208        self.peek_nth(n).is_some_and(|t| t.is_keyword(keyword))
209    }
210
211    fn peek_any_keyword(&self, keywords: &[&str]) -> bool {
212        keywords.iter().any(|k| self.peek_keyword(k))
213    }
214
215    fn peek_punct(&self, punct: Punct) -> bool {
216        self.peek().is_some_and(|t| t.is_punct(punct))
217    }
218
219    fn peek_nth_punct(&self, n: usize, punct: Punct) -> bool {
220        self.peek_nth(n).is_some_and(|t| t.is_punct(punct))
221    }
222
223    fn set_role(&mut self, index: usize, role: TokenRole) {
224        if let Some(slot) = self.roles.get_mut(index) {
225            *slot = role;
226            self.touched = self.touched.max(index + 1);
227        }
228    }
229
230    fn parse_keyword(&mut self, keyword: &str) -> bool {
231        if self.peek_keyword(keyword) {
232            self.set_role(self.pos, TokenRole::Keyword);
233            self.pos += 1;
234            true
235        } else {
236            false
237        }
238    }
239
240    /// All of `keywords` in order, or nothing consumed.
241    fn parse_keywords(&mut self, keywords: &[&str]) -> bool {
242        if keywords
243            .iter()
244            .enumerate()
245            .all(|(i, k)| self.peek_nth_keyword(i, k))
246        {
247            for _ in keywords {
248                self.set_role(self.pos, TokenRole::Keyword);
249                self.pos += 1;
250            }
251            true
252        } else {
253            false
254        }
255    }
256
257    fn expect_keyword(&mut self, keyword: &str) -> Result<()> {
258        if self.parse_keyword(keyword) {
259            Ok(())
260        } else {
261            Err(self.error(&format!("expected {keyword}")))
262        }
263    }
264
265    fn expect_keywords(&mut self, keywords: &[&str]) -> Result<()> {
266        for k in keywords {
267            self.expect_keyword(k)?;
268        }
269        Ok(())
270    }
271
272    fn consume_punct(&mut self, punct: Punct) -> bool {
273        if self.peek_punct(punct) {
274            self.pos += 1;
275            true
276        } else {
277            false
278        }
279    }
280
281    fn expect_punct(&mut self, punct: Punct) -> Result<()> {
282        if self.consume_punct(punct) {
283            Ok(())
284        } else {
285            Err(self.error(&format!("expected '{}'", punct.as_str())))
286        }
287    }
288
289    /// `>`, splitting a `>>` or `>=` the lexer read as one token (`ARRAY<ARRAY<INT64>>`).
290    fn expect_gt(&mut self) -> Result<()> {
291        let kind = self.tokens.get(self.pos).map(|t| t.kind.clone());
292        match kind {
293            Some(TokenKind::Punct(Punct::Gt)) => {
294                self.pos += 1;
295                Ok(())
296            }
297            Some(TokenKind::Punct(p @ (Punct::ShiftRight | Punct::GtEq))) => {
298                let original = self.tokens[self.pos].clone();
299                self.splits.push((self.pos, original));
300                let rest = if p == Punct::ShiftRight {
301                    Punct::Gt
302                } else {
303                    Punct::Eq
304                };
305                let token = &mut self.tokens[self.pos];
306                token.kind = TokenKind::Punct(rest);
307                token.text = rest.as_str().to_string();
308                token.span.start += 1;
309                Ok(())
310            }
311            _ => Err(self.error("expected '>'")),
312        }
313    }
314
315    fn error(&self, message: &str) -> SqlError {
316        let span = match self.peek() {
317            Some(t) => t.span,
318            None => Span::new(self.src.len(), self.src.len()),
319        };
320        let found = match self.peek() {
321            Some(t) => describe(t),
322            None => "end of input".to_string(),
323        };
324        SqlError::parse(self.src, span, format!("{message}, found {found}"))
325    }
326
327    fn expect_end(&self) -> Result<()> {
328        if self.at_end() {
329            Ok(())
330        } else {
331            Err(self.error("expected end of input"))
332        }
333    }
334
335    fn enter(&mut self) -> Result<()> {
336        self.depth += 1;
337        if self.depth > MAX_DEPTH {
338            Err(self.error("nested too deeply"))
339        } else {
340            Ok(())
341        }
342    }
343
344    fn leave(&mut self) {
345        self.depth -= 1;
346    }
347
348    /// Try `f`; on failure rewind (roles included) and return `None`.
349    fn attempt<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T>) -> Option<T> {
350        let start = self.pos;
351        let depth = self.depth;
352        let touched = std::mem::replace(&mut self.touched, start);
353        let splits = self.splits.len();
354        let result = f(self);
355        let reached = self.touched;
356        self.touched = touched.max(reached);
357        match result {
358            Ok(value) => Some(value),
359            Err(_) => {
360                // roles past `start` were only ever set by this attempt
361                for role in &mut self.roles[start.min(reached)..reached] {
362                    *role = TokenRole::Other;
363                }
364                while self.splits.len() > splits {
365                    if let Some((index, token)) = self.splits.pop() {
366                        self.tokens[index] = token;
367                    }
368                }
369                self.pos = start;
370                self.depth = depth;
371                None
372            }
373        }
374    }
375
376    // ------------------------------------------------------------------ identifiers
377
378    fn is_identifier_token(token: &Token) -> bool {
379        match &token.kind {
380            TokenKind::Word => !is_reserved_keyword(&token.text),
381            TokenKind::QuotedIdentifier(_) => true,
382            _ => false,
383        }
384    }
385
386    fn peek_identifier(&self) -> bool {
387        self.peek().is_some_and(Self::is_identifier_token)
388    }
389
390    /// An unreserved word or a backtick-quoted name.
391    pub fn parse_identifier(&mut self) -> Result<Ident> {
392        let Some(token) = self.peek().cloned() else {
393            return Err(self.error("expected an identifier"));
394        };
395        let ident = match token.kind {
396            TokenKind::Word if !is_reserved_keyword(&token.text) => Ident::new(token.text),
397            TokenKind::QuotedIdentifier(value) => Ident::quoted(value),
398            _ => return Err(self.error("expected an identifier")),
399        };
400        self.set_role(self.pos, TokenRole::Identifier);
401        self.pos += 1;
402        Ok(ident)
403    }
404
405    /// A name part after a dot, where reserved words are allowed.
406    fn parse_path_part(&mut self) -> Result<Ident> {
407        let Some(token) = self.peek().cloned() else {
408            return Err(self.error("expected a name"));
409        };
410        match token.kind {
411            TokenKind::Word => {
412                self.set_role(self.pos, TokenRole::Identifier);
413                self.pos += 1;
414                Ok(Ident::new(token.text))
415            }
416            TokenKind::QuotedIdentifier(value) => {
417                self.set_role(self.pos, TokenRole::Identifier);
418                self.pos += 1;
419                Ok(Ident::quoted(value))
420            }
421            TokenKind::Integer => {
422                // `t.2020_sales`: digits then an adjacent word
423                self.set_role(self.pos, TokenRole::Identifier);
424                self.pos += 1;
425                let mut text = token.text.clone();
426                let mut end = token.span.end;
427                while let Some(next) = self.peek() {
428                    if next.span.start == end
429                        && matches!(next.kind, TokenKind::Word | TokenKind::Integer)
430                    {
431                        text.push_str(&next.text);
432                        end = next.span.end;
433                        self.set_role(self.pos, TokenRole::Identifier);
434                        self.pos += 1;
435                    } else {
436                        break;
437                    }
438                }
439                Ok(Ident::new(text))
440            }
441            _ => Err(self.error("expected a name")),
442        }
443    }
444
445    /// A dotted name. With `table`, the first part may hold dashes (`my-project.ds.t`).
446    pub fn parse_object_name(&mut self, table: bool) -> Result<ObjectName> {
447        let first = if table {
448            self.parse_table_name_first_part()?
449        } else {
450            self.parse_identifier()?
451        };
452        let mut parts = vec![first];
453        while self.peek_punct(Punct::Dot)
454            && self.peek_nth(1).is_some_and(|t| {
455                matches!(
456                    t.kind,
457                    TokenKind::Word | TokenKind::QuotedIdentifier(_) | TokenKind::Integer
458                )
459            })
460        {
461            self.pos += 1;
462            parts.push(self.parse_path_part()?);
463        }
464        Ok(ObjectName(parts))
465    }
466
467    fn parse_table_name_first_part(&mut self) -> Result<Ident> {
468        let Some(token) = self.peek().cloned() else {
469            return Err(self.error("expected a table name"));
470        };
471        match &token.kind {
472            TokenKind::QuotedIdentifier(_) => self.parse_identifier(),
473            TokenKind::Word if !is_reserved_keyword(&token.text) => {
474                self.set_role(self.pos, TokenRole::Identifier);
475                self.pos += 1;
476                let mut text = token.text.clone();
477                let mut end = token.span.end;
478                // `my-project-123`: dashes and digits written without spaces
479                loop {
480                    let dash = self
481                        .peek()
482                        .is_some_and(|t| t.is_punct(Punct::Minus) && t.span.start == end);
483                    let after = self.peek_nth(1).cloned();
484                    match (dash, after) {
485                        (true, Some(next))
486                            if next.span.start == end + 1
487                                && matches!(next.kind, TokenKind::Word | TokenKind::Integer) =>
488                        {
489                            text.push('-');
490                            text.push_str(&next.text);
491                            end = next.span.end;
492                            self.set_role(self.pos, TokenRole::Identifier);
493                            self.set_role(self.pos + 1, TokenRole::Identifier);
494                            self.pos += 2;
495                            while let Some(more) = self.peek() {
496                                if more.span.start == end
497                                    && matches!(more.kind, TokenKind::Word | TokenKind::Integer)
498                                {
499                                    text.push_str(&more.text);
500                                    end = more.span.end;
501                                    self.set_role(self.pos, TokenRole::Identifier);
502                                    self.pos += 1;
503                                } else {
504                                    break;
505                                }
506                            }
507                        }
508                        _ => break,
509                    }
510                }
511                Ok(Ident::new(text))
512            }
513            _ => Err(self.error("expected a table name")),
514        }
515    }
516
517    fn parse_identifier_list(&mut self) -> Result<Vec<Ident>> {
518        let mut out = vec![self.parse_identifier()?];
519        while self.consume_punct(Punct::Comma) {
520            out.push(self.parse_identifier()?);
521        }
522        Ok(out)
523    }
524
525    fn parse_parenthesized_identifiers(&mut self) -> Result<Vec<Ident>> {
526        self.expect_punct(Punct::LParen)?;
527        let list = self.parse_identifier_list()?;
528        self.expect_punct(Punct::RParen)?;
529        Ok(list)
530    }
531
532    /// `AS name` or an implicit alias. `table` excludes the words that start a table operator.
533    fn parse_optional_alias(&mut self, table: bool) -> Result<Option<Ident>> {
534        if self.parse_keyword("AS") {
535            return self.parse_identifier().map(Some);
536        }
537        let Some(token) = self.peek() else {
538            return Ok(None);
539        };
540        if !Self::is_identifier_token(token) {
541            return Ok(None);
542        }
543        if table && token.is_word() {
544            let upper = token.upper();
545            let next_paren = self.peek_nth_punct(1, Punct::LParen);
546            if ((upper == "PIVOT" || upper == "MATCH_RECOGNIZE" || upper == "ALIGN") && next_paren)
547                || (upper == "UNPIVOT"
548                    && (next_paren
549                        || self.peek_nth_keyword(1, "INCLUDE")
550                        || self.peek_nth_keyword(1, "EXCLUDE")))
551            {
552                return Ok(None);
553            }
554        }
555        self.parse_identifier().map(Some)
556    }
557
558    // ------------------------------------------------------------------ statements
559
560    fn parse_statement_list(&mut self) -> Result<(Vec<Statement>, Vec<Span>)> {
561        let mut statements = Vec::new();
562        let mut spans = Vec::new();
563        loop {
564            while self.consume_punct(Punct::Semicolon) {}
565            if self.at_end() {
566                break;
567            }
568            let start = self.tokens[self.pos].span.start;
569            let statement = self.parse_statement()?;
570            let end = self.tokens[self.pos - 1].span.end;
571            statements.push(statement);
572            spans.push(Span::new(start, end));
573            if self.at_end() {
574                break;
575            }
576            if !self.consume_punct(Punct::Semicolon) {
577                return Err(self.error("expected ';' or end of input after the statement"));
578            }
579        }
580        Ok((statements, spans))
581    }
582
583    /// Statements up to one of `terminators` (each followed by a semicolon).
584    fn parse_block(&mut self, terminators: &[&str]) -> Result<Vec<Statement>> {
585        let mut out = Vec::new();
586        loop {
587            while self.consume_punct(Punct::Semicolon) {}
588            if self.at_end() {
589                return Err(self.error("unterminated block"));
590            }
591            if self.peek_any_keyword(terminators) && !self.terminator_is_statement() {
592                break;
593            }
594            out.push(self.parse_statement()?);
595            if !self.consume_punct(Punct::Semicolon) && !self.peek_any_keyword(BLOCK_TERMINATORS) {
596                return Err(self.error("expected ';' after the statement"));
597            }
598        }
599        Ok(out)
600    }
601
602    /// `WHEN` can only be a terminator; `END` always is. Nothing to disambiguate today, but a
603    /// statement starting with `CASE` is not confused with the block terminators.
604    fn terminator_is_statement(&self) -> bool {
605        false
606    }
607
608    /// Parse one statement at the current position.
609    pub fn parse_statement(&mut self) -> Result<Statement> {
610        self.enter()?;
611        let result = self.parse_statement_inner();
612        self.leave();
613        result
614    }
615
616    fn parse_statement_inner(&mut self) -> Result<Statement> {
617        let start = self.pos;
618        // `label: BEGIN|LOOP|WHILE|FOR|REPEAT`
619        let label = if self.peek_identifier()
620            && self.peek_nth_punct(1, Punct::Colon)
621            && ["BEGIN", "LOOP", "WHILE", "FOR", "REPEAT"]
622                .iter()
623                .any(|k| self.peek_nth_keyword(2, k))
624        {
625            let label = self.parse_identifier()?;
626            self.pos += 1;
627            Some(label)
628        } else {
629            None
630        };
631        let labelled = label.is_some();
632        let Some(token) = self.peek().cloned() else {
633            return Err(self.error("expected a statement"));
634        };
635        if token.is_punct(Punct::LParen) {
636            return Ok(Statement::Query(Box::new(self.parse_query()?)));
637        }
638        if !token.is_word() {
639            return Err(self.error("expected a statement"));
640        }
641        let statement = match token.upper().as_str() {
642            "SELECT" | "WITH" | "FROM" => Statement::Query(Box::new(self.parse_query()?)),
643            "CREATE" => self.parse_create(start)?,
644            "INSERT" => self.parse_insert()?,
645            "UPDATE" => self.parse_update()?,
646            "DELETE" => self.parse_delete()?,
647            "MERGE" => self.parse_merge()?,
648            "DROP" => self.parse_drop(start)?,
649            "ALTER" => self.parse_alter(start)?,
650            "TRUNCATE" => {
651                self.expect_keywords(&["TRUNCATE", "TABLE"])?;
652                Statement::Truncate {
653                    name: self.parse_object_name(true)?,
654                }
655            }
656            "DECLARE" => self.parse_declare()?,
657            "SET" => self.parse_set()?,
658            "BEGIN" => self.parse_begin(label)?,
659            "IF" => self.parse_if()?,
660            "LOOP" => {
661                self.expect_keyword("LOOP")?;
662                let body = self.parse_block(&["END"])?;
663                self.expect_keywords(&["END", "LOOP"])?;
664                self.skip_end_label(&label);
665                Statement::Loop { label, body }
666            }
667            "WHILE" => {
668                self.expect_keyword("WHILE")?;
669                let condition = self.parse_expr()?;
670                self.expect_keyword("DO")?;
671                let body = self.parse_block(&["END"])?;
672                self.expect_keywords(&["END", "WHILE"])?;
673                self.skip_end_label(&label);
674                Statement::While {
675                    label,
676                    condition,
677                    body,
678                }
679            }
680            "FOR" => {
681                self.expect_keyword("FOR")?;
682                let variable = self.parse_identifier()?;
683                self.expect_keyword("IN")?;
684                self.expect_punct(Punct::LParen)?;
685                let query = self.parse_query()?;
686                self.expect_punct(Punct::RParen)?;
687                self.expect_keyword("DO")?;
688                let body = self.parse_block(&["END"])?;
689                self.expect_keywords(&["END", "FOR"])?;
690                self.skip_end_label(&label);
691                Statement::ForIn {
692                    label,
693                    variable,
694                    query: Box::new(query),
695                    body,
696                }
697            }
698            "REPEAT" => {
699                self.expect_keyword("REPEAT")?;
700                let body = self.parse_block(&["UNTIL"])?;
701                self.expect_keyword("UNTIL")?;
702                let until = self.parse_expr()?;
703                self.expect_keywords(&["END", "REPEAT"])?;
704                self.skip_end_label(&label);
705                Statement::Repeat { label, body, until }
706            }
707            "CASE" => self.parse_case_statement()?,
708            "BREAK" | "LEAVE" | "CONTINUE" | "ITERATE" => {
709                let kind = match token.upper().as_str() {
710                    "BREAK" => ControlKind::Break,
711                    "LEAVE" => ControlKind::Leave,
712                    "CONTINUE" => ControlKind::Continue,
713                    _ => ControlKind::Iterate,
714                };
715                self.set_role(self.pos, TokenRole::Keyword);
716                self.pos += 1;
717                let label = if self.peek_identifier() {
718                    Some(self.parse_identifier()?)
719                } else {
720                    None
721                };
722                Statement::Control { kind, label }
723            }
724            "RETURN" => {
725                self.expect_keyword("RETURN")?;
726                Statement::Return
727            }
728            "RAISE" => {
729                self.expect_keyword("RAISE")?;
730                let message = if self.parse_keywords(&["USING", "MESSAGE"]) {
731                    self.expect_punct(Punct::Eq)?;
732                    Some(self.parse_expr()?)
733                } else {
734                    None
735                };
736                Statement::Raise { message }
737            }
738            "CALL" => {
739                self.expect_keyword("CALL")?;
740                let procedure = self.parse_object_name(true)?;
741                self.set_role(self.pos - 1, TokenRole::Function);
742                self.expect_punct(Punct::LParen)?;
743                let mut args = Vec::new();
744                if !self.peek_punct(Punct::RParen) {
745                    args.push(self.parse_expr()?);
746                    while self.consume_punct(Punct::Comma) {
747                        args.push(self.parse_expr()?);
748                    }
749                }
750                self.expect_punct(Punct::RParen)?;
751                Statement::Call { procedure, args }
752            }
753            "EXECUTE" => self.parse_execute()?,
754            "ASSERT" => {
755                self.expect_keyword("ASSERT")?;
756                let condition = self.parse_expr()?;
757                let description = if self.parse_keyword("AS") {
758                    Some(self.parse_expr()?)
759                } else {
760                    None
761                };
762                Statement::Assert {
763                    condition,
764                    description,
765                }
766            }
767            "COMMIT" | "ROLLBACK" => {
768                let kind = if token.is_keyword("COMMIT") {
769                    TransactionKind::Commit
770                } else {
771                    TransactionKind::Rollback
772                };
773                self.set_role(self.pos, TokenRole::Keyword);
774                self.pos += 1;
775                self.parse_keyword("TRANSACTION");
776                Statement::Transaction(kind)
777            }
778            "EXPORT" if self.peek_nth_keyword(1, "DATA") => self.parse_export()?,
779            "LOAD" if self.peek_nth_keyword(1, "DATA") => self.parse_load(start)?,
780            _ => self.parse_raw(start)?,
781        };
782        if labelled
783            && !matches!(
784                statement,
785                Statement::BeginEnd { .. }
786                    | Statement::Loop { .. }
787                    | Statement::While { .. }
788                    | Statement::ForIn { .. }
789                    | Statement::Repeat { .. }
790            )
791        {
792            return Err(self.error("a label must precede a block or loop"));
793        }
794        Ok(statement)
795    }
796
797    fn skip_end_label(&mut self, label: &Option<Ident>) {
798        if label.is_some() && self.peek_identifier() {
799            self.pos += 1;
800        }
801    }
802
803    /// The statement from `start` to its top-level semicolon, kept as text.
804    fn parse_raw(&mut self, start: usize) -> Result<Statement> {
805        self.pos = start;
806        let mut depth = 0usize;
807        let begin = self.tokens[start].span.start;
808        let mut end = begin;
809        while let Some(token) = self.peek() {
810            match token.kind {
811                TokenKind::Punct(Punct::LParen) | TokenKind::Punct(Punct::LBracket) => depth += 1,
812                TokenKind::Punct(Punct::RParen) | TokenKind::Punct(Punct::RBracket) => {
813                    depth = depth.saturating_sub(1)
814                }
815                TokenKind::Punct(Punct::Semicolon) if depth == 0 => break,
816                _ => {}
817            }
818            end = token.span.end;
819            self.pos += 1;
820        }
821        Ok(Statement::Raw(self.src[begin..end].to_string()))
822    }
823
824    fn parse_create(&mut self, start: usize) -> Result<Statement> {
825        self.expect_keyword("CREATE")?;
826        let or_replace = self.parse_keywords(&["OR", "REPLACE"]);
827        let temporary = self.parse_keyword("TEMP") || self.parse_keyword("TEMPORARY");
828        if self.parse_keywords(&["TABLE", "FUNCTION"]) {
829            return self.parse_create_table_function(or_replace, temporary);
830        }
831        if self.parse_keyword("TABLE") {
832            return self.parse_create_table(or_replace, temporary, TableKind::Table);
833        }
834        if self.peek_keyword("EXTERNAL") || self.peek_keyword("SNAPSHOT") {
835            let kind = if self.parse_keyword("EXTERNAL") {
836                TableKind::External
837            } else {
838                self.expect_keyword("SNAPSHOT")?;
839                TableKind::Snapshot
840            };
841            if !self.parse_keyword("TABLE") {
842                return self.parse_raw(start);
843            }
844            // unusual external-table clauses stay as text rather than failing
845            return match self.attempt(|p| p.parse_create_table(or_replace, temporary, kind)) {
846                Some(statement) => Ok(statement),
847                None => self.parse_raw(start),
848            };
849        }
850        if self.parse_keywords(&["MATERIALIZED", "VIEW"]) {
851            return self.parse_create_view(or_replace, true);
852        }
853        if self.parse_keyword("VIEW") {
854            return self.parse_create_view(or_replace, false);
855        }
856        if self.parse_keywords(&["AGGREGATE", "FUNCTION"]) {
857            return self.parse_create_function(or_replace, temporary, true, start);
858        }
859        if self.parse_keyword("FUNCTION") {
860            return self.parse_create_function(or_replace, temporary, false, start);
861        }
862        if self.parse_keyword("PROCEDURE") {
863            return match self.attempt(|p| p.parse_create_procedure(or_replace)) {
864                Some(statement) => Ok(statement),
865                None => self.parse_raw(start),
866            };
867        }
868        if self.parse_keyword("SCHEMA") {
869            let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
870            let name = self.parse_object_name(true)?;
871            let default_collate = if self.parse_keywords(&["DEFAULT", "COLLATE"]) {
872                Some(self.parse_expr()?)
873            } else {
874                None
875            };
876            let options = self.parse_optional_options()?;
877            return Ok(Statement::CreateSchema(Box::new(CreateSchema {
878                if_not_exists,
879                name,
880                default_collate,
881                options,
882            })));
883        }
884        self.parse_raw(start)
885    }
886
887    fn parse_optional_options(&mut self) -> Result<Vec<SqlOption>> {
888        if self.peek_keyword("OPTIONS") && self.peek_nth_punct(1, Punct::LParen) {
889            self.parse_keyword("OPTIONS");
890            self.parse_options_body()
891        } else {
892            Ok(Vec::new())
893        }
894    }
895
896    fn parse_options_body(&mut self) -> Result<Vec<SqlOption>> {
897        self.expect_punct(Punct::LParen)?;
898        let mut options = Vec::new();
899        while !self.peek_punct(Punct::RParen) {
900            let name = self.parse_path_part()?;
901            self.expect_punct(Punct::Eq)?;
902            let value = self.parse_expr()?;
903            options.push(SqlOption { name, value });
904            if !self.consume_punct(Punct::Comma) {
905                break;
906            }
907        }
908        self.expect_punct(Punct::RParen)?;
909        Ok(options)
910    }
911
912    fn parse_cluster_by(&mut self) -> Result<Vec<Expr>> {
913        let mut out = vec![self.parse_expr()?];
914        while self.consume_punct(Punct::Comma) {
915            out.push(self.parse_expr()?);
916        }
917        Ok(out)
918    }
919
920    fn parse_create_table(
921        &mut self,
922        or_replace: bool,
923        temporary: bool,
924        kind: TableKind,
925    ) -> Result<Statement> {
926        let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
927        let name = self.parse_object_name(true)?;
928        let mut table = CreateTable {
929            or_replace,
930            temporary,
931            kind,
932            if_not_exists,
933            name,
934            columns: Vec::new(),
935            constraints: Vec::new(),
936            copy: None,
937            with_connection: None,
938            default_collate: None,
939            partition_by: None,
940            cluster_by: Vec::new(),
941            options: Vec::new(),
942            query: None,
943        };
944        if self.peek_punct(Punct::LParen) && !self.paren_starts_query() {
945            self.pos += 1;
946            loop {
947                if self.peek_keyword("PRIMARY")
948                    || self.peek_keyword("FOREIGN")
949                    || self.peek_keyword("CONSTRAINT")
950                {
951                    table.constraints.push(self.parse_table_constraint()?);
952                } else {
953                    table.columns.push(self.parse_column_def()?);
954                }
955                if !self.consume_punct(Punct::Comma) || self.peek_punct(Punct::RParen) {
956                    break;
957                }
958            }
959            self.expect_punct(Punct::RParen)?;
960        }
961        loop {
962            if self.peek_any_keyword(&["LIKE", "COPY", "CLONE"]) && table.copy.is_none() {
963                let copy_kind = if self.parse_keyword("LIKE") {
964                    CopyKind::Like
965                } else if self.parse_keyword("COPY") {
966                    CopyKind::Copy
967                } else {
968                    self.expect_keyword("CLONE")?;
969                    CopyKind::Clone
970                };
971                let source = self.parse_object_name(true)?;
972                let system_time = self.parse_system_time()?;
973                table.copy = Some(TableCopy {
974                    kind: copy_kind,
975                    source,
976                    system_time,
977                });
978            } else if self.parse_keywords(&["DEFAULT", "COLLATE"]) {
979                table.default_collate = Some(self.parse_expr()?);
980            } else if self.parse_keywords(&["PARTITION", "BY"]) {
981                table.partition_by = Some(self.parse_expr()?);
982            } else if self.parse_keywords(&["CLUSTER", "BY"]) {
983                table.cluster_by = self.parse_cluster_by()?;
984            } else if self.parse_keywords(&["WITH", "CONNECTION"]) {
985                table.with_connection = Some(self.parse_object_name(true)?);
986            } else if self.peek_keyword("OPTIONS") && self.peek_nth_punct(1, Punct::LParen) {
987                table.options = self.parse_optional_options()?;
988            } else if self.parse_keyword("AS") {
989                table.query = Some(Box::new(self.parse_query()?));
990                break;
991            } else {
992                break;
993            }
994        }
995        Ok(Statement::CreateTable(Box::new(table)))
996    }
997
998    fn parse_system_time(&mut self) -> Result<Option<Expr>> {
999        if self.parse_keywords(&["FOR", "SYSTEM_TIME", "AS", "OF"]) {
1000            Ok(Some(self.parse_expr()?))
1001        } else {
1002            Ok(None)
1003        }
1004    }
1005
1006    fn parse_table_constraint(&mut self) -> Result<TableConstraint> {
1007        let name = if self.parse_keyword("CONSTRAINT") {
1008            Some(self.parse_identifier()?)
1009        } else {
1010            None
1011        };
1012        if self.parse_keywords(&["PRIMARY", "KEY"]) {
1013            let columns = self.parse_parenthesized_identifiers()?;
1014            let not_enforced = self.parse_keywords(&["NOT", "ENFORCED"]);
1015            return Ok(TableConstraint::PrimaryKey {
1016                columns,
1017                not_enforced,
1018            });
1019        }
1020        self.expect_keywords(&["FOREIGN", "KEY"])?;
1021        let columns = self.parse_parenthesized_identifiers()?;
1022        self.expect_keyword("REFERENCES")?;
1023        let foreign_table = self.parse_object_name(true)?;
1024        let referred_columns = self.parse_parenthesized_identifiers()?;
1025        let not_enforced = self.parse_keywords(&["NOT", "ENFORCED"]);
1026        Ok(TableConstraint::ForeignKey {
1027            name,
1028            columns,
1029            foreign_table,
1030            referred_columns,
1031            not_enforced,
1032        })
1033    }
1034
1035    fn parse_column_def(&mut self) -> Result<ColumnDef> {
1036        let name = self.parse_identifier()?;
1037        let data_type = self.parse_data_type()?;
1038        let mut column = ColumnDef {
1039            name,
1040            data_type,
1041            collate: None,
1042            not_null: false,
1043            default: None,
1044            primary_key: false,
1045            options: Vec::new(),
1046        };
1047        loop {
1048            if self.parse_keyword("COLLATE") {
1049                column.collate = Some(self.parse_expr()?);
1050            } else if self.parse_keywords(&["NOT", "NULL"]) {
1051                column.not_null = true;
1052            } else if self.parse_keyword("DEFAULT") {
1053                column.default = Some(self.parse_expr()?);
1054            } else if self.parse_keywords(&["PRIMARY", "KEY", "NOT", "ENFORCED"]) {
1055                column.primary_key = true;
1056            } else if self.peek_keyword("OPTIONS") && self.peek_nth_punct(1, Punct::LParen) {
1057                column.options = self.parse_optional_options()?;
1058            } else {
1059                break;
1060            }
1061        }
1062        Ok(column)
1063    }
1064
1065    fn parse_create_view(&mut self, or_replace: bool, materialized: bool) -> Result<Statement> {
1066        let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
1067        let name = self.parse_object_name(true)?;
1068        let mut columns = Vec::new();
1069        if self.peek_punct(Punct::LParen) && !self.paren_starts_query() {
1070            self.pos += 1;
1071            loop {
1072                let name = self.parse_identifier()?;
1073                let options = self.parse_optional_options()?;
1074                columns.push(ViewColumn { name, options });
1075                if !self.consume_punct(Punct::Comma) {
1076                    break;
1077                }
1078            }
1079            self.expect_punct(Punct::RParen)?;
1080        }
1081        let mut partition_by = None;
1082        let mut cluster_by = Vec::new();
1083        let mut options = Vec::new();
1084        loop {
1085            if self.parse_keywords(&["PARTITION", "BY"]) {
1086                partition_by = Some(self.parse_expr()?);
1087            } else if self.parse_keywords(&["CLUSTER", "BY"]) {
1088                cluster_by = self.parse_cluster_by()?;
1089            } else if self.peek_keyword("OPTIONS") && self.peek_nth_punct(1, Punct::LParen) {
1090                options = self.parse_optional_options()?;
1091            } else {
1092                break;
1093            }
1094        }
1095        self.expect_keyword("AS")?;
1096        let query = self.parse_query()?;
1097        Ok(Statement::CreateView(Box::new(CreateView {
1098            or_replace,
1099            materialized,
1100            if_not_exists,
1101            name,
1102            columns,
1103            partition_by,
1104            cluster_by,
1105            options,
1106            query: Box::new(query),
1107        })))
1108    }
1109
1110    fn parse_param_type(&mut self) -> Result<ParamType> {
1111        if self.parse_keywords(&["ANY", "TYPE"]) {
1112            return Ok(ParamType::AnyType);
1113        }
1114        if self.parse_keywords(&["ANY", "TABLE"]) {
1115            return Ok(ParamType::AnyTable);
1116        }
1117        if self.peek_keyword("TABLE") && self.peek_nth_punct(1, Punct::Lt) {
1118            self.parse_keyword("TABLE");
1119            self.pos += 1;
1120            let fields = self.parse_struct_fields()?;
1121            return Ok(ParamType::Table(fields));
1122        }
1123        Ok(ParamType::Type(self.parse_data_type()?))
1124    }
1125
1126    fn parse_function_params(&mut self) -> Result<Vec<FunctionParam>> {
1127        self.expect_punct(Punct::LParen)?;
1128        let mut params = Vec::new();
1129        while !self.peek_punct(Punct::RParen) {
1130            let name = self.parse_identifier()?;
1131            let param_type = self.parse_param_type()?;
1132            let not_aggregate = self.parse_keywords(&["NOT", "AGGREGATE"]);
1133            params.push(FunctionParam {
1134                name,
1135                param_type,
1136                not_aggregate,
1137            });
1138            if !self.consume_punct(Punct::Comma) {
1139                break;
1140            }
1141        }
1142        self.expect_punct(Punct::RParen)?;
1143        Ok(params)
1144    }
1145
1146    fn parse_create_function(
1147        &mut self,
1148        or_replace: bool,
1149        temporary: bool,
1150        aggregate: bool,
1151        start: usize,
1152    ) -> Result<Statement> {
1153        let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
1154        let name = self.parse_object_name(true)?;
1155        self.set_role(self.pos - 1, TokenRole::Function);
1156        let params = self.parse_function_params()?;
1157        let mut function = CreateFunction {
1158            or_replace,
1159            temporary,
1160            aggregate,
1161            if_not_exists,
1162            name,
1163            params,
1164            returns: None,
1165            determinism: None,
1166            language: None,
1167            options: Vec::new(),
1168            body: FunctionBody::None,
1169        };
1170        loop {
1171            if self.parse_keyword("RETURNS") {
1172                function.returns = Some(self.parse_data_type()?);
1173            } else if self.parse_keyword("DETERMINISTIC") {
1174                function.determinism = Some(true);
1175            } else if self.parse_keywords(&["NOT", "DETERMINISTIC"]) {
1176                function.determinism = Some(false);
1177            } else if self.parse_keyword("LANGUAGE") {
1178                function.language = Some(self.parse_identifier()?);
1179            } else if self.peek_keyword("OPTIONS") && self.peek_nth_punct(1, Punct::LParen) {
1180                function.options = self.parse_optional_options()?;
1181            } else if self.parse_keywords(&["REMOTE", "WITH", "CONNECTION"]) {
1182                function.body = FunctionBody::Remote(self.parse_object_name(true)?);
1183            } else if self.parse_keyword("AS") {
1184                if self.consume_punct(Punct::LParen) {
1185                    let expr = if self.peek_query_start() {
1186                        Expr::Subquery(Box::new(self.parse_query()?))
1187                    } else {
1188                        self.parse_expr()?
1189                    };
1190                    self.expect_punct(Punct::RParen)?;
1191                    function.body = FunctionBody::Expr(expr);
1192                } else {
1193                    match self.parse_prefix()? {
1194                        Expr::Literal(lit @ Literal::String(_)) => {
1195                            function.body = FunctionBody::Code(lit)
1196                        }
1197                        _ => return self.parse_raw(start),
1198                    }
1199                }
1200            } else {
1201                break;
1202            }
1203        }
1204        Ok(Statement::CreateFunction(Box::new(function)))
1205    }
1206
1207    fn parse_create_table_function(
1208        &mut self,
1209        or_replace: bool,
1210        temporary: bool,
1211    ) -> Result<Statement> {
1212        let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
1213        let name = self.parse_object_name(true)?;
1214        self.set_role(self.pos - 1, TokenRole::Function);
1215        let params = self.parse_function_params()?;
1216        let mut returns = None;
1217        let mut options = Vec::new();
1218        loop {
1219            if self.parse_keywords(&["RETURNS", "TABLE"]) {
1220                if !self.consume_punct(Punct::Lt) {
1221                    return Err(self.error("expected '<'"));
1222                }
1223                returns = Some(self.parse_struct_fields()?);
1224            } else if self.peek_keyword("OPTIONS") && self.peek_nth_punct(1, Punct::LParen) {
1225                options = self.parse_optional_options()?;
1226            } else {
1227                break;
1228            }
1229        }
1230        self.expect_keyword("AS")?;
1231        let query = self.parse_query()?;
1232        Ok(Statement::CreateTableFunction(Box::new(
1233            CreateTableFunction {
1234                or_replace,
1235                temporary,
1236                if_not_exists,
1237                name,
1238                params,
1239                returns,
1240                options,
1241                query: Box::new(query),
1242            },
1243        )))
1244    }
1245
1246    fn parse_create_procedure(&mut self, or_replace: bool) -> Result<Statement> {
1247        let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
1248        let name = self.parse_object_name(true)?;
1249        self.set_role(self.pos - 1, TokenRole::Function);
1250        self.expect_punct(Punct::LParen)?;
1251        let mut params = Vec::new();
1252        while !self.peek_punct(Punct::RParen) {
1253            let mode = if self.parse_keyword("INOUT") {
1254                Some(ParamMode::InOut)
1255            } else if self.parse_keyword("OUT") {
1256                Some(ParamMode::Out)
1257            } else if self.peek_keyword("IN")
1258                && self.peek_nth(1).is_some_and(Self::is_identifier_token)
1259            {
1260                self.parse_keyword("IN");
1261                Some(ParamMode::In)
1262            } else {
1263                None
1264            };
1265            let name = self.parse_identifier()?;
1266            let param_type = self.parse_param_type()?;
1267            params.push(ProcedureParam {
1268                mode,
1269                name,
1270                param_type,
1271            });
1272            if !self.consume_punct(Punct::Comma) {
1273                break;
1274            }
1275        }
1276        self.expect_punct(Punct::RParen)?;
1277        let options = self.parse_optional_options()?;
1278        self.expect_keyword("BEGIN")?;
1279        let body = self.parse_block(&["END", "EXCEPTION"])?;
1280        let exception = self.parse_exception_handler()?;
1281        self.expect_keyword("END")?;
1282        Ok(Statement::CreateProcedure(Box::new(CreateProcedure {
1283            or_replace,
1284            if_not_exists,
1285            name,
1286            params,
1287            options,
1288            body,
1289            exception,
1290        })))
1291    }
1292
1293    fn parse_exception_handler(&mut self) -> Result<Option<Vec<Statement>>> {
1294        if self.parse_keyword("EXCEPTION") {
1295            self.expect_keyword("WHEN")?;
1296            self.expect_keyword("ERROR")?;
1297            self.expect_keyword("THEN")?;
1298            Ok(Some(self.parse_block(&["END"])?))
1299        } else {
1300            Ok(None)
1301        }
1302    }
1303
1304    fn parse_insert(&mut self) -> Result<Statement> {
1305        self.expect_keyword("INSERT")?;
1306        self.parse_keyword("INTO");
1307        let table = self.parse_object_name(true)?;
1308        let columns = if self.peek_punct(Punct::LParen) && !self.paren_starts_query() {
1309            self.parse_parenthesized_identifiers()?
1310        } else {
1311            Vec::new()
1312        };
1313        let source = if self.parse_keyword("VALUES") {
1314            let mut rows = vec![self.parse_values_row()?];
1315            while self.consume_punct(Punct::Comma) {
1316                rows.push(self.parse_values_row()?);
1317            }
1318            InsertSource::Values(rows)
1319        } else {
1320            InsertSource::Query(Box::new(self.parse_query()?))
1321        };
1322        Ok(Statement::Insert(Box::new(Insert {
1323            table,
1324            columns,
1325            source,
1326        })))
1327    }
1328
1329    fn parse_values_row(&mut self) -> Result<Vec<Expr>> {
1330        self.expect_punct(Punct::LParen)?;
1331        let mut row = vec![self.parse_expr()?];
1332        while self.consume_punct(Punct::Comma) {
1333            row.push(self.parse_expr()?);
1334        }
1335        self.expect_punct(Punct::RParen)?;
1336        Ok(row)
1337    }
1338
1339    fn parse_assignments(&mut self) -> Result<Vec<Assignment>> {
1340        let mut out = Vec::new();
1341        loop {
1342            let mut target = vec![self.parse_identifier()?];
1343            while self.consume_punct(Punct::Dot) {
1344                target.push(self.parse_path_part()?);
1345            }
1346            self.expect_punct(Punct::Eq)?;
1347            let value = self.parse_expr()?;
1348            out.push(Assignment { target, value });
1349            if !self.consume_punct(Punct::Comma) {
1350                break;
1351            }
1352        }
1353        Ok(out)
1354    }
1355
1356    fn parse_update(&mut self) -> Result<Statement> {
1357        self.expect_keyword("UPDATE")?;
1358        let table = self.parse_object_name(true)?;
1359        let alias = self.parse_optional_alias(false)?;
1360        self.expect_keyword("SET")?;
1361        let assignments = self.parse_assignments()?;
1362        let from = if self.parse_keyword("FROM") {
1363            self.parse_from_list()?
1364        } else {
1365            Vec::new()
1366        };
1367        let selection = if self.parse_keyword("WHERE") {
1368            Some(self.parse_expr()?)
1369        } else {
1370            None
1371        };
1372        Ok(Statement::Update(Box::new(Update {
1373            table,
1374            alias,
1375            assignments,
1376            from,
1377            selection,
1378        })))
1379    }
1380
1381    fn parse_delete(&mut self) -> Result<Statement> {
1382        self.expect_keyword("DELETE")?;
1383        self.parse_keyword("FROM");
1384        let table = self.parse_object_name(true)?;
1385        let alias = self.parse_optional_alias(false)?;
1386        let selection = if self.parse_keyword("WHERE") {
1387            Some(self.parse_expr()?)
1388        } else {
1389            None
1390        };
1391        Ok(Statement::Delete(Box::new(Delete {
1392            table,
1393            alias,
1394            selection,
1395        })))
1396    }
1397
1398    fn parse_merge(&mut self) -> Result<Statement> {
1399        self.expect_keyword("MERGE")?;
1400        self.parse_keyword("INTO");
1401        let target = self.parse_object_name(true)?;
1402        let target_alias = self.parse_optional_alias(false)?;
1403        self.expect_keyword("USING")?;
1404        let source = self.parse_table_factor()?;
1405        self.expect_keyword("ON")?;
1406        let on = self.parse_expr()?;
1407        let mut clauses = Vec::new();
1408        while self.parse_keyword("WHEN") {
1409            let not = self.parse_keyword("NOT");
1410            self.expect_keyword("MATCHED")?;
1411            let mut explicit_by_target = false;
1412            let kind = if not {
1413                if self.parse_keywords(&["BY", "SOURCE"]) {
1414                    MergeMatch::NotMatchedBySource
1415                } else {
1416                    explicit_by_target = self.parse_keywords(&["BY", "TARGET"]);
1417                    MergeMatch::NotMatchedByTarget
1418                }
1419            } else {
1420                MergeMatch::Matched
1421            };
1422            let condition = if self.parse_keyword("AND") {
1423                Some(self.parse_expr()?)
1424            } else {
1425                None
1426            };
1427            self.expect_keyword("THEN")?;
1428            let action = if self.parse_keyword("UPDATE") {
1429                self.expect_keyword("SET")?;
1430                MergeAction::Update(self.parse_assignments()?)
1431            } else if self.parse_keyword("DELETE") {
1432                MergeAction::Delete
1433            } else {
1434                self.expect_keyword("INSERT")?;
1435                let columns = if self.peek_punct(Punct::LParen) {
1436                    self.parse_parenthesized_identifiers()?
1437                } else {
1438                    Vec::new()
1439                };
1440                if self.parse_keyword("ROW") {
1441                    MergeAction::Insert {
1442                        columns,
1443                        values: Vec::new(),
1444                        row: true,
1445                    }
1446                } else {
1447                    self.expect_keyword("VALUES")?;
1448                    let values = self.parse_values_row()?;
1449                    MergeAction::Insert {
1450                        columns,
1451                        values,
1452                        row: false,
1453                    }
1454                }
1455            };
1456            clauses.push(MergeClause {
1457                kind,
1458                explicit_by_target,
1459                condition,
1460                action,
1461            });
1462        }
1463        if clauses.is_empty() {
1464            return Err(self.error("expected WHEN"));
1465        }
1466        Ok(Statement::Merge(Box::new(Merge {
1467            target,
1468            target_alias,
1469            source,
1470            on,
1471            clauses,
1472        })))
1473    }
1474
1475    fn parse_object_type(&mut self) -> Option<ObjectType> {
1476        let checks: &[(&[&str], ObjectType)] = &[
1477            (&["EXTERNAL", "TABLE"], ObjectType::ExternalTable),
1478            (&["SNAPSHOT", "TABLE"], ObjectType::SnapshotTable),
1479            (&["MATERIALIZED", "VIEW"], ObjectType::MaterializedView),
1480            (&["TABLE", "FUNCTION"], ObjectType::TableFunction),
1481            (&["TABLE"], ObjectType::Table),
1482            (&["VIEW"], ObjectType::View),
1483            (&["SCHEMA"], ObjectType::Schema),
1484            (&["FUNCTION"], ObjectType::Function),
1485            (&["PROCEDURE"], ObjectType::Procedure),
1486            (&["MODEL"], ObjectType::Model),
1487        ];
1488        for (words, kind) in checks {
1489            if self.parse_keywords(words) {
1490                return Some(*kind);
1491            }
1492        }
1493        None
1494    }
1495
1496    fn parse_drop(&mut self, start: usize) -> Result<Statement> {
1497        self.expect_keyword("DROP")?;
1498        let Some(object_type) = self.parse_object_type() else {
1499            return self.parse_raw(start);
1500        };
1501        let if_exists = self.parse_keywords(&["IF", "EXISTS"]);
1502        let name = self.parse_object_name(true)?;
1503        let cascade = if self.parse_keyword("CASCADE") {
1504            Some(true)
1505        } else if self.parse_keyword("RESTRICT") {
1506            Some(false)
1507        } else {
1508            None
1509        };
1510        Ok(Statement::Drop(Box::new(Drop {
1511            object_type,
1512            if_exists,
1513            name,
1514            cascade,
1515        })))
1516    }
1517
1518    fn parse_alter(&mut self, start: usize) -> Result<Statement> {
1519        self.expect_keyword("ALTER")?;
1520        let object_type = if self.parse_keywords(&["MATERIALIZED", "VIEW"]) {
1521            ObjectType::MaterializedView
1522        } else if self.parse_keyword("TABLE") {
1523            ObjectType::Table
1524        } else if self.parse_keyword("VIEW") {
1525            ObjectType::View
1526        } else {
1527            return self.parse_raw(start);
1528        };
1529        match self.attempt(|p| p.parse_alter_body(object_type)) {
1530            Some(statement) => Ok(statement),
1531            None => self.parse_raw(start),
1532        }
1533    }
1534
1535    fn parse_alter_body(&mut self, object_type: ObjectType) -> Result<Statement> {
1536        let if_exists = self.parse_keywords(&["IF", "EXISTS"]);
1537        let name = self.parse_object_name(true)?;
1538        let mut actions = Vec::new();
1539        loop {
1540            let action = if self.parse_keywords(&["ADD", "COLUMN"]) {
1541                let if_not_exists = self.parse_keywords(&["IF", "NOT", "EXISTS"]);
1542                AlterAction::AddColumn {
1543                    if_not_exists,
1544                    column: self.parse_column_def()?,
1545                }
1546            } else if self.parse_keywords(&["DROP", "COLUMN"]) {
1547                let if_exists = self.parse_keywords(&["IF", "EXISTS"]);
1548                AlterAction::DropColumn {
1549                    if_exists,
1550                    name: self.parse_identifier()?,
1551                }
1552            } else if self.parse_keywords(&["RENAME", "TO"]) {
1553                AlterAction::RenameTo(self.parse_object_name(true)?)
1554            } else if self.parse_keywords(&["RENAME", "COLUMN"]) {
1555                let if_exists = self.parse_keywords(&["IF", "EXISTS"]);
1556                let from = self.parse_identifier()?;
1557                self.expect_keyword("TO")?;
1558                AlterAction::RenameColumn {
1559                    if_exists,
1560                    from,
1561                    to: self.parse_identifier()?,
1562                }
1563            } else if self.parse_keywords(&["SET", "DEFAULT", "COLLATE"]) {
1564                AlterAction::SetDefaultCollate(self.parse_expr()?)
1565            } else if self.parse_keywords(&["SET", "OPTIONS"]) {
1566                AlterAction::SetOptions(self.parse_options_body()?)
1567            } else if self.parse_keywords(&["ALTER", "COLUMN"]) {
1568                let if_exists = self.parse_keywords(&["IF", "EXISTS"]);
1569                let name = self.parse_identifier()?;
1570                let action = if self.parse_keywords(&["SET", "OPTIONS"]) {
1571                    AlterColumnAction::SetOptions(self.parse_options_body()?)
1572                } else if self.parse_keywords(&["DROP", "NOT", "NULL"]) {
1573                    AlterColumnAction::DropNotNull
1574                } else if self.parse_keywords(&["SET", "DATA", "TYPE"]) {
1575                    AlterColumnAction::SetDataType(self.parse_data_type()?)
1576                } else if self.parse_keywords(&["SET", "DEFAULT"]) {
1577                    AlterColumnAction::SetDefault(self.parse_expr()?)
1578                } else if self.parse_keywords(&["DROP", "DEFAULT"]) {
1579                    AlterColumnAction::DropDefault
1580                } else {
1581                    return Err(self.error("unsupported ALTER COLUMN action"));
1582                };
1583                AlterAction::AlterColumn {
1584                    if_exists,
1585                    name,
1586                    action,
1587                }
1588            } else {
1589                return Err(self.error("unsupported ALTER action"));
1590            };
1591            actions.push(action);
1592            if !self.consume_punct(Punct::Comma) {
1593                break;
1594            }
1595        }
1596        if !(self.at_end() || self.peek_punct(Punct::Semicolon)) {
1597            return Err(self.error("unsupported ALTER clause"));
1598        }
1599        Ok(Statement::AlterTable(Box::new(AlterTable {
1600            object_type,
1601            if_exists,
1602            name,
1603            actions,
1604        })))
1605    }
1606
1607    fn parse_declare(&mut self) -> Result<Statement> {
1608        self.expect_keyword("DECLARE")?;
1609        let names = self.parse_identifier_list()?;
1610        let data_type =
1611            if self.peek_keyword("DEFAULT") || self.at_end() || self.peek_punct(Punct::Semicolon) {
1612                None
1613            } else {
1614                Some(self.parse_data_type()?)
1615            };
1616        let default = if self.parse_keyword("DEFAULT") {
1617            Some(self.parse_expr()?)
1618        } else {
1619            None
1620        };
1621        Ok(Statement::Declare {
1622            names,
1623            data_type,
1624            default,
1625        })
1626    }
1627
1628    fn parse_set(&mut self) -> Result<Statement> {
1629        self.expect_keyword("SET")?;
1630        let targets = if self.consume_punct(Punct::LParen) {
1631            let mut out = vec![self.parse_set_target()?];
1632            while self.consume_punct(Punct::Comma) {
1633                out.push(self.parse_set_target()?);
1634            }
1635            self.expect_punct(Punct::RParen)?;
1636            out
1637        } else {
1638            vec![self.parse_set_target()?]
1639        };
1640        self.expect_punct(Punct::Eq)?;
1641        let value = self.parse_expr()?;
1642        Ok(Statement::Set { targets, value })
1643    }
1644
1645    fn parse_set_target(&mut self) -> Result<Expr> {
1646        if let Some(TokenKind::SystemVariable(name)) = self.peek().map(|t| t.kind.clone()) {
1647            self.pos += 1;
1648            return Ok(Expr::Parameter(Parameter::System(name)));
1649        }
1650        let first = self.parse_identifier()?;
1651        let mut parts = vec![first];
1652        while self.consume_punct(Punct::Dot) {
1653            parts.push(self.parse_path_part()?);
1654        }
1655        Ok(if parts.len() == 1 {
1656            Expr::Identifier(parts.remove(0))
1657        } else {
1658            Expr::CompoundIdentifier(parts)
1659        })
1660    }
1661
1662    fn parse_begin(&mut self, label: Option<Ident>) -> Result<Statement> {
1663        self.expect_keyword("BEGIN")?;
1664        if self.parse_keyword("TRANSACTION") || self.at_end() || self.peek_punct(Punct::Semicolon) {
1665            if label.is_some() {
1666                return Err(self.error("a label must precede a block or loop"));
1667            }
1668            return Ok(Statement::Transaction(TransactionKind::Begin));
1669        }
1670        let body = self.parse_block(&["END", "EXCEPTION"])?;
1671        let exception = self.parse_exception_handler()?;
1672        self.expect_keyword("END")?;
1673        self.skip_end_label(&label);
1674        Ok(Statement::BeginEnd {
1675            label,
1676            body,
1677            exception,
1678        })
1679    }
1680
1681    fn parse_if(&mut self) -> Result<Statement> {
1682        self.expect_keyword("IF")?;
1683        let mut branches = Vec::new();
1684        let condition = self.parse_expr()?;
1685        self.expect_keyword("THEN")?;
1686        let body = self.parse_block(&["ELSEIF", "ELSE", "END"])?;
1687        branches.push(ConditionalBlock { condition, body });
1688        let mut else_branch = None;
1689        loop {
1690            if self.parse_keyword("ELSEIF") {
1691                let condition = self.parse_expr()?;
1692                self.expect_keyword("THEN")?;
1693                let body = self.parse_block(&["ELSEIF", "ELSE", "END"])?;
1694                branches.push(ConditionalBlock { condition, body });
1695            } else if self.parse_keyword("ELSE") {
1696                else_branch = Some(self.parse_block(&["END"])?);
1697            } else {
1698                break;
1699            }
1700        }
1701        self.expect_keywords(&["END", "IF"])?;
1702        Ok(Statement::If {
1703            branches,
1704            else_branch,
1705        })
1706    }
1707
1708    fn parse_case_statement(&mut self) -> Result<Statement> {
1709        self.expect_keyword("CASE")?;
1710        let operand = if self.peek_keyword("WHEN") {
1711            None
1712        } else {
1713            Some(self.parse_expr()?)
1714        };
1715        let mut branches = Vec::new();
1716        while self.parse_keyword("WHEN") {
1717            let condition = self.parse_expr()?;
1718            self.expect_keyword("THEN")?;
1719            let body = self.parse_block(&["WHEN", "ELSE", "END"])?;
1720            branches.push(ConditionalBlock { condition, body });
1721        }
1722        let else_branch = if self.parse_keyword("ELSE") {
1723            Some(self.parse_block(&["END"])?)
1724        } else {
1725            None
1726        };
1727        self.expect_keywords(&["END", "CASE"])?;
1728        Ok(Statement::Case {
1729            operand,
1730            branches,
1731            else_branch,
1732        })
1733    }
1734
1735    fn parse_execute(&mut self) -> Result<Statement> {
1736        self.expect_keywords(&["EXECUTE", "IMMEDIATE"])?;
1737        let sql = self.parse_expr()?;
1738        let into = if self.parse_keyword("INTO") {
1739            self.parse_identifier_list()?
1740        } else {
1741            Vec::new()
1742        };
1743        let mut using = Vec::new();
1744        if self.parse_keyword("USING") {
1745            loop {
1746                let expr = self.parse_expr()?;
1747                let alias = if self.parse_keyword("AS") {
1748                    Some(self.parse_identifier()?)
1749                } else {
1750                    None
1751                };
1752                using.push(ExprWithAlias { expr, alias });
1753                if !self.consume_punct(Punct::Comma) {
1754                    break;
1755                }
1756            }
1757        }
1758        Ok(Statement::ExecuteImmediate { sql, into, using })
1759    }
1760
1761    fn parse_export(&mut self) -> Result<Statement> {
1762        self.expect_keywords(&["EXPORT", "DATA"])?;
1763        let connection = if self.parse_keywords(&["WITH", "CONNECTION"]) {
1764            Some(self.parse_object_name(true)?)
1765        } else {
1766            None
1767        };
1768        let options = self.parse_optional_options()?;
1769        self.expect_keyword("AS")?;
1770        let query = self.parse_query()?;
1771        Ok(Statement::ExportData(Box::new(ExportData {
1772            connection,
1773            options,
1774            query: Box::new(query),
1775        })))
1776    }
1777
1778    fn parse_load(&mut self, start: usize) -> Result<Statement> {
1779        self.expect_keywords(&["LOAD", "DATA"])?;
1780        let overwrite = if self.parse_keyword("OVERWRITE") {
1781            true
1782        } else if self.parse_keyword("INTO") {
1783            false
1784        } else {
1785            return self.parse_raw(start);
1786        };
1787        let temporary = if self.parse_keyword("TEMP") || self.parse_keyword("TEMPORARY") {
1788            self.expect_keyword("TABLE")?;
1789            true
1790        } else {
1791            false
1792        };
1793        let table = self.parse_object_name(true)?;
1794        let rest_start = self.peek().map(|t| t.span.start);
1795        let mut depth = 0usize;
1796        let mut end = rest_start.unwrap_or(self.src.len());
1797        while let Some(token) = self.peek() {
1798            match token.kind {
1799                TokenKind::Punct(Punct::LParen) => depth += 1,
1800                TokenKind::Punct(Punct::RParen) => depth = depth.saturating_sub(1),
1801                TokenKind::Punct(Punct::Semicolon) if depth == 0 => break,
1802                _ => {}
1803            }
1804            end = token.span.end;
1805            self.pos += 1;
1806        }
1807        let rest = rest_start
1808            .map(|s| self.src[s..end].to_string())
1809            .unwrap_or_default();
1810        Ok(Statement::LoadData(Box::new(LoadData {
1811            overwrite,
1812            temporary,
1813            table,
1814            rest,
1815        })))
1816    }
1817
1818    // ------------------------------------------------------------------ queries
1819
1820    /// Whether the `(` at the current position opens a query rather than an expression or join.
1821    fn paren_starts_query(&self) -> bool {
1822        let mut n = 0;
1823        while self.peek_nth_punct(n, Punct::LParen) {
1824            n += 1;
1825        }
1826        n > 0
1827            && self.peek_nth(n).is_some_and(|t| {
1828                t.is_keyword("SELECT") || t.is_keyword("WITH") || t.is_keyword("FROM")
1829            })
1830    }
1831
1832    fn peek_query_start(&self) -> bool {
1833        self.peek_keyword("SELECT") || self.peek_keyword("WITH") || self.peek_keyword("FROM")
1834    }
1835
1836    /// Parse a query at the current position.
1837    pub fn parse_query(&mut self) -> Result<Query> {
1838        self.enter()?;
1839        let result = self.parse_query_inner();
1840        self.leave();
1841        result
1842    }
1843
1844    fn parse_query_inner(&mut self) -> Result<Query> {
1845        let with = if self.peek_keyword("WITH") && !self.peek_nth_punct(1, Punct::LParen) {
1846            Some(self.parse_with()?)
1847        } else {
1848            None
1849        };
1850        let body = self.parse_set_expr()?;
1851        let order_by = if self.parse_keywords(&["ORDER", "BY"]) {
1852            self.parse_order_by_list()?
1853        } else {
1854            Vec::new()
1855        };
1856        let limit = if self.parse_keyword("LIMIT") {
1857            Some(self.parse_limit_body()?)
1858        } else {
1859            None
1860        };
1861        let mut pipes = Vec::new();
1862        while self.consume_punct(Punct::Pipe) {
1863            pipes.push(self.parse_pipe_operator()?);
1864        }
1865        Ok(Query {
1866            with,
1867            body,
1868            order_by,
1869            limit,
1870            pipes,
1871        })
1872    }
1873
1874    fn parse_limit_body(&mut self) -> Result<Limit> {
1875        let count = self.parse_expr()?;
1876        let offset = if self.parse_keyword("OFFSET") {
1877            Some(self.parse_expr()?)
1878        } else {
1879            None
1880        };
1881        Ok(Limit { count, offset })
1882    }
1883
1884    fn parse_with(&mut self) -> Result<With> {
1885        self.expect_keyword("WITH")?;
1886        let recursive = self.parse_keyword("RECURSIVE");
1887        let mut ctes = Vec::new();
1888        loop {
1889            let name = self.parse_identifier()?;
1890            self.expect_keyword("AS")?;
1891            self.expect_punct(Punct::LParen)?;
1892            let query = self.parse_query()?;
1893            self.expect_punct(Punct::RParen)?;
1894            ctes.push(Cte {
1895                name,
1896                query: Box::new(query),
1897            });
1898            if !self.consume_punct(Punct::Comma) {
1899                break;
1900            }
1901        }
1902        Ok(With { recursive, ctes })
1903    }
1904
1905    fn parse_set_expr(&mut self) -> Result<SetExpr> {
1906        let mut left = self.parse_set_operand()?;
1907        while let Some((op, quantifier, mode, corresponding)) = self.parse_set_operator()? {
1908            let right = self.parse_set_operand()?;
1909            left = SetExpr::SetOperation {
1910                op,
1911                quantifier,
1912                mode,
1913                corresponding,
1914                left: Box::new(left),
1915                right: Box::new(right),
1916            };
1917        }
1918        Ok(left)
1919    }
1920
1921    /// A set operator with its quantifier and column matching, if one starts here.
1922    #[allow(clippy::type_complexity)]
1923    fn parse_set_operator(
1924        &mut self,
1925    ) -> Result<
1926        Option<(
1927            SetOperator,
1928            SetQuantifier,
1929            Option<SetOpMode>,
1930            Option<Corresponding>,
1931        )>,
1932    > {
1933        let is_op = |p: &Self, n: usize| {
1934            p.peek_nth_keyword(n, "UNION")
1935                || p.peek_nth_keyword(n, "INTERSECT")
1936                || p.peek_nth_keyword(n, "EXCEPT")
1937        };
1938        let mode = if (self.peek_keyword("FULL") || self.peek_keyword("LEFT"))
1939            && (is_op(self, 1) || (self.peek_nth_keyword(1, "OUTER") && is_op(self, 2)))
1940        {
1941            let mode = if self.parse_keyword("FULL") {
1942                SetOpMode::Full
1943            } else {
1944                self.parse_keyword("LEFT");
1945                SetOpMode::Left
1946            };
1947            self.parse_keyword("OUTER");
1948            Some(mode)
1949        } else if self.peek_keyword("INNER") && is_op(self, 1) {
1950            self.parse_keyword("INNER");
1951            Some(SetOpMode::Inner)
1952        } else {
1953            None
1954        };
1955        let op = if self.parse_keyword("UNION") {
1956            SetOperator::Union
1957        } else if self.parse_keyword("INTERSECT") {
1958            SetOperator::Intersect
1959        } else if self.parse_keyword("EXCEPT") {
1960            SetOperator::Except
1961        } else {
1962            return Ok(None);
1963        };
1964        let quantifier = if self.parse_keyword("ALL") {
1965            SetQuantifier::All
1966        } else if self.parse_keyword("DISTINCT") {
1967            SetQuantifier::Distinct
1968        } else {
1969            SetQuantifier::None
1970        };
1971        let corresponding = self.parse_corresponding()?;
1972        Ok(Some((op, quantifier, mode, corresponding)))
1973    }
1974
1975    fn parse_corresponding(&mut self) -> Result<Option<Corresponding>> {
1976        if self.parse_keywords(&["BY", "NAME"]) {
1977            let on = if self.parse_keyword("ON") {
1978                self.parse_parenthesized_identifiers()?
1979            } else {
1980                Vec::new()
1981            };
1982            return Ok(Some(Corresponding::ByName(on)));
1983        }
1984        let strict = self.parse_keyword("STRICT");
1985        if self.parse_keyword("CORRESPONDING") {
1986            let by = if self.parse_keyword("BY") {
1987                self.parse_parenthesized_identifiers()?
1988            } else {
1989                Vec::new()
1990            };
1991            return Ok(Some(Corresponding::Corresponding { strict, by }));
1992        }
1993        if strict {
1994            return Err(self.error("expected CORRESPONDING"));
1995        }
1996        Ok(None)
1997    }
1998
1999    fn parse_set_operand(&mut self) -> Result<SetExpr> {
2000        if self.peek_keyword("SELECT") {
2001            return Ok(SetExpr::Select(Box::new(self.parse_select()?)));
2002        }
2003        if self.peek_keyword("FROM") {
2004            self.parse_keyword("FROM");
2005            return Ok(SetExpr::From(self.parse_from_list()?));
2006        }
2007        if self.consume_punct(Punct::LParen) {
2008            let query = self.parse_query()?;
2009            self.expect_punct(Punct::RParen)?;
2010            return Ok(SetExpr::Query(Box::new(query)));
2011        }
2012        Err(self.error("expected SELECT, FROM or '('"))
2013    }
2014
2015    fn parse_select(&mut self) -> Result<Select> {
2016        self.expect_keyword("SELECT")?;
2017        let distinct = if self.parse_keyword("DISTINCT") {
2018            true
2019        } else {
2020            self.parse_keyword("ALL");
2021            false
2022        };
2023        let select_as = self.parse_select_as();
2024        let projection = self.parse_select_items()?;
2025        let mut select = Select::new(projection);
2026        select.distinct = distinct;
2027        select.select_as = select_as;
2028        if self.parse_keyword("FROM") {
2029            select.from = self.parse_from_list()?;
2030        }
2031        if self.parse_keyword("WHERE") {
2032            select.where_clause = Some(self.parse_expr()?);
2033        }
2034        if self.parse_keywords(&["GROUP", "BY"]) {
2035            select.group_by = Some(self.parse_group_by()?);
2036        }
2037        if self.parse_keyword("HAVING") {
2038            select.having = Some(self.parse_expr()?);
2039        }
2040        if self.parse_keyword("QUALIFY") {
2041            select.qualify = Some(self.parse_expr()?);
2042        }
2043        if self.parse_keyword("WINDOW") {
2044            loop {
2045                let name = self.parse_identifier()?;
2046                self.expect_keyword("AS")?;
2047                let spec = if self.peek_punct(Punct::LParen) {
2048                    self.parse_window_spec()?
2049                } else {
2050                    WindowSpec {
2051                        base: Some(self.parse_identifier()?),
2052                        ..WindowSpec::default()
2053                    }
2054                };
2055                select.window.push(NamedWindow { name, spec });
2056                if !self.consume_punct(Punct::Comma) {
2057                    break;
2058                }
2059            }
2060        }
2061        Ok(select)
2062    }
2063
2064    fn parse_select_as(&mut self) -> Option<SelectAs> {
2065        if self.parse_keywords(&["AS", "STRUCT"]) {
2066            Some(SelectAs::Struct)
2067        } else if self.parse_keywords(&["AS", "VALUE"]) {
2068            Some(SelectAs::Value)
2069        } else {
2070            None
2071        }
2072    }
2073
2074    /// Whether the current token ends a list of select items (so a trailing comma before it is allowed).
2075    fn at_select_list_end(&self) -> bool {
2076        match self.peek() {
2077            None => true,
2078            Some(t)
2079                if t.is_punct(Punct::RParen)
2080                    || t.is_punct(Punct::Semicolon)
2081                    || t.is_punct(Punct::Pipe) =>
2082            {
2083                true
2084            }
2085            Some(t) => [
2086                "FROM",
2087                "WHERE",
2088                "GROUP",
2089                "HAVING",
2090                "QUALIFY",
2091                "WINDOW",
2092                "ORDER",
2093                "LIMIT",
2094                "UNION",
2095                "INTERSECT",
2096                "EXCEPT",
2097            ]
2098            .iter()
2099            .any(|k| t.is_keyword(k)),
2100        }
2101    }
2102
2103    fn parse_select_items(&mut self) -> Result<Vec<SelectItem>> {
2104        let mut items = vec![self.parse_select_item()?];
2105        while self.consume_punct(Punct::Comma) {
2106            if self.at_select_list_end() {
2107                break; // a trailing comma
2108            }
2109            items.push(self.parse_select_item()?);
2110        }
2111        Ok(items)
2112    }
2113
2114    fn parse_select_item(&mut self) -> Result<SelectItem> {
2115        if self.consume_punct(Punct::Star) {
2116            return Ok(SelectItem::Wildcard(self.parse_wildcard_options()?));
2117        }
2118        let expr = self.parse_expr()?;
2119        if self.peek_punct(Punct::Dot) && self.peek_nth_punct(1, Punct::Star) {
2120            self.pos += 2;
2121            return Ok(SelectItem::QualifiedWildcard {
2122                qualifier: expr,
2123                options: self.parse_wildcard_options()?,
2124            });
2125        }
2126        let alias = self.parse_optional_alias(false)?;
2127        Ok(SelectItem::Expr { expr, alias })
2128    }
2129
2130    fn parse_wildcard_options(&mut self) -> Result<WildcardOptions> {
2131        let mut options = WildcardOptions::default();
2132        if self.peek_keyword("EXCEPT") && self.peek_nth_punct(1, Punct::LParen) {
2133            self.parse_keyword("EXCEPT");
2134            options.except = self.parse_parenthesized_identifiers()?;
2135        }
2136        if self.peek_keyword("REPLACE") && self.peek_nth_punct(1, Punct::LParen) {
2137            self.parse_keyword("REPLACE");
2138            self.expect_punct(Punct::LParen)?;
2139            loop {
2140                let expr = self.parse_expr()?;
2141                self.expect_keyword("AS")?;
2142                let alias = self.parse_identifier()?;
2143                options.replace.push(ExprWithAlias {
2144                    expr,
2145                    alias: Some(alias),
2146                });
2147                if !self.consume_punct(Punct::Comma) {
2148                    break;
2149                }
2150            }
2151            self.expect_punct(Punct::RParen)?;
2152        }
2153        Ok(options)
2154    }
2155
2156    fn parse_group_by(&mut self) -> Result<GroupBy> {
2157        if self.parse_keyword("ALL") {
2158            return Ok(GroupBy::All);
2159        }
2160        let mut items = vec![self.parse_group_by_item()?];
2161        while self.consume_punct(Punct::Comma) {
2162            items.push(self.parse_group_by_item()?);
2163        }
2164        Ok(GroupBy::Items(items))
2165    }
2166
2167    fn parse_group_by_item(&mut self) -> Result<GroupByItem> {
2168        if self.peek_keyword("ROLLUP") || self.peek_keyword("CUBE") {
2169            let rollup = self.parse_keyword("ROLLUP");
2170            if !rollup {
2171                self.parse_keyword("CUBE");
2172            }
2173            self.expect_punct(Punct::LParen)?;
2174            let mut exprs = vec![self.parse_expr()?];
2175            while self.consume_punct(Punct::Comma) {
2176                exprs.push(self.parse_expr()?);
2177            }
2178            self.expect_punct(Punct::RParen)?;
2179            return Ok(if rollup {
2180                GroupByItem::Rollup(exprs)
2181            } else {
2182                GroupByItem::Cube(exprs)
2183            });
2184        }
2185        if self.parse_keywords(&["GROUPING", "SETS"]) {
2186            self.expect_punct(Punct::LParen)?;
2187            let mut sets = vec![self.parse_group_by_item()?];
2188            while self.consume_punct(Punct::Comma) {
2189                sets.push(self.parse_group_by_item()?);
2190            }
2191            self.expect_punct(Punct::RParen)?;
2192            return Ok(GroupByItem::GroupingSets(sets));
2193        }
2194        if self.peek_punct(Punct::LParen) && self.peek_nth_punct(1, Punct::RParen) {
2195            self.pos += 2;
2196            return Ok(GroupByItem::Empty);
2197        }
2198        Ok(GroupByItem::Expr(self.parse_expr()?))
2199    }
2200
2201    fn parse_order_by_list(&mut self) -> Result<Vec<OrderByExpr>> {
2202        let mut items = vec![self.parse_order_by_expr()?];
2203        while self.consume_punct(Punct::Comma) {
2204            items.push(self.parse_order_by_expr()?);
2205        }
2206        Ok(items)
2207    }
2208
2209    fn parse_order_by_expr(&mut self) -> Result<OrderByExpr> {
2210        let expr = self.parse_expr()?;
2211        let collate = if self.parse_keyword("COLLATE") {
2212            Some(self.parse_expr()?)
2213        } else {
2214            None
2215        };
2216        let (asc, nulls_first) = self.parse_order_spec();
2217        Ok(OrderByExpr {
2218            expr,
2219            collate,
2220            asc,
2221            nulls_first,
2222        })
2223    }
2224
2225    fn parse_order_spec(&mut self) -> (Option<bool>, Option<bool>) {
2226        let asc = if self.parse_keyword("ASC") {
2227            Some(true)
2228        } else if self.parse_keyword("DESC") {
2229            Some(false)
2230        } else {
2231            None
2232        };
2233        let nulls_first = if self.parse_keywords(&["NULLS", "FIRST"]) {
2234            Some(true)
2235        } else if self.parse_keywords(&["NULLS", "LAST"]) {
2236            Some(false)
2237        } else {
2238            None
2239        };
2240        (asc, nulls_first)
2241    }
2242
2243    // ------------------------------------------------------------------ FROM
2244
2245    fn parse_from_list(&mut self) -> Result<Vec<TableWithJoins>> {
2246        let mut items = vec![self.parse_table_with_joins()?];
2247        while self.consume_punct(Punct::Comma) {
2248            items.push(self.parse_table_with_joins()?);
2249        }
2250        Ok(items)
2251    }
2252
2253    fn parse_table_with_joins(&mut self) -> Result<TableWithJoins> {
2254        let mut relation = self.parse_table_factor()?;
2255        let mut joins = Vec::new();
2256        loop {
2257            if self.extended
2258                && self.peek_keyword("LEFT")
2259                && (self.peek_nth_keyword(1, "SEMI") || self.peek_nth_keyword(1, "ANTI"))
2260                && self.peek_nth_keyword(2, "JOIN")
2261            {
2262                if !joins.is_empty() {
2263                    return Err(
2264                        self.error("LEFT SEMI/ANTI JOIN after other joins is not supported")
2265                    );
2266                }
2267                self.pos += 1;
2268                let anti = self.peek_keyword("ANTI");
2269                self.pos += 2;
2270                let right = self.parse_table_factor()?;
2271                self.expect_keyword("ON")?;
2272                let on = self.parse_expr()?;
2273                relation = self.semi_join_factor(relation, right, on, anti)?;
2274                continue;
2275            }
2276            match self.parse_join()? {
2277                Some(join) => joins.push(join),
2278                None => break,
2279            }
2280        }
2281        Ok(TableWithJoins { relation, joins })
2282    }
2283
2284    /// `left LEFT SEMI|ANTI JOIN right ON on` as `(SELECT * FROM left WHERE [NOT] EXISTS (SELECT 1
2285    /// FROM right WHERE on)) AS <left's name>`.
2286    fn semi_join_factor(
2287        &self,
2288        left: TableFactor,
2289        right: TableFactor,
2290        mut on: Expr,
2291        anti: bool,
2292    ) -> Result<TableFactor> {
2293        fn relation_name(factor: &TableFactor) -> Option<&Ident> {
2294            match factor {
2295                TableFactor::Table { alias: Some(a), .. }
2296                | TableFactor::Derived { alias: Some(a), .. } => Some(a),
2297                TableFactor::Table {
2298                    name, alias: None, ..
2299                } => name.0.last(),
2300                _ => None,
2301            }
2302        }
2303        fn relation_columns(factor: &TableFactor) -> Option<Vec<String>> {
2304            let TableFactor::Derived { subquery, .. } = factor else {
2305                return None;
2306            };
2307            match &subquery.body {
2308                SetExpr::Select(select) if select.select_as.is_none() => subquery.output_names(),
2309                _ => None,
2310            }
2311        }
2312        let (Some(left_name), Some(right_name)) = (relation_name(&left), relation_name(&right))
2313        else {
2314            return Err(self.error("a semi or anti join needs named relations"));
2315        };
2316        if left_name.value.eq_ignore_ascii_case(&right_name.value) {
2317            return Err(self.error("a semi or anti join needs distinct relation names"));
2318        }
2319        let name = left_name.clone();
2320        struct JoinScope<'a> {
2321            names: [&'a Ident; 2],
2322            columns: [Option<Vec<String>>; 2],
2323            valid: bool,
2324        }
2325        impl JoinScope<'_> {
2326            fn owner(&self, column: &str) -> Option<&Ident> {
2327                let [Some(left), Some(right)] = &self.columns else {
2328                    return None;
2329                };
2330                let count = |names: &[String]| {
2331                    names
2332                        .iter()
2333                        .filter(|name| name.eq_ignore_ascii_case(column))
2334                        .count()
2335                };
2336                match (count(left), count(right)) {
2337                    (1, 0) => Some(self.names[0]),
2338                    (0, 1) => Some(self.names[1]),
2339                    _ => None,
2340                }
2341            }
2342        }
2343        impl Visitor for JoinScope<'_> {
2344            fn visit_expr(&mut self, expr: &Expr) {
2345                if let Some(parts) = expr.column_parts() {
2346                    self.valid &= match parts.as_slice() {
2347                        [column] => self.owner(column).is_some(),
2348                        [qualifier, _] => self
2349                            .names
2350                            .iter()
2351                            .any(|name| name.value.eq_ignore_ascii_case(qualifier)),
2352                        _ => false,
2353                    };
2354                }
2355            }
2356
2357            fn visit_query(&mut self, _query: &Query) {
2358                self.valid = false;
2359            }
2360        }
2361        // Moving ON into EXISTS creates an inner scope. Resolve unqualified names only when
2362        // both projections establish exactly one owner, then qualify them before moving ON.
2363        let mut scope = JoinScope {
2364            names: [left_name, right_name],
2365            columns: [relation_columns(&left), relation_columns(&right)],
2366            valid: true,
2367        };
2368        walk_expr(&on, &mut scope);
2369        if !scope.valid {
2370            return Err(self.error(
2371                "a semi or anti join ON needs unambiguous columns from either side and no subqueries",
2372            ));
2373        }
2374        walk_expr_mut(&mut on, false, &mut |expr| {
2375            if let Expr::Identifier(column) = expr {
2376                if let Some(owner) = scope.owner(&column.value) {
2377                    *expr = Expr::CompoundIdentifier(vec![owner.clone(), column.clone()]);
2378                }
2379            }
2380        });
2381        let mut inner = Select::new(vec![SelectItem::expr(Expr::Literal(Literal::int(1)), None)]);
2382        inner.from = vec![TableWithJoins {
2383            relation: right,
2384            joins: Vec::new(),
2385        }];
2386        inner.where_clause = Some(on);
2387        let exists = Expr::Exists(Box::new(Query::from_select(inner)));
2388        let mut outer = Select::new(vec![SelectItem::Wildcard(WildcardOptions::default())]);
2389        outer.from = vec![TableWithJoins {
2390            relation: left,
2391            joins: Vec::new(),
2392        }];
2393        outer.where_clause = Some(if anti {
2394            Expr::UnaryOp {
2395                op: UnaryOperator::Not,
2396                expr: Box::new(exists),
2397            }
2398        } else {
2399            exists
2400        });
2401        Ok(TableFactor::Derived {
2402            subquery: Box::new(Query::from_select(outer)),
2403            alias: Some(name),
2404            sample: None,
2405        })
2406    }
2407
2408    /// `(VALUES (a, b), (c, d)) [AS t [(x, y)]]` as a union of selects.
2409    fn parse_values_factor(&mut self) -> Result<TableFactor> {
2410        self.expect_punct(Punct::LParen)?;
2411        self.expect_keyword("VALUES")?;
2412        let mut rows: Vec<Vec<Expr>> = Vec::new();
2413        loop {
2414            self.expect_punct(Punct::LParen)?;
2415            let mut row = vec![self.parse_expr()?];
2416            while self.consume_punct(Punct::Comma) {
2417                row.push(self.parse_expr()?);
2418            }
2419            self.expect_punct(Punct::RParen)?;
2420            if rows.first().is_some_and(|first| first.len() != row.len()) {
2421                return Err(self.error("VALUES rows have different widths"));
2422            }
2423            rows.push(row);
2424            if !self.consume_punct(Punct::Comma) {
2425                break;
2426            }
2427        }
2428        self.expect_punct(Punct::RParen)?;
2429        let alias = self.parse_optional_alias(true)?;
2430        let width = rows[0].len();
2431        let names: Vec<Ident> = if alias.is_some() && self.peek_punct(Punct::LParen) {
2432            self.parse_parenthesized_identifiers()?
2433        } else {
2434            (0..width)
2435                .map(|i| Ident::new(format!("EXPR${i}")))
2436                .collect()
2437        };
2438        if names.len() != width {
2439            return Err(self.error("the VALUES column list does not match its rows"));
2440        }
2441        let mut body: Option<SetExpr> = None;
2442        for (i, row) in rows.into_iter().enumerate() {
2443            let projection = row
2444                .into_iter()
2445                .enumerate()
2446                .map(|(c, e)| SelectItem::Expr {
2447                    expr: e,
2448                    alias: (i == 0).then(|| names[c].clone()),
2449                })
2450                .collect();
2451            let select = SetExpr::Select(Box::new(Select::new(projection)));
2452            body = Some(match body {
2453                None => select,
2454                Some(left) => SetExpr::SetOperation {
2455                    op: SetOperator::Union,
2456                    quantifier: SetQuantifier::All,
2457                    mode: None,
2458                    corresponding: None,
2459                    left: Box::new(left),
2460                    right: Box::new(select),
2461                },
2462            });
2463        }
2464        Ok(TableFactor::Derived {
2465            subquery: Box::new(Query::from_body(body.expect("a row"))),
2466            alias,
2467            sample: None,
2468        })
2469    }
2470
2471    /// A join operator and its right side, if one starts here.
2472    fn parse_join(&mut self) -> Result<Option<Join>> {
2473        let start = self.pos;
2474        let natural = self.parse_keyword("NATURAL");
2475        let kind = if self.parse_keyword("CROSS") {
2476            Some(JoinKind::Cross)
2477        } else if self.parse_keyword("INNER") {
2478            Some(JoinKind::Inner)
2479        } else if self.parse_keyword("LEFT") {
2480            self.parse_keyword("OUTER");
2481            Some(JoinKind::Left)
2482        } else if self.parse_keyword("RIGHT") {
2483            self.parse_keyword("OUTER");
2484            Some(JoinKind::Right)
2485        } else if self.parse_keyword("FULL") {
2486            self.parse_keyword("OUTER");
2487            Some(JoinKind::Full)
2488        } else {
2489            None
2490        };
2491        if !self.peek_keyword("JOIN") {
2492            // `LEFT UNION ALL ...` (a set operation mode) or nothing at all
2493            for role in &mut self.roles[start..self.pos] {
2494                *role = TokenRole::Other;
2495            }
2496            self.pos = start;
2497            return Ok(None);
2498        }
2499        self.parse_keyword("JOIN");
2500        let kind = kind.unwrap_or(JoinKind::Inner);
2501        let relation = self.parse_table_factor()?;
2502        let constraint = self.parse_join_constraint()?;
2503        Ok(Some(Join {
2504            kind,
2505            natural,
2506            relation,
2507            constraint,
2508        }))
2509    }
2510
2511    fn parse_join_constraint(&mut self) -> Result<JoinConstraint> {
2512        if self.parse_keyword("ON") {
2513            Ok(JoinConstraint::On(self.parse_expr()?))
2514        } else if self.parse_keyword("USING") {
2515            Ok(JoinConstraint::Using(
2516                self.parse_parenthesized_identifiers()?,
2517            ))
2518        } else {
2519            Ok(JoinConstraint::None)
2520        }
2521    }
2522
2523    /// One FROM item: a table, subquery, `UNNEST`, table function or parenthesized join, with
2524    /// any `PIVOT`, `UNPIVOT` and `TABLESAMPLE` after it.
2525    pub fn parse_table_factor(&mut self) -> Result<TableFactor> {
2526        self.enter()?;
2527        let result = self.parse_table_factor_inner();
2528        self.leave();
2529        result
2530    }
2531
2532    fn parse_table_factor_inner(&mut self) -> Result<TableFactor> {
2533        if self.extended && self.peek_punct(Punct::LParen) && self.peek_nth_keyword(1, "VALUES") {
2534            return self.parse_values_factor();
2535        }
2536        let mut factor = if self.peek_punct(Punct::LParen) {
2537            let as_query = if self.paren_starts_query() {
2538                self.attempt(|p| {
2539                    p.expect_punct(Punct::LParen)?;
2540                    let q = p.parse_query()?;
2541                    p.expect_punct(Punct::RParen)?;
2542                    Ok(q)
2543                })
2544            } else {
2545                None
2546            };
2547            match as_query {
2548                Some(query) => {
2549                    let alias = self.parse_optional_alias(true)?;
2550                    TableFactor::Derived {
2551                        subquery: Box::new(query),
2552                        alias,
2553                        sample: None,
2554                    }
2555                }
2556                None => {
2557                    self.expect_punct(Punct::LParen)?;
2558                    let table = self.parse_table_with_joins()?;
2559                    self.expect_punct(Punct::RParen)?;
2560                    let alias = self.parse_optional_alias(true)?;
2561                    TableFactor::NestedJoin {
2562                        table: Box::new(table),
2563                        alias,
2564                    }
2565                }
2566            }
2567        } else if self.peek_keyword("UNNEST") && self.peek_nth_punct(1, Punct::LParen) {
2568            self.parse_keyword("UNNEST");
2569            self.expect_punct(Punct::LParen)?;
2570            let array = self.parse_expr()?;
2571            self.expect_punct(Punct::RParen)?;
2572            let alias = self.parse_optional_alias(true)?;
2573            let with_offset = if self.parse_keywords(&["WITH", "OFFSET"]) {
2574                Some(self.parse_optional_alias(true)?)
2575            } else {
2576                None
2577            };
2578            TableFactor::Unnest {
2579                array: Box::new(array),
2580                alias,
2581                with_offset,
2582            }
2583        } else {
2584            let name = self.parse_object_name(true)?;
2585            if self.peek_punct(Punct::LParen) {
2586                let function = self.parse_function_call(name, self.pos.saturating_sub(1))?;
2587                let alias = self.parse_optional_alias(true)?;
2588                TableFactor::TableFunction { function, alias }
2589            } else {
2590                let mut system_time = self.parse_system_time()?;
2591                let alias = self.parse_optional_alias(true)?;
2592                if system_time.is_none() {
2593                    system_time = self.parse_system_time()?;
2594                }
2595                TableFactor::Table {
2596                    name,
2597                    alias,
2598                    system_time,
2599                    sample: None,
2600                }
2601            }
2602        };
2603        loop {
2604            if self.peek_keyword("PIVOT") && self.peek_nth_punct(1, Punct::LParen) {
2605                self.parse_keyword("PIVOT");
2606                let (aggregates, value_column, values) = self.parse_pivot_body()?;
2607                let alias = self.parse_optional_alias(true)?;
2608                factor = TableFactor::Pivot {
2609                    table: Box::new(factor),
2610                    aggregates,
2611                    value_column: Box::new(value_column),
2612                    values,
2613                    alias,
2614                };
2615            } else if self.peek_keyword("UNPIVOT")
2616                && (self.peek_nth_punct(1, Punct::LParen)
2617                    || self.peek_nth_keyword(1, "INCLUDE")
2618                    || self.peek_nth_keyword(1, "EXCLUDE"))
2619            {
2620                self.parse_keyword("UNPIVOT");
2621                let (include_nulls, value_columns, name_column, columns) =
2622                    self.parse_unpivot_body()?;
2623                let alias = self.parse_optional_alias(true)?;
2624                factor = TableFactor::Unpivot {
2625                    table: Box::new(factor),
2626                    include_nulls,
2627                    value_columns,
2628                    name_column,
2629                    columns,
2630                    alias,
2631                };
2632            } else if self.peek_keyword("MATCH_RECOGNIZE") && self.peek_nth_punct(1, Punct::LParen)
2633            {
2634                self.parse_keyword("MATCH_RECOGNIZE");
2635                let spec = self.parse_match_recognize_body()?;
2636                let alias = self.parse_optional_alias(true)?;
2637                factor = TableFactor::MatchRecognize {
2638                    table: Box::new(factor),
2639                    spec: Box::new(spec),
2640                    alias,
2641                };
2642            } else if self.peek_keyword("ALIGN") && self.peek_nth_punct(1, Punct::LParen) {
2643                self.parse_keyword("ALIGN");
2644                let spec = self.parse_align_body()?;
2645                let alias = self.parse_optional_alias(true)?;
2646                factor = TableFactor::Align {
2647                    table: Box::new(factor),
2648                    spec: Box::new(spec),
2649                    alias,
2650                };
2651            } else {
2652                break;
2653            }
2654        }
2655        if self.peek_keyword("TABLESAMPLE") {
2656            let parsed = self.parse_tablesample()?;
2657            match &mut factor {
2658                TableFactor::Table { sample, .. } | TableFactor::Derived { sample, .. } => {
2659                    *sample = Some(parsed)
2660                }
2661                _ => return Err(self.error("TABLESAMPLE applies to a table or subquery")),
2662            }
2663        }
2664        Ok(factor)
2665    }
2666
2667    fn parse_tablesample(&mut self) -> Result<TableSample> {
2668        self.expect_keyword("TABLESAMPLE")?;
2669        let method = self.parse_identifier()?;
2670        self.set_role(self.pos - 1, TokenRole::Keyword);
2671        self.expect_punct(Punct::LParen)?;
2672        let size = self.parse_expr()?;
2673        let unit = if self.parse_keyword("PERCENT") {
2674            SampleUnit::Percent
2675        } else {
2676            self.expect_keyword("ROWS")?;
2677            SampleUnit::Rows
2678        };
2679        self.expect_punct(Punct::RParen)?;
2680        Ok(TableSample { method, size, unit })
2681    }
2682
2683    fn parse_expr_with_alias_list(&mut self) -> Result<Vec<ExprWithAlias>> {
2684        let mut out = Vec::new();
2685        loop {
2686            let expr = self.parse_expr()?;
2687            let alias = self.parse_optional_alias(false)?;
2688            out.push(ExprWithAlias { expr, alias });
2689            if !self.consume_punct(Punct::Comma) {
2690                break;
2691            }
2692        }
2693        Ok(out)
2694    }
2695
2696    #[allow(clippy::type_complexity)]
2697    fn parse_pivot_body(&mut self) -> Result<(Vec<ExprWithAlias>, Expr, Vec<ExprWithAlias>)> {
2698        self.expect_punct(Punct::LParen)?;
2699        let aggregates = self.parse_expr_with_alias_list()?;
2700        self.expect_keyword("FOR")?;
2701        let value_column = self.parse_subexpr(COMPARISON_PRECEDENCE)?;
2702        self.expect_keyword("IN")?;
2703        self.expect_punct(Punct::LParen)?;
2704        let values = self.parse_expr_with_alias_list()?;
2705        self.expect_punct(Punct::RParen)?;
2706        self.expect_punct(Punct::RParen)?;
2707        Ok((aggregates, value_column, values))
2708    }
2709
2710    #[allow(clippy::type_complexity)]
2711    fn parse_unpivot_body(
2712        &mut self,
2713    ) -> Result<(Option<bool>, Vec<Ident>, Ident, Vec<UnpivotColumns>)> {
2714        let include_nulls = if self.parse_keywords(&["INCLUDE", "NULLS"]) {
2715            Some(true)
2716        } else if self.parse_keywords(&["EXCLUDE", "NULLS"]) {
2717            Some(false)
2718        } else {
2719            None
2720        };
2721        self.expect_punct(Punct::LParen)?;
2722        let value_columns = if self.peek_punct(Punct::LParen) {
2723            self.parse_parenthesized_identifiers()?
2724        } else {
2725            vec![self.parse_identifier()?]
2726        };
2727        self.expect_keyword("FOR")?;
2728        let name_column = self.parse_identifier()?;
2729        self.expect_keyword("IN")?;
2730        self.expect_punct(Punct::LParen)?;
2731        let mut columns = Vec::new();
2732        loop {
2733            let cols = if self.peek_punct(Punct::LParen) {
2734                self.parse_parenthesized_identifiers()?
2735            } else {
2736                vec![self.parse_identifier()?]
2737            };
2738            let alias = if self.parse_keyword("AS") {
2739                Some(self.parse_prefix()?)
2740            } else {
2741                None
2742            };
2743            columns.push(UnpivotColumns {
2744                columns: cols,
2745                alias,
2746            });
2747            if !self.consume_punct(Punct::Comma) {
2748                break;
2749            }
2750        }
2751        self.expect_punct(Punct::RParen)?;
2752        self.expect_punct(Punct::RParen)?;
2753        Ok((include_nulls, value_columns, name_column, columns))
2754    }
2755
2756    // ------------------------------------------------------------------ MATCH_RECOGNIZE and ALIGN
2757
2758    /// An alias that must be written with `AS` (inside clauses whose next word could pass for one).
2759    fn parse_as_alias(&mut self) -> Result<Option<Ident>> {
2760        if self.parse_keyword("AS") {
2761            Ok(Some(self.parse_identifier()?))
2762        } else {
2763            Ok(None)
2764        }
2765    }
2766
2767    /// `( [PARTITION BY ...] ORDER BY ... MEASURES ... [AFTER MATCH SKIP ...] PATTERN (...) [DEFINE ...]
2768    /// [OPTIONS (...)] )`, the parentheses included.
2769    fn parse_match_recognize_body(&mut self) -> Result<MatchRecognize> {
2770        self.expect_punct(Punct::LParen)?;
2771        let mut partition_by = Vec::new();
2772        if self.parse_keywords(&["PARTITION", "BY"]) {
2773            loop {
2774                partition_by.push(self.parse_expr()?);
2775                if !self.consume_punct(Punct::Comma) {
2776                    break;
2777                }
2778            }
2779        }
2780        self.expect_keywords(&["ORDER", "BY"])?;
2781        let order_by = self.parse_order_by_list()?;
2782        self.expect_keyword("MEASURES")?;
2783        let mut measures = Vec::new();
2784        loop {
2785            let expr = self.parse_expr()?;
2786            self.expect_keyword("AS")?;
2787            measures.push((expr, self.parse_identifier()?));
2788            if !self.consume_punct(Punct::Comma) {
2789                break;
2790            }
2791        }
2792        let after_match = if self.parse_keywords(&["AFTER", "MATCH", "SKIP"]) {
2793            if self.parse_keywords(&["PAST", "LAST", "ROW"]) {
2794                Some(AfterMatchSkip::PastLastRow)
2795            } else {
2796                self.expect_keywords(&["TO", "NEXT", "ROW"])?;
2797                Some(AfterMatchSkip::ToNextRow)
2798            }
2799        } else {
2800            None
2801        };
2802        self.expect_keyword("PATTERN")?;
2803        self.expect_punct(Punct::LParen)?;
2804        let pattern = if self.peek_punct(Punct::RParen) {
2805            RowPattern::Empty
2806        } else {
2807            self.parse_row_pattern()?
2808        };
2809        self.expect_punct(Punct::RParen)?;
2810        let mut define = Vec::new();
2811        if self.parse_keyword("DEFINE") {
2812            loop {
2813                let symbol = self.parse_identifier()?;
2814                self.expect_keyword("AS")?;
2815                define.push((symbol, self.parse_expr()?));
2816                if !self.consume_punct(Punct::Comma) {
2817                    break;
2818                }
2819            }
2820        }
2821        let options = if self.parse_keyword("OPTIONS") {
2822            self.parse_options_body()?
2823        } else {
2824            Vec::new()
2825        };
2826        self.expect_punct(Punct::RParen)?;
2827        Ok(MatchRecognize {
2828            partition_by,
2829            order_by,
2830            measures,
2831            after_match,
2832            pattern,
2833            define,
2834            options,
2835        })
2836    }
2837
2838    /// `a | b c+`: alternation of concatenations of quantified primaries.
2839    fn parse_row_pattern(&mut self) -> Result<RowPattern> {
2840        let mut branches = vec![self.parse_row_pattern_concat()?];
2841        while self.consume_punct(Punct::Bar) {
2842            branches.push(self.parse_row_pattern_concat()?);
2843        }
2844        Ok(if branches.len() == 1 {
2845            branches.pop().unwrap()
2846        } else {
2847            RowPattern::Alternation(branches)
2848        })
2849    }
2850
2851    fn parse_row_pattern_concat(&mut self) -> Result<RowPattern> {
2852        let mut items = Vec::new();
2853        while !(self.at_end() || self.peek_punct(Punct::Bar) || self.peek_punct(Punct::RParen)) {
2854            let mut item = if self.consume_punct(Punct::LParen) {
2855                let inner = if self.peek_punct(Punct::RParen) {
2856                    RowPattern::Empty
2857                } else {
2858                    self.parse_row_pattern()?
2859                };
2860                self.expect_punct(Punct::RParen)?;
2861                RowPattern::Group(Box::new(inner))
2862            } else if self.consume_punct(Punct::Caret) {
2863                RowPattern::Start
2864            } else {
2865                RowPattern::Symbol(self.parse_identifier()?)
2866            };
2867            while let Some(quantifier) = self.parse_pattern_quantifier()? {
2868                let reluctant = self.consume_punct(Punct::Question);
2869                item = RowPattern::Quantified {
2870                    pattern: Box::new(item),
2871                    quantifier,
2872                    reluctant,
2873                };
2874            }
2875            items.push(item);
2876        }
2877        if items.is_empty() {
2878            return Err(self.error("expected a row pattern"));
2879        }
2880        Ok(if items.len() == 1 {
2881            items.pop().unwrap()
2882        } else {
2883            RowPattern::Concat(items)
2884        })
2885    }
2886
2887    fn parse_pattern_bound(&mut self) -> Result<Option<u64>> {
2888        match self.peek().map(|t| t.kind.clone()) {
2889            Some(TokenKind::Integer) => {
2890                let text = self.peek().unwrap().text.clone();
2891                let value = text
2892                    .parse::<u64>()
2893                    .map_err(|_| self.error("expected a whole number in a pattern quantifier"))?;
2894                self.pos += 1;
2895                Ok(Some(value))
2896            }
2897            _ => Ok(None),
2898        }
2899    }
2900
2901    fn parse_pattern_quantifier(&mut self) -> Result<Option<PatternQuantifier>> {
2902        if self.consume_punct(Punct::Star) {
2903            return Ok(Some(PatternQuantifier::ZeroOrMore));
2904        }
2905        if self.consume_punct(Punct::Plus) {
2906            return Ok(Some(PatternQuantifier::OneOrMore));
2907        }
2908        if self.consume_punct(Punct::Question) {
2909            return Ok(Some(PatternQuantifier::ZeroOrOne));
2910        }
2911        if !self.consume_punct(Punct::LBrace) {
2912            return Ok(None);
2913        }
2914        let min = self.parse_pattern_bound()?;
2915        let quantifier = if self.consume_punct(Punct::Comma) {
2916            let max = self.parse_pattern_bound()?;
2917            if let (Some(lo), Some(hi)) = (min, max) {
2918                if lo > hi {
2919                    return Err(self.error("a pattern quantifier's minimum is above its maximum"));
2920                }
2921            }
2922            PatternQuantifier::Range { min, max }
2923        } else {
2924            match min {
2925                Some(n) => PatternQuantifier::Exactly(n),
2926                None => return Err(self.error("expected a number in a pattern quantifier")),
2927            }
2928        };
2929        self.expect_punct(Punct::RBrace)?;
2930        Ok(Some(quantifier))
2931    }
2932
2933    /// The source text of the tokens from `start` up to (not including) the current one.
2934    fn source_between(&self, start: usize) -> String {
2935        if start >= self.pos {
2936            return String::new();
2937        }
2938        let from = self.tokens[start].span.start;
2939        let to = self.tokens[self.pos - 1].span.end;
2940        self.src[from..to].to_string()
2941    }
2942
2943    /// Skip a balanced token run up to a top-level word of `stops` or the closing parenthesis.
2944    fn skip_until_clause(&mut self, stops: &[&str]) -> Result<()> {
2945        let mut depth = 0usize;
2946        while let Some(token) = self.peek() {
2947            if token.is_punct(Punct::LParen) {
2948                depth += 1;
2949            } else if token.is_punct(Punct::RParen) {
2950                if depth == 0 {
2951                    return Ok(());
2952                }
2953                depth -= 1;
2954            } else if depth == 0 && stops.iter().any(|s| token.is_keyword(s)) {
2955                return Ok(());
2956            }
2957            self.pos += 1;
2958        }
2959        Err(self.error("unclosed parenthesis"))
2960    }
2961
2962    /// `( [TIMESTAMP column [AS name]] PERIOD interval [ORIGIN ...] [OUTPUT ...] [PARTITION BY ...]
2963    /// [METRICS ...] )`, the parentheses included.
2964    fn parse_align_body(&mut self) -> Result<Align> {
2965        self.expect_punct(Punct::LParen)?;
2966        let (timestamp, timestamp_alias) = if self.peek_keyword("TIMESTAMP")
2967            && self.peek_nth(1).is_some_and(Self::is_identifier_token)
2968            && !self.peek_nth_keyword(1, "PERIOD")
2969        {
2970            self.parse_keyword("TIMESTAMP");
2971            let column = self.parse_identifier()?;
2972            (Some(column), self.parse_as_alias()?)
2973        } else {
2974            (None, None)
2975        };
2976        self.expect_keyword("PERIOD")?;
2977        let period = self.parse_expr()?;
2978        let origin = if self.parse_keyword("ORIGIN") {
2979            Some(self.parse_expr()?)
2980        } else {
2981            None
2982        };
2983        let output = if self.parse_keyword("OUTPUT") {
2984            let start = self.pos;
2985            self.skip_until_clause(&["PARTITION", "METRICS"])?;
2986            if start == self.pos {
2987                return Err(self.error("expected the OUTPUT of ALIGN"));
2988            }
2989            Some(self.source_between(start))
2990        } else {
2991            None
2992        };
2993        let mut partition_by = Vec::new();
2994        if self.parse_keywords(&["PARTITION", "BY"]) {
2995            loop {
2996                let expr = self.parse_expr()?;
2997                let alias = self.parse_as_alias()?;
2998                partition_by.push(ExprWithAlias { expr, alias });
2999                if !self.consume_punct(Punct::Comma) {
3000                    break;
3001                }
3002            }
3003        }
3004        let mut metrics = Vec::new();
3005        if self.parse_keyword("METRICS") {
3006            loop {
3007                let expr = self.parse_expr()?;
3008                let within = if self.parse_keyword("WITHIN") {
3009                    if !matches!(expr, Expr::Function(_)) {
3010                        return Err(self.error("WITHIN follows an aggregate call"));
3011                    }
3012                    self.expect_punct(Punct::LParen)?;
3013                    let start = self.pos;
3014                    self.skip_until_clause(&[])?;
3015                    let text = self.source_between(start);
3016                    self.expect_punct(Punct::RParen)?;
3017                    Some(text)
3018                } else {
3019                    None
3020                };
3021                let alias = self.parse_as_alias()?;
3022                metrics.push(AlignMetric {
3023                    expr,
3024                    within,
3025                    alias,
3026                });
3027                if !self.consume_punct(Punct::Comma) {
3028                    break;
3029                }
3030            }
3031        }
3032        self.expect_punct(Punct::RParen)?;
3033        Ok(Align {
3034            timestamp,
3035            timestamp_alias,
3036            period,
3037            origin,
3038            output,
3039            partition_by,
3040            metrics,
3041        })
3042    }
3043
3044    // ------------------------------------------------------------------ pipe syntax
3045
3046    fn parse_pipe_expr_items(&mut self) -> Result<Vec<PipeExprItem>> {
3047        let mut out = Vec::new();
3048        loop {
3049            let expr = self.parse_expr()?;
3050            let alias = self.parse_optional_alias(false)?;
3051            let (asc, nulls_first) = self.parse_order_spec();
3052            out.push(PipeExprItem {
3053                expr,
3054                alias,
3055                asc,
3056                nulls_first,
3057            });
3058            if !self.consume_punct(Punct::Comma) || self.peek_keyword("GROUP") || self.at_pipe_end()
3059            {
3060                break;
3061            }
3062        }
3063        Ok(out)
3064    }
3065
3066    fn at_pipe_end(&self) -> bool {
3067        self.at_end()
3068            || self.peek_punct(Punct::Pipe)
3069            || self.peek_punct(Punct::RParen)
3070            || self.peek_punct(Punct::Semicolon)
3071    }
3072
3073    fn parse_pipe_operator(&mut self) -> Result<PipeOperator> {
3074        if self.parse_keyword("WHERE") {
3075            return Ok(PipeOperator::Where(self.parse_expr()?));
3076        }
3077        if self.parse_keyword("SELECT") {
3078            let distinct = if self.parse_keyword("DISTINCT") {
3079                true
3080            } else {
3081                self.parse_keyword("ALL");
3082                false
3083            };
3084            let select_as = self.parse_select_as();
3085            return Ok(PipeOperator::Select {
3086                distinct,
3087                select_as,
3088                items: self.parse_select_items()?,
3089            });
3090        }
3091        if self.parse_keyword("EXTEND") {
3092            return Ok(PipeOperator::Extend(self.parse_select_items()?));
3093        }
3094        if self.parse_keyword("WINDOW") {
3095            return Ok(PipeOperator::Window(self.parse_select_items()?));
3096        }
3097        if self.parse_keyword("SET") {
3098            return Ok(PipeOperator::Set(self.parse_assignments()?));
3099        }
3100        if self.parse_keyword("DROP") {
3101            let mut cols = vec![self.parse_identifier()?];
3102            while self.consume_punct(Punct::Comma) {
3103                if self.at_pipe_end() {
3104                    break;
3105                }
3106                cols.push(self.parse_identifier()?);
3107            }
3108            return Ok(PipeOperator::Drop(cols));
3109        }
3110        if self.parse_keyword("RENAME") {
3111            let mut pairs = Vec::new();
3112            loop {
3113                let from = self.parse_identifier()?;
3114                self.parse_keyword("AS");
3115                let to = self.parse_identifier()?;
3116                pairs.push((from, to));
3117                if !self.consume_punct(Punct::Comma) || self.at_pipe_end() {
3118                    break;
3119                }
3120            }
3121            return Ok(PipeOperator::Rename(pairs));
3122        }
3123        if self.parse_keyword("AS") {
3124            return Ok(PipeOperator::As(self.parse_identifier()?));
3125        }
3126        if self.parse_keyword("AGGREGATE") {
3127            let items = if self.peek_keyword("GROUP") || self.at_pipe_end() {
3128                Vec::new()
3129            } else {
3130                self.parse_pipe_expr_items()?
3131            };
3132            let mut group_by = Vec::new();
3133            let mut group_and_order = false;
3134            if self.parse_keywords(&["GROUP", "AND", "ORDER", "BY"]) {
3135                group_and_order = true;
3136                group_by = self.parse_pipe_expr_items()?;
3137            } else if self.parse_keywords(&["GROUP", "BY"]) {
3138                group_by = self.parse_pipe_expr_items()?;
3139            }
3140            return Ok(PipeOperator::Aggregate {
3141                items,
3142                group_by,
3143                group_and_order,
3144            });
3145        }
3146        if self.parse_keywords(&["ORDER", "BY"]) {
3147            return Ok(PipeOperator::OrderBy(self.parse_order_by_list()?));
3148        }
3149        if self.parse_keyword("LIMIT") {
3150            return Ok(PipeOperator::Limit(self.parse_limit_body()?));
3151        }
3152        if self.parse_keyword("DISTINCT") {
3153            return Ok(PipeOperator::Distinct);
3154        }
3155        if self.peek_keyword("TABLESAMPLE") {
3156            return Ok(PipeOperator::TableSample(self.parse_tablesample()?));
3157        }
3158        if self.parse_keyword("CALL") {
3159            let name = self.parse_object_name(true)?;
3160            let function = self.parse_function_call(name, self.pos.saturating_sub(1))?;
3161            let alias = self.parse_optional_alias(true)?;
3162            return Ok(PipeOperator::Call { function, alias });
3163        }
3164        if self.parse_keyword("PIVOT") {
3165            let (aggregates, value_column, values) = self.parse_pivot_body()?;
3166            let alias = self.parse_optional_alias(true)?;
3167            return Ok(PipeOperator::Pivot {
3168                aggregates,
3169                value_column: Box::new(value_column),
3170                values,
3171                alias,
3172            });
3173        }
3174        if self.parse_keyword("UNPIVOT") {
3175            let (include_nulls, value_columns, name_column, columns) = self.parse_unpivot_body()?;
3176            let alias = self.parse_optional_alias(true)?;
3177            return Ok(PipeOperator::Unpivot {
3178                include_nulls,
3179                value_columns,
3180                name_column,
3181                columns,
3182                alias,
3183            });
3184        }
3185        if self.peek_keyword("MATCH_RECOGNIZE") && self.peek_nth_punct(1, Punct::LParen) {
3186            self.parse_keyword("MATCH_RECOGNIZE");
3187            let spec = Box::new(self.parse_match_recognize_body()?);
3188            let alias = self.parse_optional_alias(true)?;
3189            return Ok(PipeOperator::MatchRecognize { spec, alias });
3190        }
3191        if self.peek_keyword("ALIGN") && self.peek_nth_punct(1, Punct::LParen) {
3192            self.parse_keyword("ALIGN");
3193            let spec = Box::new(self.parse_align_body()?);
3194            let alias = self.parse_optional_alias(true)?;
3195            return Ok(PipeOperator::Align { spec, alias });
3196        }
3197        if self.parse_keyword("ASSERT") {
3198            let condition = self.parse_expr()?;
3199            let mut payload = Vec::new();
3200            while self.consume_punct(Punct::Comma) {
3201                payload.push(self.parse_expr()?);
3202            }
3203            return Ok(PipeOperator::Assert { condition, payload });
3204        }
3205        if let Some((op, quantifier, mode, corresponding)) = self.parse_set_operator()? {
3206            let mut queries = Vec::new();
3207            loop {
3208                self.expect_punct(Punct::LParen)?;
3209                queries.push(self.parse_query()?);
3210                self.expect_punct(Punct::RParen)?;
3211                if !self.consume_punct(Punct::Comma) {
3212                    break;
3213                }
3214            }
3215            return Ok(PipeOperator::SetOperation {
3216                op,
3217                quantifier,
3218                mode,
3219                corresponding,
3220                queries,
3221            });
3222        }
3223        if let Some(join) = self.parse_join()? {
3224            return Ok(PipeOperator::Join(join));
3225        }
3226        Err(self.error("expected a pipe operator"))
3227    }
3228
3229    // ------------------------------------------------------------------ expressions
3230
3231    /// Parse a full expression.
3232    pub fn parse_expr(&mut self) -> Result<Expr> {
3233        self.parse_subexpr(0)
3234    }
3235
3236    fn parse_subexpr(&mut self, min_precedence: u8) -> Result<Expr> {
3237        self.enter()?;
3238        let result = (|| {
3239            let mut left = self.parse_prefix()?;
3240            loop {
3241                let precedence = self.infix_precedence();
3242                if precedence == 0 || precedence <= min_precedence {
3243                    break;
3244                }
3245                left = self.parse_infix(left, precedence)?;
3246            }
3247            Ok(left)
3248        })();
3249        self.leave();
3250        result
3251    }
3252
3253    fn infix_precedence(&self) -> u8 {
3254        let Some(token) = self.peek() else {
3255            return 0;
3256        };
3257        match &token.kind {
3258            TokenKind::Word => match token.upper().as_str() {
3259                "OR" => 1,
3260                "AND" => 2,
3261                "NOT" => {
3262                    if ["IN", "LIKE", "BETWEEN"]
3263                        .iter()
3264                        .any(|k| self.peek_nth_keyword(1, k))
3265                    {
3266                        COMPARISON_PRECEDENCE
3267                    } else {
3268                        0
3269                    }
3270                }
3271                "IS" | "IN" | "LIKE" | "BETWEEN" => COMPARISON_PRECEDENCE,
3272                _ => 0,
3273            },
3274            TokenKind::Punct(p) => match p {
3275                Punct::Eq
3276                | Punct::NotEq
3277                | Punct::LtGt
3278                | Punct::Lt
3279                | Punct::LtEq
3280                | Punct::Gt
3281                | Punct::GtEq => COMPARISON_PRECEDENCE,
3282                Punct::Bar => 5,
3283                Punct::Caret => 6,
3284                Punct::Ampersand => 7,
3285                Punct::ShiftLeft | Punct::ShiftRight => 8,
3286                Punct::Plus | Punct::Minus => 9,
3287                Punct::Star | Punct::Slash | Punct::Concat => 10,
3288                _ => 0,
3289            },
3290            _ => 0,
3291        }
3292    }
3293
3294    fn parse_infix(&mut self, left: Expr, precedence: u8) -> Result<Expr> {
3295        let token = self
3296            .peek()
3297            .cloned()
3298            .ok_or_else(|| self.error("expected an operator"))?;
3299        if let TokenKind::Punct(p) = token.kind {
3300            let op = match p {
3301                Punct::Eq => BinaryOperator::Eq,
3302                Punct::NotEq | Punct::LtGt => BinaryOperator::NotEq,
3303                Punct::Lt => BinaryOperator::Lt,
3304                Punct::LtEq => BinaryOperator::LtEq,
3305                Punct::Gt => BinaryOperator::Gt,
3306                Punct::GtEq => BinaryOperator::GtEq,
3307                Punct::Bar => BinaryOperator::BitOr,
3308                Punct::Caret => BinaryOperator::BitXor,
3309                Punct::Ampersand => BinaryOperator::BitAnd,
3310                Punct::ShiftLeft => BinaryOperator::ShiftLeft,
3311                Punct::ShiftRight => BinaryOperator::ShiftRight,
3312                Punct::Plus => BinaryOperator::Plus,
3313                Punct::Minus => BinaryOperator::Minus,
3314                Punct::Star => BinaryOperator::Multiply,
3315                Punct::Slash => BinaryOperator::Divide,
3316                Punct::Concat => BinaryOperator::Concat,
3317                _ => return Err(self.error("expected an operator")),
3318            };
3319            self.pos += 1;
3320            let right = self.parse_subexpr(precedence)?;
3321            return Ok(Expr::binary(left, op, right));
3322        }
3323        let upper = token.upper();
3324        match upper.as_str() {
3325            "OR" | "AND" => {
3326                self.parse_keyword(&upper);
3327                let op = if upper == "OR" {
3328                    BinaryOperator::Or
3329                } else {
3330                    BinaryOperator::And
3331                };
3332                let right = self.parse_subexpr(precedence)?;
3333                Ok(Expr::binary(left, op, right))
3334            }
3335            "IS" => {
3336                self.parse_keyword("IS");
3337                let negated = self.parse_keyword("NOT");
3338                if self.parse_keyword("NULL") {
3339                    self.set_role(self.pos - 1, TokenRole::Literal);
3340                    return Ok(Expr::IsNull {
3341                        expr: Box::new(left),
3342                        negated,
3343                    });
3344                }
3345                if self.parse_keyword("TRUE")
3346                    || self.parse_keyword("FALSE")
3347                    || self.parse_keyword("UNKNOWN")
3348                {
3349                    let word = self.tokens[self.pos - 1].upper();
3350                    self.set_role(self.pos - 1, TokenRole::Literal);
3351                    let value = match word.as_str() {
3352                        "TRUE" => Some(true),
3353                        "FALSE" => Some(false),
3354                        _ => None,
3355                    };
3356                    return Ok(Expr::IsBool {
3357                        expr: Box::new(left),
3358                        value,
3359                        negated,
3360                    });
3361                }
3362                if self.parse_keywords(&["DISTINCT", "FROM"]) {
3363                    let right = self.parse_subexpr(COMPARISON_PRECEDENCE)?;
3364                    return Ok(Expr::IsDistinctFrom {
3365                        left: Box::new(left),
3366                        right: Box::new(right),
3367                        negated,
3368                    });
3369                }
3370                Err(self.error("expected NULL, TRUE, FALSE, UNKNOWN or DISTINCT FROM after IS"))
3371            }
3372            _ => {
3373                let negated = self.parse_keyword("NOT");
3374                if self.parse_keyword("IN") {
3375                    return self.parse_in(left, negated);
3376                }
3377                if self.parse_keyword("LIKE") {
3378                    return self.parse_like(left, negated);
3379                }
3380                if self.parse_keyword("BETWEEN") {
3381                    let low = self.parse_subexpr(COMPARISON_PRECEDENCE)?;
3382                    self.expect_keyword("AND")?;
3383                    let high = self.parse_subexpr(COMPARISON_PRECEDENCE)?;
3384                    return Ok(Expr::Between {
3385                        expr: Box::new(left),
3386                        negated,
3387                        low: Box::new(low),
3388                        high: Box::new(high),
3389                    });
3390                }
3391                Err(self.error("expected an operator"))
3392            }
3393        }
3394    }
3395
3396    fn parse_in(&mut self, left: Expr, negated: bool) -> Result<Expr> {
3397        if self.parse_keyword("UNNEST") {
3398            self.expect_punct(Punct::LParen)?;
3399            let array = self.parse_expr()?;
3400            self.expect_punct(Punct::RParen)?;
3401            return Ok(Expr::InUnnest {
3402                expr: Box::new(left),
3403                array: Box::new(array),
3404                negated,
3405            });
3406        }
3407        if let Some(query) = self.attempt_parenthesized_query() {
3408            return Ok(Expr::InSubquery {
3409                expr: Box::new(left),
3410                subquery: Box::new(query),
3411                negated,
3412            });
3413        }
3414        self.expect_punct(Punct::LParen)?;
3415        let mut list = vec![self.parse_expr()?];
3416        while self.consume_punct(Punct::Comma) {
3417            list.push(self.parse_expr()?);
3418        }
3419        self.expect_punct(Punct::RParen)?;
3420        Ok(Expr::InList {
3421            expr: Box::new(left),
3422            list,
3423            negated,
3424        })
3425    }
3426
3427    /// `( query )` when the parenthesis opens a query; nothing consumed otherwise.
3428    fn attempt_parenthesized_query(&mut self) -> Option<Query> {
3429        if !self.paren_starts_query() {
3430            return None;
3431        }
3432        self.attempt(|p| {
3433            p.expect_punct(Punct::LParen)?;
3434            let query = p.parse_query()?;
3435            p.expect_punct(Punct::RParen)?;
3436            Ok(query)
3437        })
3438    }
3439
3440    fn parse_like(&mut self, left: Expr, negated: bool) -> Result<Expr> {
3441        let quantifier = if self.parse_keyword("ANY") {
3442            Some(LikeQuantifier::Any)
3443        } else if self.parse_keyword("SOME") {
3444            Some(LikeQuantifier::Some)
3445        } else if self.parse_keyword("ALL") {
3446            Some(LikeQuantifier::All)
3447        } else {
3448            None
3449        };
3450        let Some(quantifier) = quantifier else {
3451            let pattern = self.parse_subexpr(COMPARISON_PRECEDENCE)?;
3452            return Ok(Expr::Like {
3453                expr: Box::new(left),
3454                negated,
3455                pattern: Box::new(pattern),
3456            });
3457        };
3458        let patterns = if self.parse_keyword("UNNEST") {
3459            self.expect_punct(Punct::LParen)?;
3460            let array = self.parse_expr()?;
3461            self.expect_punct(Punct::RParen)?;
3462            LikePatterns::Unnest(Box::new(array))
3463        } else if let Some(query) = self.attempt_parenthesized_query() {
3464            LikePatterns::Subquery(Box::new(query))
3465        } else {
3466            self.expect_punct(Punct::LParen)?;
3467            let mut list = vec![self.parse_expr()?];
3468            while self.consume_punct(Punct::Comma) {
3469                list.push(self.parse_expr()?);
3470            }
3471            self.expect_punct(Punct::RParen)?;
3472            LikePatterns::List(list)
3473        };
3474        Ok(Expr::LikeQuantified {
3475            expr: Box::new(left),
3476            negated,
3477            quantifier,
3478            patterns,
3479        })
3480    }
3481
3482    /// A primary expression with its postfix field accesses and subscripts.
3483    fn parse_prefix(&mut self) -> Result<Expr> {
3484        let mut expr = self.parse_primary()?;
3485        loop {
3486            if self.peek_punct(Punct::LBracket) {
3487                self.pos += 1;
3488                let (kind, index) = self.parse_subscript()?;
3489                self.expect_punct(Punct::RBracket)?;
3490                expr = Expr::Subscript {
3491                    expr: Box::new(expr),
3492                    kind,
3493                    index: Box::new(index),
3494                };
3495            } else if self.peek_punct(Punct::Dot)
3496                && self.peek_nth(1).is_some_and(|t| {
3497                    matches!(
3498                        t.kind,
3499                        TokenKind::Word | TokenKind::QuotedIdentifier(_) | TokenKind::Integer
3500                    )
3501                })
3502            {
3503                self.pos += 1;
3504                let field = self.parse_path_part()?;
3505                expr = match expr {
3506                    Expr::Identifier(first) => Expr::CompoundIdentifier(vec![first, field]),
3507                    Expr::CompoundIdentifier(mut parts) => {
3508                        parts.push(field);
3509                        Expr::CompoundIdentifier(parts)
3510                    }
3511                    other => Expr::FieldAccess {
3512                        expr: Box::new(other),
3513                        field,
3514                    },
3515                };
3516            } else {
3517                break;
3518            }
3519        }
3520        Ok(expr)
3521    }
3522
3523    fn parse_subscript(&mut self) -> Result<(SubscriptKind, Expr)> {
3524        let kinds = [
3525            ("OFFSET", SubscriptKind::Offset),
3526            ("ORDINAL", SubscriptKind::Ordinal),
3527            ("SAFE_OFFSET", SubscriptKind::SafeOffset),
3528            ("SAFE_ORDINAL", SubscriptKind::SafeOrdinal),
3529        ];
3530        for (word, kind) in kinds {
3531            if self.peek_keyword(word) && self.peek_nth_punct(1, Punct::LParen) {
3532                self.parse_keyword(word);
3533                self.expect_punct(Punct::LParen)?;
3534                let index = self.parse_expr()?;
3535                self.expect_punct(Punct::RParen)?;
3536                return Ok((kind, index));
3537            }
3538        }
3539        Ok((SubscriptKind::Plain, self.parse_expr()?))
3540    }
3541
3542    fn parse_primary(&mut self) -> Result<Expr> {
3543        let Some(token) = self.peek().cloned() else {
3544            return Err(self.error("expected an expression"));
3545        };
3546        match &token.kind {
3547            TokenKind::Integer => {
3548                self.pos += 1;
3549                Ok(Expr::Literal(Literal::Int(token.text)))
3550            }
3551            TokenKind::Float => {
3552                self.pos += 1;
3553                Ok(Expr::Literal(Literal::Float(token.text)))
3554            }
3555            TokenKind::String { value, raw, quote } => {
3556                self.pos += 1;
3557                Ok(Expr::Literal(Literal::String(StringLiteral {
3558                    value: value.clone(),
3559                    raw: *raw,
3560                    quote: *quote,
3561                })))
3562            }
3563            TokenKind::Bytes { value, raw, quote } => {
3564                self.pos += 1;
3565                Ok(Expr::Literal(Literal::Bytes(BytesLiteral {
3566                    value: value.clone(),
3567                    raw: *raw,
3568                    quote: *quote,
3569                })))
3570            }
3571            TokenKind::Parameter(name) => {
3572                self.pos += 1;
3573                Ok(Expr::Parameter(Parameter::Named(name.clone())))
3574            }
3575            TokenKind::SystemVariable(name) => {
3576                self.pos += 1;
3577                Ok(Expr::Parameter(Parameter::System(name.clone())))
3578            }
3579            TokenKind::Punct(Punct::Question) => {
3580                self.pos += 1;
3581                Ok(Expr::Parameter(Parameter::Positional))
3582            }
3583            TokenKind::Punct(p @ (Punct::Minus | Punct::Plus | Punct::Tilde)) => {
3584                self.pos += 1;
3585                let op = match p {
3586                    Punct::Minus => UnaryOperator::Minus,
3587                    Punct::Plus => UnaryOperator::Plus,
3588                    _ => UnaryOperator::BitNot,
3589                };
3590                let expr = self.parse_subexpr(UNARY_PRECEDENCE)?;
3591                Ok(Expr::UnaryOp {
3592                    op,
3593                    expr: Box::new(expr),
3594                })
3595            }
3596            TokenKind::Punct(Punct::LParen) => self.parse_parenthesized(),
3597            TokenKind::Punct(Punct::LBracket) => {
3598                self.pos += 1;
3599                let elements = self.parse_array_elements()?;
3600                Ok(Expr::Array {
3601                    elements,
3602                    element_type: None,
3603                    keyword: false,
3604                })
3605            }
3606            TokenKind::QuotedIdentifier(_) => self.parse_identifier_chain(),
3607            TokenKind::Word => self.parse_word_expr(&token),
3608            _ => Err(self.error("expected an expression")),
3609        }
3610    }
3611
3612    fn parse_parenthesized(&mut self) -> Result<Expr> {
3613        if let Some(query) = self.attempt_parenthesized_query() {
3614            return Ok(Expr::Subquery(Box::new(query)));
3615        }
3616        self.expect_punct(Punct::LParen)?;
3617        let first = self.parse_expr()?;
3618        if self.consume_punct(Punct::Comma) {
3619            let mut items = vec![first];
3620            loop {
3621                items.push(self.parse_expr()?);
3622                if !self.consume_punct(Punct::Comma) {
3623                    break;
3624                }
3625            }
3626            self.expect_punct(Punct::RParen)?;
3627            return Ok(Expr::Tuple(items));
3628        }
3629        self.expect_punct(Punct::RParen)?;
3630        Ok(Expr::Nested(Box::new(first)))
3631    }
3632
3633    fn parse_array_elements(&mut self) -> Result<Vec<Expr>> {
3634        let mut elements = Vec::new();
3635        while !self.peek_punct(Punct::RBracket) {
3636            elements.push(self.parse_expr()?);
3637            if !self.consume_punct(Punct::Comma) {
3638                break;
3639            }
3640        }
3641        self.expect_punct(Punct::RBracket)?;
3642        Ok(elements)
3643    }
3644
3645    fn parse_identifier_chain(&mut self) -> Result<Expr> {
3646        let start = self.pos;
3647        let first = self.parse_identifier()?;
3648        let mut parts = vec![first];
3649        while self.peek_punct(Punct::Dot)
3650            && self.peek_nth(1).is_some_and(|t| {
3651                matches!(
3652                    t.kind,
3653                    TokenKind::Word | TokenKind::QuotedIdentifier(_) | TokenKind::Integer
3654                )
3655            })
3656        {
3657            self.pos += 1;
3658            parts.push(self.parse_path_part()?);
3659        }
3660        if self.peek_punct(Punct::LParen) {
3661            let function = self.parse_function_call(ObjectName(parts), self.pos - 1)?;
3662            return Ok(Expr::Function(Box::new(function)));
3663        }
3664        if parts.len() == 1 {
3665            let name = parts[0].value.to_ascii_uppercase();
3666            if !parts[0].quoted && NO_PAREN_FUNCTIONS.contains(&name.as_str()) {
3667                self.set_role(start, TokenRole::Function);
3668                let mut function = Function::new(&parts[0].value, Vec::new());
3669                function.no_parens = true;
3670                return Ok(Expr::Function(Box::new(function)));
3671            }
3672            return Ok(Expr::Identifier(parts.remove(0)));
3673        }
3674        Ok(Expr::CompoundIdentifier(parts))
3675    }
3676
3677    fn parse_word_expr(&mut self, token: &Token) -> Result<Expr> {
3678        let upper = token.upper();
3679        let next_is_string = matches!(
3680            self.peek_nth(1).map(|t| &t.kind),
3681            Some(TokenKind::String { .. })
3682        );
3683        let next_paren = self.peek_nth_punct(1, Punct::LParen);
3684        match upper.as_str() {
3685            "NOT" => {
3686                self.parse_keyword("NOT");
3687                let expr = self.parse_subexpr(NOT_PRECEDENCE)?;
3688                return Ok(Expr::UnaryOp {
3689                    op: UnaryOperator::Not,
3690                    expr: Box::new(expr),
3691                });
3692            }
3693            "NULL" => {
3694                self.set_role(self.pos, TokenRole::Literal);
3695                self.pos += 1;
3696                return Ok(Expr::null());
3697            }
3698            "TRUE" | "FALSE" => {
3699                self.set_role(self.pos, TokenRole::Literal);
3700                self.pos += 1;
3701                return Ok(Expr::Literal(Literal::Bool(upper == "TRUE")));
3702            }
3703            "DEFAULT" => {
3704                self.parse_keyword("DEFAULT");
3705                return Ok(Expr::Default);
3706            }
3707            "CASE" => return self.parse_case_expr(),
3708            "CAST" | "SAFE_CAST" if next_paren => return self.parse_cast(upper == "SAFE_CAST"),
3709            "EXTRACT" if next_paren => return self.parse_extract(),
3710            "EXISTS" if next_paren => {
3711                self.parse_keyword("EXISTS");
3712                self.expect_punct(Punct::LParen)?;
3713                let query = self.parse_query()?;
3714                self.expect_punct(Punct::RParen)?;
3715                return Ok(Expr::Exists(Box::new(query)));
3716            }
3717            "ARRAY" => return self.parse_array_expr(),
3718            "STRUCT" => return self.parse_struct_expr(),
3719            "INTERVAL" => return self.parse_interval(),
3720            "WITH" if next_paren => return self.parse_scalar_with(),
3721            "RANGE" if self.peek_nth_punct(1, Punct::Lt) => {
3722                self.parse_keyword("RANGE");
3723                self.set_role(self.pos - 1, TokenRole::Type);
3724                self.expect_punct(Punct::Lt)?;
3725                let element = self.parse_data_type()?;
3726                self.expect_gt()?;
3727                let value = self.expect_string()?;
3728                return Ok(Expr::Literal(Literal::Range {
3729                    element: Box::new(element),
3730                    value,
3731                }));
3732            }
3733            "DATE" | "DATETIME" | "TIME" | "TIMESTAMP" | "NUMERIC" | "BIGNUMERIC" | "DECIMAL"
3734            | "BIGDECIMAL" | "JSON"
3735                if next_is_string =>
3736            {
3737                self.set_role(self.pos, TokenRole::Keyword);
3738                self.pos += 1;
3739                let value = self.expect_string()?;
3740                let literal = match upper.as_str() {
3741                    "DATE" => Literal::Date(value),
3742                    "DATETIME" => Literal::Datetime(value),
3743                    "TIME" => Literal::Time(value),
3744                    "TIMESTAMP" => Literal::Timestamp(value),
3745                    "NUMERIC" | "DECIMAL" => Literal::Numeric(value),
3746                    "BIGNUMERIC" | "BIGDECIMAL" => Literal::BigNumeric(value),
3747                    _ => Literal::Json(value),
3748                };
3749                return Ok(Expr::Literal(literal));
3750            }
3751            _ => {}
3752        }
3753        if is_reserved_keyword(&upper) {
3754            if next_paren && RESERVED_FUNCTIONS.contains(&upper.as_str()) {
3755                self.pos += 1;
3756                let name = ObjectName(vec![Ident::new(token.text.clone())]);
3757                let function = self.parse_function_call(name, self.pos - 1)?;
3758                return Ok(Expr::Function(Box::new(function)));
3759            }
3760            return Err(self.error("expected an expression"));
3761        }
3762        self.parse_identifier_chain()
3763    }
3764
3765    fn expect_string(&mut self) -> Result<String> {
3766        match self.peek().map(|t| t.kind.clone()) {
3767            Some(TokenKind::String { value, .. }) => {
3768                self.pos += 1;
3769                Ok(value)
3770            }
3771            _ => Err(self.error("expected a string literal")),
3772        }
3773    }
3774
3775    fn parse_case_expr(&mut self) -> Result<Expr> {
3776        self.expect_keyword("CASE")?;
3777        let operand = if self.peek_keyword("WHEN") {
3778            None
3779        } else {
3780            Some(Box::new(self.parse_expr()?))
3781        };
3782        let mut branches = Vec::new();
3783        while self.parse_keyword("WHEN") {
3784            let condition = self.parse_expr()?;
3785            self.expect_keyword("THEN")?;
3786            let result = self.parse_expr()?;
3787            branches.push(CaseWhen { condition, result });
3788        }
3789        if branches.is_empty() {
3790            return Err(self.error("expected WHEN"));
3791        }
3792        let else_result = if self.parse_keyword("ELSE") {
3793            Some(Box::new(self.parse_expr()?))
3794        } else {
3795            None
3796        };
3797        self.expect_keyword("END")?;
3798        Ok(Expr::Case {
3799            operand,
3800            branches,
3801            else_result,
3802        })
3803    }
3804
3805    fn parse_cast(&mut self, safe: bool) -> Result<Expr> {
3806        self.set_role(self.pos, TokenRole::Function);
3807        self.pos += 1;
3808        self.expect_punct(Punct::LParen)?;
3809        let expr = self.parse_expr()?;
3810        self.expect_keyword("AS")?;
3811        let data_type = self.parse_data_type()?;
3812        let format = if self.parse_keyword("FORMAT") {
3813            Some(Box::new(self.parse_expr()?))
3814        } else {
3815            None
3816        };
3817        let time_zone = if self.parse_keywords(&["AT", "TIME", "ZONE"]) {
3818            Some(Box::new(self.parse_expr()?))
3819        } else {
3820            None
3821        };
3822        self.expect_punct(Punct::RParen)?;
3823        Ok(Expr::Cast {
3824            expr: Box::new(expr),
3825            data_type,
3826            safe,
3827            format,
3828            time_zone,
3829        })
3830    }
3831
3832    fn parse_extract(&mut self) -> Result<Expr> {
3833        self.set_role(self.pos, TokenRole::Function);
3834        self.pos += 1;
3835        self.expect_punct(Punct::LParen)?;
3836        let part_start = self.pos;
3837        let part = self.parse_expr()?;
3838        if part_start + 1 == self.pos {
3839            self.set_role(part_start, TokenRole::Keyword);
3840        }
3841        self.expect_keyword("FROM")?;
3842        let expr = self.parse_expr()?;
3843        let time_zone = if self.parse_keywords(&["AT", "TIME", "ZONE"]) {
3844            Some(Box::new(self.parse_expr()?))
3845        } else {
3846            None
3847        };
3848        self.expect_punct(Punct::RParen)?;
3849        Ok(Expr::Extract {
3850            part: Box::new(part),
3851            expr: Box::new(expr),
3852            time_zone,
3853        })
3854    }
3855
3856    fn parse_array_expr(&mut self) -> Result<Expr> {
3857        self.set_role(self.pos, TokenRole::Keyword);
3858        self.pos += 1;
3859        if self.peek_punct(Punct::LParen) {
3860            self.set_role(self.pos - 1, TokenRole::Function);
3861            self.pos += 1;
3862            let query = self.parse_query()?;
3863            self.expect_punct(Punct::RParen)?;
3864            return Ok(Expr::ArraySubquery(Box::new(query)));
3865        }
3866        let element_type = if self.consume_punct(Punct::Lt) {
3867            self.set_role(self.pos - 2, TokenRole::Type);
3868            let ty = self.parse_data_type()?;
3869            self.expect_gt()?;
3870            Some(Box::new(ty))
3871        } else {
3872            None
3873        };
3874        self.expect_punct(Punct::LBracket)?;
3875        let elements = self.parse_array_elements()?;
3876        Ok(Expr::Array {
3877            elements,
3878            element_type,
3879            keyword: true,
3880        })
3881    }
3882
3883    fn parse_struct_expr(&mut self) -> Result<Expr> {
3884        self.set_role(self.pos, TokenRole::Keyword);
3885        self.pos += 1;
3886        let typed = if self.consume_punct(Punct::Lt) {
3887            self.set_role(self.pos - 2, TokenRole::Type);
3888            Some(self.parse_struct_fields()?)
3889        } else {
3890            None
3891        };
3892        self.expect_punct(Punct::LParen)?;
3893        let mut fields = Vec::new();
3894        while !self.peek_punct(Punct::RParen) {
3895            let expr = self.parse_expr()?;
3896            let alias = if self.parse_keyword("AS") {
3897                Some(self.parse_identifier()?)
3898            } else {
3899                None
3900            };
3901            fields.push(StructExprField { expr, alias });
3902            if !self.consume_punct(Punct::Comma) {
3903                break;
3904            }
3905        }
3906        self.expect_punct(Punct::RParen)?;
3907        Ok(Expr::Struct { fields, typed })
3908    }
3909
3910    fn parse_interval(&mut self) -> Result<Expr> {
3911        self.expect_keyword("INTERVAL")?;
3912        let value = self.parse_subexpr(UNARY_PRECEDENCE)?;
3913        let leading = self.parse_date_part()?;
3914        let trailing = if self.parse_keyword("TO") {
3915            Some(self.parse_date_part()?)
3916        } else {
3917            None
3918        };
3919        Ok(Expr::Literal(Literal::Interval(IntervalLiteral {
3920            value: Box::new(value),
3921            leading,
3922            trailing,
3923        })))
3924    }
3925
3926    fn parse_date_part(&mut self) -> Result<String> {
3927        match self.peek() {
3928            Some(t) if t.is_word() => {
3929                let part = t.upper();
3930                self.set_role(self.pos, TokenRole::Keyword);
3931                self.pos += 1;
3932                Ok(part)
3933            }
3934            _ => Err(self.error("expected a date part")),
3935        }
3936    }
3937
3938    fn parse_scalar_with(&mut self) -> Result<Expr> {
3939        self.parse_keyword("WITH");
3940        self.expect_punct(Punct::LParen)?;
3941        let mut bindings = Vec::new();
3942        loop {
3943            if self.peek_identifier() && self.peek_nth_keyword(1, "AS") {
3944                let name = self.parse_identifier()?;
3945                self.expect_keyword("AS")?;
3946                let value = self.parse_expr()?;
3947                bindings.push((name, value));
3948                self.expect_punct(Punct::Comma)?;
3949            } else {
3950                let body = self.parse_expr()?;
3951                self.expect_punct(Punct::RParen)?;
3952                return Ok(Expr::ScalarWith {
3953                    bindings,
3954                    body: Box::new(body),
3955                });
3956            }
3957        }
3958    }
3959
3960    /// The call after its name; `name_token` is the index of the name's last token.
3961    fn parse_function_call(&mut self, name: ObjectName, name_token: usize) -> Result<Function> {
3962        self.set_role(name_token, TokenRole::Function);
3963        self.expect_punct(Punct::LParen)?;
3964        let mut function = Function {
3965            name,
3966            args: Vec::new(),
3967            distinct: false,
3968            null_treatment: None,
3969            having: None,
3970            order_by: Vec::new(),
3971            limit: None,
3972            over: None,
3973            no_parens: false,
3974        };
3975        function.distinct = self.parse_keyword("DISTINCT");
3976        while !self.peek_punct(Punct::RParen) && !self.peek_function_modifier() {
3977            function.args.push(self.parse_function_arg()?);
3978            // `SUBSTRING(x FROM a [FOR b])`
3979            if self.extended
3980                && function.args.len() == 1
3981                && function.name.0.len() == 1
3982                && (function.name.0[0].value.eq_ignore_ascii_case("SUBSTRING")
3983                    || function.name.0[0].value.eq_ignore_ascii_case("SUBSTR"))
3984                && self.parse_keyword("FROM")
3985            {
3986                function.args.push(self.parse_function_arg()?);
3987                if self.parse_keyword("FOR") {
3988                    function.args.push(self.parse_function_arg()?);
3989                }
3990                break;
3991            }
3992            if !self.consume_punct(Punct::Comma) {
3993                break;
3994            }
3995        }
3996        if self.parse_keywords(&["IGNORE", "NULLS"]) {
3997            function.null_treatment = Some(NullTreatment::IgnoreNulls);
3998        } else if self.parse_keywords(&["RESPECT", "NULLS"]) {
3999            function.null_treatment = Some(NullTreatment::RespectNulls);
4000        }
4001        if self.parse_keyword("HAVING") {
4002            let max = if self.parse_keyword("MAX") {
4003                true
4004            } else {
4005                self.expect_keyword("MIN")?;
4006                false
4007            };
4008            function.having = Some(HavingBound {
4009                max,
4010                expr: Box::new(self.parse_expr()?),
4011            });
4012        }
4013        if self.parse_keywords(&["ORDER", "BY"]) {
4014            function.order_by = self.parse_order_by_list()?;
4015        }
4016        if self.parse_keyword("LIMIT") {
4017            function.limit = Some(Box::new(self.parse_expr()?));
4018        }
4019        self.expect_punct(Punct::RParen)?;
4020        if self.parse_keyword("OVER") {
4021            function.over = Some(if self.peek_punct(Punct::LParen) {
4022                WindowType::Spec(self.parse_window_spec()?)
4023            } else {
4024                WindowType::Named(self.parse_identifier()?)
4025            });
4026        }
4027        Ok(function)
4028    }
4029
4030    fn peek_function_modifier(&self) -> bool {
4031        (self.peek_keyword("IGNORE") || self.peek_keyword("RESPECT"))
4032            && self.peek_nth_keyword(1, "NULLS")
4033            || self.peek_keyword("HAVING")
4034            || (self.peek_keyword("ORDER") && self.peek_nth_keyword(1, "BY"))
4035            || self.peek_keyword("LIMIT")
4036    }
4037
4038    fn parse_function_arg(&mut self) -> Result<FunctionArg> {
4039        if self.peek_punct(Punct::Star)
4040            && (self.peek_nth_punct(1, Punct::RParen) || self.peek_nth_punct(1, Punct::Comma))
4041        {
4042            self.pos += 1;
4043            return Ok(FunctionArg::Wildcard);
4044        }
4045        if (self.peek_keyword("TABLE") || self.peek_keyword("MODEL"))
4046            && self.peek_nth(1).is_some_and(|t| {
4047                Self::is_identifier_token(t) || matches!(t.kind, TokenKind::QuotedIdentifier(_))
4048            })
4049            && !self.peek_nth_punct(1, Punct::LParen)
4050        {
4051            let table = self.parse_keyword("TABLE");
4052            if !table {
4053                self.parse_keyword("MODEL");
4054            }
4055            let name = self.parse_object_name(true)?;
4056            return Ok(if table {
4057                FunctionArg::Table(name)
4058            } else {
4059                FunctionArg::Model(name)
4060            });
4061        }
4062        // `x -> body`
4063        if self.peek_identifier() && self.peek_nth_punct(1, Punct::Arrow) {
4064            let param = self.parse_identifier()?;
4065            self.pos += 1;
4066            let body = self.parse_expr()?;
4067            return Ok(FunctionArg::Expr(Expr::Lambda {
4068                params: vec![param],
4069                body: Box::new(body),
4070            }));
4071        }
4072        // `(a, b) -> body`
4073        if self.peek_punct(Punct::LParen) {
4074            if let Some(lambda) = self.attempt(|p| {
4075                let params = p.parse_parenthesized_identifiers()?;
4076                p.expect_punct(Punct::Arrow)?;
4077                let body = p.parse_expr()?;
4078                Ok(Expr::Lambda {
4079                    params,
4080                    body: Box::new(body),
4081                })
4082            }) {
4083                return Ok(FunctionArg::Expr(lambda));
4084            }
4085        }
4086        // `name => value`
4087        if self.peek_identifier() && self.peek_nth_punct(1, Punct::FatArrow) {
4088            let name = self.parse_identifier()?;
4089            self.pos += 1;
4090            let value = self.parse_expr()?;
4091            return Ok(FunctionArg::Expr(Expr::NamedArg {
4092                name,
4093                value: Box::new(value),
4094            }));
4095        }
4096        Ok(FunctionArg::Expr(self.parse_expr()?))
4097    }
4098
4099    fn parse_window_spec(&mut self) -> Result<WindowSpec> {
4100        self.expect_punct(Punct::LParen)?;
4101        let mut spec = WindowSpec::default();
4102        if self.peek_identifier()
4103            && !self.peek_keyword("PARTITION")
4104            && !self.peek_keyword("ORDER")
4105            && !self.peek_keyword("ROWS")
4106            && !self.peek_keyword("RANGE")
4107        {
4108            spec.base = Some(self.parse_identifier()?);
4109        }
4110        if self.parse_keywords(&["PARTITION", "BY"]) {
4111            spec.partition_by.push(self.parse_expr()?);
4112            while self.consume_punct(Punct::Comma) {
4113                spec.partition_by.push(self.parse_expr()?);
4114            }
4115        }
4116        if self.parse_keywords(&["ORDER", "BY"]) {
4117            spec.order_by = self.parse_order_by_list()?;
4118        }
4119        if self.peek_keyword("ROWS") || self.peek_keyword("RANGE") {
4120            let units = if self.parse_keyword("ROWS") {
4121                FrameUnits::Rows
4122            } else {
4123                self.parse_keyword("RANGE");
4124                FrameUnits::Range
4125            };
4126            let (start, end) = if self.parse_keyword("BETWEEN") {
4127                let start = self.parse_frame_bound()?;
4128                self.expect_keyword("AND")?;
4129                let end = self.parse_frame_bound()?;
4130                (start, Some(end))
4131            } else {
4132                (self.parse_frame_bound()?, None)
4133            };
4134            spec.frame = Some(WindowFrame { units, start, end });
4135        }
4136        self.expect_punct(Punct::RParen)?;
4137        Ok(spec)
4138    }
4139
4140    fn parse_frame_bound(&mut self) -> Result<FrameBound> {
4141        if self.parse_keywords(&["UNBOUNDED", "PRECEDING"]) {
4142            return Ok(FrameBound::UnboundedPreceding);
4143        }
4144        if self.parse_keywords(&["UNBOUNDED", "FOLLOWING"]) {
4145            return Ok(FrameBound::UnboundedFollowing);
4146        }
4147        if self.parse_keywords(&["CURRENT", "ROW"]) {
4148            return Ok(FrameBound::CurrentRow);
4149        }
4150        let expr = self.parse_subexpr(COMPARISON_PRECEDENCE)?;
4151        if self.parse_keyword("PRECEDING") {
4152            Ok(FrameBound::Preceding(Box::new(expr)))
4153        } else {
4154            self.expect_keyword("FOLLOWING")?;
4155            Ok(FrameBound::Following(Box::new(expr)))
4156        }
4157    }
4158
4159    // ------------------------------------------------------------------ data types
4160
4161    /// Parse a data type at the current position.
4162    pub fn parse_data_type(&mut self) -> Result<DataType> {
4163        self.enter()?;
4164        let result = self.parse_data_type_inner();
4165        self.leave();
4166        result
4167    }
4168
4169    fn parse_data_type_inner(&mut self) -> Result<DataType> {
4170        let Some(token) = self.peek().cloned() else {
4171            return Err(self.error("expected a data type"));
4172        };
4173        let name = match &token.kind {
4174            TokenKind::Word => token.upper(),
4175            TokenKind::QuotedIdentifier(v) => {
4176                self.pos += 1;
4177                return Ok(DataType::Other(v.clone()));
4178            }
4179            _ => return Err(self.error("expected a data type")),
4180        };
4181        self.set_role(self.pos, TokenRole::Type);
4182        self.pos += 1;
4183        match name.as_str() {
4184            "ARRAY" => {
4185                self.expect_punct(Punct::Lt)?;
4186                let inner = self.parse_data_type()?;
4187                self.expect_gt()?;
4188                Ok(DataType::Array(Box::new(inner)))
4189            }
4190            "RANGE" => {
4191                self.expect_punct(Punct::Lt)?;
4192                let inner = self.parse_data_type()?;
4193                self.expect_gt()?;
4194                Ok(DataType::Range(Box::new(inner)))
4195            }
4196            "STRUCT" => {
4197                self.expect_punct(Punct::Lt)?;
4198                Ok(DataType::Struct(self.parse_struct_fields()?))
4199            }
4200            _ => {
4201                let base =
4202                    DataType::from_name(&name).unwrap_or_else(|| DataType::Other(name.clone()));
4203                match base {
4204                    DataType::Numeric(_) | DataType::BigNumeric(_)
4205                        if self.peek_punct(Punct::LParen) =>
4206                    {
4207                        self.pos += 1;
4208                        let precision = self.parse_u64()? as u32;
4209                        let scale = if self.consume_punct(Punct::Comma) {
4210                            Some(self.parse_u64()? as u32)
4211                        } else {
4212                            None
4213                        };
4214                        self.expect_punct(Punct::RParen)?;
4215                        Ok(if matches!(base, DataType::Numeric(_)) {
4216                            DataType::Numeric(Some((precision, scale)))
4217                        } else {
4218                            DataType::BigNumeric(Some((precision, scale)))
4219                        })
4220                    }
4221                    DataType::String(_) | DataType::Bytes(_) if self.peek_punct(Punct::LParen) => {
4222                        self.pos += 1;
4223                        let length = self.parse_u64()?;
4224                        self.expect_punct(Punct::RParen)?;
4225                        Ok(if matches!(base, DataType::String(_)) {
4226                            DataType::String(Some(length))
4227                        } else {
4228                            DataType::Bytes(Some(length))
4229                        })
4230                    }
4231                    other => Ok(other),
4232                }
4233            }
4234        }
4235    }
4236
4237    fn parse_u64(&mut self) -> Result<u64> {
4238        match self.peek() {
4239            Some(t) if t.kind == TokenKind::Integer => {
4240                let value = t
4241                    .text
4242                    .parse::<u64>()
4243                    .map_err(|_| self.error("expected a number"))?;
4244                self.pos += 1;
4245                Ok(value)
4246            }
4247            _ => Err(self.error("expected a number")),
4248        }
4249    }
4250
4251    /// Fields up to and including the closing `>` (the `<` already consumed).
4252    fn parse_struct_fields(&mut self) -> Result<Vec<StructField>> {
4253        let mut fields = Vec::new();
4254        if self.peek_punct(Punct::Gt) || self.peek_punct(Punct::ShiftRight) {
4255            self.expect_gt()?;
4256            return Ok(fields);
4257        }
4258        loop {
4259            let named = self.peek().is_some_and(|t| {
4260                matches!(t.kind, TokenKind::Word | TokenKind::QuotedIdentifier(_))
4261            }) && self.peek_nth(1).is_some_and(|t| {
4262                matches!(t.kind, TokenKind::Word | TokenKind::QuotedIdentifier(_))
4263            });
4264            let name = if named {
4265                Some(self.parse_path_part()?)
4266            } else {
4267                None
4268            };
4269            let data_type = self.parse_data_type()?;
4270            let not_null = self.parse_keywords(&["NOT", "NULL"]);
4271            let options = self.parse_optional_options()?;
4272            fields.push(StructField {
4273                name,
4274                data_type,
4275                not_null,
4276                options,
4277            });
4278            if !self.consume_punct(Punct::Comma) {
4279                break;
4280            }
4281        }
4282        self.expect_gt()?;
4283        Ok(fields)
4284    }
4285}
4286
4287fn describe(token: &Token) -> String {
4288    match &token.kind {
4289        TokenKind::Word => format!("'{}'", token.text),
4290        TokenKind::QuotedIdentifier(_) => "a quoted identifier".to_string(),
4291        TokenKind::String { .. } => "a string literal".to_string(),
4292        TokenKind::Bytes { .. } => "a bytes literal".to_string(),
4293        TokenKind::Integer | TokenKind::Float => "a number".to_string(),
4294        TokenKind::Parameter(_) | TokenKind::SystemVariable(_) => "a parameter".to_string(),
4295        TokenKind::Punct(p) => format!("'{}'", p.as_str()),
4296        TokenKind::Comment(_) => "a comment".to_string(),
4297        TokenKind::Whitespace => "whitespace".to_string(),
4298    }
4299}