risingwave_sqlparser/
parser.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12
13//! SQL Parser
14
15#[cfg(not(feature = "std"))]
16use alloc::{
17    boxed::Box,
18    format,
19    string::{String, ToString},
20    vec,
21    vec::Vec,
22};
23use core::fmt;
24
25use ddl::WebhookSourceInfo;
26use itertools::Itertools;
27use tracing::{debug, instrument};
28use winnow::combinator::{
29    alt, cut_err, dispatch, fail, opt, peek, preceded, repeat, separated, separated_pair,
30};
31use winnow::{ModalResult, Parser as _};
32
33use crate::ast::*;
34use crate::keywords::{self, Keyword};
35use crate::parser_v2::{
36    ParserExt as _, dollar_quoted_string, keyword, literal_i64, literal_u32, literal_u64,
37    single_quoted_string,
38};
39use crate::tokenizer::*;
40use crate::{impl_parse_to, parser_v2};
41
42pub(crate) const UPSTREAM_SOURCE_KEY: &str = "connector";
43pub(crate) const WEBHOOK_CONNECTOR: &str = "webhook";
44
45const WEBHOOK_WAIT_FOR_PERSISTENCE: &str = "webhook.wait_for_persistence";
46const WEBHOOK_IS_BATCHED: &str = "is_batched";
47
48#[derive(Debug, Clone, PartialEq)]
49pub enum ParserError {
50    TokenizerError(String),
51    ParserError(String),
52}
53
54impl ParserError {
55    pub fn inner_msg(self) -> String {
56        match self {
57            ParserError::TokenizerError(s) | ParserError::ParserError(s) => s,
58        }
59    }
60}
61
62#[derive(Debug, thiserror::Error)]
63#[error("{0}")]
64pub struct StrError(pub String);
65
66// Use `Parser::expected` instead, if possible
67#[macro_export]
68macro_rules! parser_err {
69    ($($arg:tt)*) => {
70        return Err(winnow::error::ErrMode::Backtrack(<winnow::error::ContextError as winnow::error::FromExternalError<_, _>>::from_external_error(
71            &Parser::default(),
72            $crate::parser::StrError(format!($($arg)*)),
73        )))
74    };
75}
76
77impl From<StrError> for winnow::error::ErrMode<winnow::error::ContextError> {
78    fn from(e: StrError) -> Self {
79        winnow::error::ErrMode::Backtrack(<winnow::error::ContextError as winnow::error::FromExternalError<_, _>>::from_external_error(
80            &Parser::default(),
81            e,
82        ))
83    }
84}
85
86// Returns a successful result if the optional expression is some
87macro_rules! return_ok_if_some {
88    ($e:expr) => {{
89        if let Some(v) = $e {
90            return Ok(v);
91        }
92    }};
93}
94
95#[derive(PartialEq)]
96pub enum IsOptional {
97    Optional,
98    Mandatory,
99}
100
101use IsOptional::*;
102
103pub enum IsLateral {
104    Lateral,
105    NotLateral,
106}
107
108use IsLateral::*;
109
110use crate::ast::ddl::AlterFragmentOperation;
111
112pub type IncludeOption = Vec<IncludeOptionItem>;
113
114#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
115#[derive(Eq, Clone, Debug, PartialEq, Hash)]
116pub struct IncludeOptionItem {
117    pub column_type: Ident,
118    pub column_alias: Option<Ident>,
119    pub inner_field: Option<String>,
120    pub header_inner_expect_type: Option<DataType>,
121}
122
123#[derive(Debug)]
124pub enum WildcardOrExpr {
125    Expr(Expr),
126    /// Expr is an arbitrary expression, returning either a table or a column.
127    /// Idents are the prefix of `*`, which are consecutive field accesses.
128    /// e.g. `(table.v1).*` or `(table).v1.*`
129    ///
130    /// See also [`Expr::FieldIdentifier`] for behaviors of parentheses.
131    ExprQualifiedWildcard(Expr, Vec<Ident>),
132    /// `QualifiedWildcard` and `Wildcard` can be followed by EXCEPT (columns)
133    QualifiedWildcard(ObjectName, Option<Vec<Expr>>),
134    Wildcard(Option<Vec<Expr>>),
135}
136
137impl From<WildcardOrExpr> for FunctionArgExpr {
138    fn from(wildcard_expr: WildcardOrExpr) -> Self {
139        match wildcard_expr {
140            WildcardOrExpr::Expr(expr) => Self::Expr(expr),
141            WildcardOrExpr::ExprQualifiedWildcard(expr, prefix) => {
142                Self::ExprQualifiedWildcard(expr, prefix)
143            }
144            WildcardOrExpr::QualifiedWildcard(prefix, except) => {
145                Self::QualifiedWildcard(prefix, except)
146            }
147            WildcardOrExpr::Wildcard(except) => Self::Wildcard(except),
148        }
149    }
150}
151
152impl From<TokenizerError> for ParserError {
153    fn from(e: TokenizerError) -> Self {
154        ParserError::TokenizerError(e.to_string())
155    }
156}
157
158impl fmt::Display for ParserError {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        write!(
161            f,
162            "sql parser error: {}",
163            match self {
164                ParserError::TokenizerError(s) => s,
165                ParserError::ParserError(s) => s,
166            }
167        )
168    }
169}
170
171#[cfg(feature = "std")]
172impl std::error::Error for ParserError {}
173
174type ColumnsDefTuple = (
175    Vec<ColumnDef>,
176    Vec<TableConstraint>,
177    Vec<SourceWatermark>,
178    Option<usize>,
179);
180
181/// Reference:
182/// <https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-PRECEDENCE>
183#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
184pub enum Precedence {
185    Zero = 0,
186    LogicalOr, // 5 in upstream
187    LogicalXor,
188    LogicalAnd, // 10 in upstream
189    UnaryNot,   // 15 in upstream
190    Is,         // 17 in upstream
191    Cmp,
192    Like,    // 19 in upstream
193    Between, // 20 in upstream
194    Other,
195    PlusMinus, // 30 in upstream
196    MulDiv,    // 40 in upstream
197    Exp,
198    At,
199    Collate,
200    UnaryPosNeg,
201    Array,
202    DoubleColon, // 50 in upstream
203}
204
205#[derive(Clone, Copy, Default)]
206pub struct Parser<'a>(pub(crate) &'a [TokenWithLocation]);
207
208impl Parser<'_> {
209    /// Parse a SQL statement and produce an Abstract Syntax Tree (AST)
210    #[instrument(level = "debug")]
211    pub fn parse_sql(sql: &str) -> Result<Vec<Statement>, ParserError> {
212        let mut tokenizer = Tokenizer::new(sql);
213        let tokens = tokenizer.tokenize_with_location()?;
214        let parser = Parser(&tokens);
215        let stmts = Parser::parse_statements.parse(parser).map_err(|e| {
216            // append SQL context to the error message, e.g.:
217            // LINE 1: SELECT 1::int(2);
218            let loc = match tokens.get(e.offset()) {
219                Some(token) => token.location.clone(),
220                None => {
221                    // get location of EOF
222                    Location {
223                        line: sql.lines().count() as u64,
224                        column: sql.lines().last().map_or(0, |l| l.len() as u64) + 1,
225                    }
226                }
227            };
228            let prefix = format!("LINE {}: ", loc.line);
229            let sql_line = sql.split('\n').nth(loc.line as usize - 1).unwrap();
230            let cursor = " ".repeat(prefix.len() + loc.column as usize - 1);
231            ParserError::ParserError(format!(
232                "{}\n{}{}\n{}^",
233                e.inner().to_string().replace('\n', ": "),
234                prefix,
235                sql_line,
236                cursor
237            ))
238        })?;
239        Ok(stmts)
240    }
241
242    /// Parse exactly one statement from a string.
243    pub fn parse_exactly_one(sql: &str) -> Result<Statement, ParserError> {
244        Parser::parse_sql(sql)
245            .map_err(|e| {
246                ParserError::ParserError(format!("failed to parse definition sql: {}", e))
247            })?
248            .into_iter()
249            .exactly_one()
250            .map_err(|e| {
251                ParserError::ParserError(format!(
252                    "expecting exactly one statement in definition: {}",
253                    e
254                ))
255            })
256    }
257
258    /// Parse object name from a string.
259    pub fn parse_object_name_str(s: &str) -> Result<ObjectName, ParserError> {
260        let mut tokenizer = Tokenizer::new(s);
261        let tokens = tokenizer.tokenize_with_location()?;
262        let parser = Parser(&tokens);
263        Parser::parse_object_name
264            .parse(parser)
265            .map_err(|e| ParserError::ParserError(e.inner().to_string()))
266    }
267
268    /// Parse function description from a string.
269    pub fn parse_function_desc_str(func: &str) -> Result<FunctionDesc, ParserError> {
270        let mut tokenizer = Tokenizer::new(func);
271        let tokens = tokenizer.tokenize_with_location()?;
272        let parser = Parser(&tokens);
273        Parser::parse_function_desc
274            .parse(parser)
275            .map_err(|e| ParserError::ParserError(e.inner().to_string()))
276    }
277
278    /// Parse a list of semicolon-separated statements.
279    fn parse_statements(&mut self) -> ModalResult<Vec<Statement>> {
280        let mut stmts = Vec::new();
281        let mut expecting_statement_delimiter = false;
282        loop {
283            // ignore empty statements (between successive statement delimiters)
284            while self.consume_token(&Token::SemiColon) {
285                expecting_statement_delimiter = false;
286            }
287
288            if self.peek_token() == Token::EOF {
289                break;
290            }
291            if expecting_statement_delimiter {
292                return self.expected("end of statement");
293            }
294
295            let statement = self.parse_statement()?;
296            stmts.push(statement);
297            expecting_statement_delimiter = true;
298        }
299        debug!("parsed statements:\n{:#?}", stmts);
300        Ok(stmts)
301    }
302
303    /// Parse a single top-level statement (such as SELECT, INSERT, CREATE, etc.),
304    /// stopping before the statement separator, if any.
305    pub fn parse_statement(&mut self) -> ModalResult<Statement> {
306        let checkpoint = *self;
307        let token = self.next_token();
308        match token.token {
309            Token::Word(w) => match w.keyword {
310                Keyword::EXPLAIN => Ok(self.parse_explain()?),
311                Keyword::ANALYZE => Ok(self.parse_analyze()?),
312                Keyword::SELECT | Keyword::WITH | Keyword::VALUES => {
313                    *self = checkpoint;
314                    Ok(Statement::Query(Box::new(self.parse_query()?)))
315                }
316                Keyword::DECLARE => Ok(self.parse_declare()?),
317                Keyword::FETCH => Ok(self.parse_fetch_cursor()?),
318                Keyword::CLOSE => Ok(self.parse_close_cursor()?),
319                Keyword::TRUNCATE => Ok(self.parse_truncate()?),
320                Keyword::REFRESH => Ok(self.parse_refresh()?),
321                Keyword::CREATE => Ok(self.parse_create()?),
322                Keyword::DISCARD => Ok(self.parse_discard()?),
323                Keyword::DROP => Ok(self.parse_drop()?),
324                Keyword::DELETE => Ok(self.parse_delete()?),
325                Keyword::INSERT => Ok(self.parse_insert()?),
326                Keyword::UPDATE => Ok(self.parse_update()?),
327                Keyword::ALTER => Ok(self.parse_alter()?),
328                Keyword::COPY => Ok(self.parse_copy()?),
329                Keyword::SET => Ok(self.parse_set()?),
330                Keyword::SHOW => {
331                    if self.parse_keyword(Keyword::CREATE) {
332                        Ok(self.parse_show_create()?)
333                    } else {
334                        Ok(self.parse_show()?)
335                    }
336                }
337                Keyword::CANCEL => Ok(self.parse_cancel_job()?),
338                Keyword::KILL => Ok(self.parse_kill_process()?),
339                Keyword::DESCRIBE => Ok(self.parse_describe()?),
340                Keyword::GRANT => Ok(self.parse_grant()?),
341                Keyword::REVOKE => Ok(self.parse_revoke()?),
342                Keyword::START => Ok(self.parse_start_transaction()?),
343                Keyword::ABORT => Ok(Statement::Abort),
344                // `BEGIN` is a nonstandard but common alias for the
345                // standard `START TRANSACTION` statement. It is supported
346                // by at least PostgreSQL and MySQL.
347                Keyword::BEGIN => Ok(self.parse_begin()?),
348                Keyword::COMMIT => Ok(self.parse_commit()?),
349                Keyword::ROLLBACK => Ok(self.parse_rollback()?),
350                // `PREPARE`, `EXECUTE` and `DEALLOCATE` are Postgres-specific
351                // syntaxes. They are used for Postgres prepared statement.
352                Keyword::DEALLOCATE => Ok(self.parse_deallocate()?),
353                Keyword::EXECUTE => Ok(self.parse_execute()?),
354                Keyword::PREPARE => Ok(self.parse_prepare()?),
355                Keyword::COMMENT => Ok(self.parse_comment()?),
356                Keyword::FLUSH => Ok(Statement::Flush),
357                Keyword::WAIT => Ok(Statement::Wait),
358                Keyword::RECOVER => Ok(Statement::Recover),
359                Keyword::USE => Ok(self.parse_use()?),
360                Keyword::VACUUM => Ok(self.parse_vacuum()?),
361                _ => self.expected_at(checkpoint, "statement"),
362            },
363            Token::LParen => {
364                *self = checkpoint;
365                Ok(Statement::Query(Box::new(self.parse_query()?)))
366            }
367            _ => self.expected_at(checkpoint, "statement"),
368        }
369    }
370
371    pub fn parse_truncate(&mut self) -> ModalResult<Statement> {
372        let _ = self.parse_keyword(Keyword::TABLE);
373        let table_name = self.parse_object_name()?;
374        Ok(Statement::Truncate { table_name })
375    }
376
377    pub fn parse_refresh(&mut self) -> ModalResult<Statement> {
378        self.expect_keyword(Keyword::TABLE)?;
379        let table_name = self.parse_object_name()?;
380        Ok(Statement::Refresh { table_name })
381    }
382
383    pub fn parse_analyze(&mut self) -> ModalResult<Statement> {
384        let table_name = self.parse_object_name()?;
385
386        Ok(Statement::Analyze { table_name })
387    }
388
389    pub fn parse_vacuum(&mut self) -> ModalResult<Statement> {
390        let object_name = self.parse_object_name()?;
391
392        Ok(Statement::Vacuum { object_name })
393    }
394
395    /// Tries to parse a wildcard expression. If it is not a wildcard, parses an expression.
396    ///
397    /// A wildcard expression either means:
398    /// - Selecting all fields from a struct. In this case, it is a
399    ///   [`WildcardOrExpr::ExprQualifiedWildcard`]. Similar to [`Expr::FieldIdentifier`], It must
400    ///   contain parentheses.
401    /// - Selecting all columns from a table. In this case, it is a
402    ///   [`WildcardOrExpr::QualifiedWildcard`] or a [`WildcardOrExpr::Wildcard`].
403    pub fn parse_wildcard_or_expr(&mut self) -> ModalResult<WildcardOrExpr> {
404        let checkpoint = *self;
405
406        match self.next_token().token {
407            Token::Word(w) if self.peek_token() == Token::Period => {
408                // Since there's no parenthesis, `w` must be a column or a table
409                // So what follows must be dot-delimited identifiers, e.g. `a.b.c.*`
410                let wildcard_expr = self.parse_simple_wildcard_expr(checkpoint)?;
411                return self.word_concat_wildcard_expr(w.to_ident()?, wildcard_expr);
412            }
413            Token::Mul => {
414                return Ok(WildcardOrExpr::Wildcard(self.parse_except()?));
415            }
416            // parses wildcard field selection expression.
417            // Code is similar to `parse_struct_selection`
418            Token::LParen => {
419                let mut expr = self.parse_expr()?;
420                if self.consume_token(&Token::RParen) {
421                    // Unwrap parentheses
422                    while let Expr::Nested(inner) = expr {
423                        expr = *inner;
424                    }
425                    // Now that we have an expr, what follows must be
426                    // dot-delimited identifiers, e.g. `b.c.*` in `(a).b.c.*`
427                    let wildcard_expr = self.parse_simple_wildcard_expr(checkpoint)?;
428                    return self.expr_concat_wildcard_expr(expr, wildcard_expr);
429                }
430            }
431            _ => (),
432        };
433
434        *self = checkpoint;
435        self.parse_expr().map(WildcardOrExpr::Expr)
436    }
437
438    /// Concats `ident` and `wildcard_expr` in `ident.wildcard_expr`
439    pub fn word_concat_wildcard_expr(
440        &mut self,
441        ident: Ident,
442        simple_wildcard_expr: WildcardOrExpr,
443    ) -> ModalResult<WildcardOrExpr> {
444        let mut idents = vec![ident];
445        let mut except_cols = vec![];
446        match simple_wildcard_expr {
447            WildcardOrExpr::QualifiedWildcard(ids, except) => {
448                idents.extend(ids.0);
449                if let Some(cols) = except {
450                    except_cols = cols;
451                }
452            }
453            WildcardOrExpr::Wildcard(except) => {
454                if let Some(cols) = except {
455                    except_cols = cols;
456                }
457            }
458            WildcardOrExpr::ExprQualifiedWildcard(_, _) => unreachable!(),
459            WildcardOrExpr::Expr(e) => return Ok(WildcardOrExpr::Expr(e)),
460        }
461        Ok(WildcardOrExpr::QualifiedWildcard(
462            ObjectName(idents),
463            if except_cols.is_empty() {
464                None
465            } else {
466                Some(except_cols)
467            },
468        ))
469    }
470
471    /// Concats `expr` and `wildcard_expr` in `(expr).wildcard_expr`.
472    pub fn expr_concat_wildcard_expr(
473        &mut self,
474        expr: Expr,
475        simple_wildcard_expr: WildcardOrExpr,
476    ) -> ModalResult<WildcardOrExpr> {
477        if let WildcardOrExpr::Expr(e) = simple_wildcard_expr {
478            return Ok(WildcardOrExpr::Expr(e));
479        }
480
481        // similar to `parse_struct_selection`
482        let mut idents = vec![];
483        let expr = match expr {
484            // expr is `(foo)`
485            Expr::Identifier(_) => expr,
486            // expr is `(foo.v1)`
487            Expr::CompoundIdentifier(_) => expr,
488            // expr is `((1,2,3)::foo)`
489            Expr::Cast { .. } => expr,
490            // expr is `(func())`
491            Expr::Function(_) => expr,
492            // expr is `((foo.v1).v2)`
493            Expr::FieldIdentifier(expr, ids) => {
494                // Put `ids` to the latter part!
495                idents.extend(ids);
496                *expr
497            }
498            // expr is other things, e.g., `(1+2)`. It will become an unexpected period error at
499            // upper level.
500            _ => return Ok(WildcardOrExpr::Expr(expr)),
501        };
502
503        match simple_wildcard_expr {
504            WildcardOrExpr::QualifiedWildcard(ids, except) => {
505                if except.is_some() {
506                    return self.expected("Expr quantified wildcard does not support except");
507                }
508                idents.extend(ids.0);
509            }
510            WildcardOrExpr::Wildcard(except) => {
511                if except.is_some() {
512                    return self.expected("Expr quantified wildcard does not support except");
513                }
514            }
515            WildcardOrExpr::ExprQualifiedWildcard(_, _) => unreachable!(),
516            WildcardOrExpr::Expr(_) => unreachable!(),
517        }
518        Ok(WildcardOrExpr::ExprQualifiedWildcard(expr, idents))
519    }
520
521    /// Tries to parses a wildcard expression without any parentheses.
522    ///
523    /// If wildcard is not found, go back to `index` and parse an expression.
524    pub fn parse_simple_wildcard_expr(&mut self, checkpoint: Self) -> ModalResult<WildcardOrExpr> {
525        let mut id_parts = vec![];
526        while self.consume_token(&Token::Period) {
527            let ckpt = *self;
528            let token = self.next_token();
529            match token.token {
530                Token::Word(w) => id_parts.push(w.to_ident()?),
531                Token::Mul => {
532                    return if id_parts.is_empty() {
533                        Ok(WildcardOrExpr::Wildcard(self.parse_except()?))
534                    } else {
535                        Ok(WildcardOrExpr::QualifiedWildcard(
536                            ObjectName(id_parts),
537                            self.parse_except()?,
538                        ))
539                    };
540                }
541                _ => {
542                    *self = ckpt;
543                    return self.expected("an identifier or a '*' after '.'");
544                }
545            }
546        }
547        *self = checkpoint;
548        self.parse_expr().map(WildcardOrExpr::Expr)
549    }
550
551    pub fn parse_except(&mut self) -> ModalResult<Option<Vec<Expr>>> {
552        if !self.parse_keyword(Keyword::EXCEPT) {
553            return Ok(None);
554        }
555        if !self.consume_token(&Token::LParen) {
556            return self.expected("EXCEPT should be followed by (");
557        }
558        let exprs = self.parse_comma_separated(Parser::parse_expr)?;
559        if self.consume_token(&Token::RParen) {
560            Ok(Some(exprs))
561        } else {
562            self.expected("( should be followed by ) after column names")
563        }
564    }
565
566    /// Parse a new expression
567    pub fn parse_expr(&mut self) -> ModalResult<Expr> {
568        self.parse_subexpr(Precedence::Zero)
569    }
570
571    /// Parse tokens until the precedence changes
572    pub fn parse_subexpr(&mut self, precedence: Precedence) -> ModalResult<Expr> {
573        debug!("parsing expr, current token: {:?}", self.peek_token().token);
574        let mut expr = self.parse_prefix()?;
575        debug!("prefix: {:?}", expr);
576        loop {
577            let next_precedence = self.get_next_precedence()?;
578            debug!("precedence: {precedence:?}, next precedence: {next_precedence:?}");
579
580            if precedence >= next_precedence {
581                break;
582            }
583
584            expr = self.parse_infix(expr, next_precedence)?;
585        }
586        Ok(expr)
587    }
588
589    /// Parse an expression prefix
590    pub fn parse_prefix(&mut self) -> ModalResult<Expr> {
591        // PostgreSQL allows any string literal to be preceded by a type name, indicating that the
592        // string literal represents a literal of that type. Some examples:
593        //
594        //      DATE '2020-05-20'
595        //      TIMESTAMP WITH TIME ZONE '2020-05-20 7:43:54'
596        //      BOOL 'true'
597        //
598        // The first two are standard SQL, while the latter is a PostgreSQL extension. Complicating
599        // matters is the fact that INTERVAL string literals may optionally be followed by special
600        // keywords, e.g.:
601        //
602        //      INTERVAL '7' DAY
603        //
604        // Note also that naively `SELECT date` looks like a syntax error because the `date` type
605        // name is not followed by a string literal, but in fact in PostgreSQL it is a valid
606        // expression that should parse as the column name "date".
607        return_ok_if_some!(self.maybe_parse(|parser| {
608            match parser.parse_data_type()? {
609                DataType::Interval => parser.parse_literal_interval(),
610                // PostgreSQL allows almost any identifier to be used as custom data type name,
611                // and we support that in `parse_data_type()`. But unlike Postgres we don't
612                // have a list of globally reserved keywords (since they vary across dialects),
613                // so given `NOT 'a' LIKE 'b'`, we'd accept `NOT` as a possible custom data type
614                // name, resulting in `NOT 'a'` being recognized as a `TypedString` instead of
615                // an unary negation `NOT ('a' LIKE 'b')`. To solve this, we don't accept the
616                // `type 'string'` syntax for the custom data types at all.
617                DataType::Custom(..) => parser_err!("dummy"),
618                data_type => Ok(Expr::TypedString {
619                    data_type,
620                    value: parser.parse_literal_string()?,
621                }),
622            }
623        }));
624
625        let checkpoint = *self;
626        let token = self.next_token();
627        let expr = match token.token.clone() {
628            Token::Word(w) => match w.keyword {
629                Keyword::TRUE | Keyword::FALSE | Keyword::NULL => {
630                    *self = checkpoint;
631                    Ok(Expr::Value(self.ensure_parse_value()?))
632                }
633                Keyword::CASE => self.parse_case_expr(),
634                Keyword::CAST => self.parse_cast_expr(),
635                Keyword::TRY_CAST => self.parse_try_cast_expr(),
636                Keyword::EXISTS => self.parse_exists_expr(),
637                Keyword::EXTRACT => self.parse_extract_expr(),
638                Keyword::SUBSTRING => self.parse_substring_expr(),
639                Keyword::POSITION => self.parse_position_expr(),
640                Keyword::OVERLAY => self.parse_overlay_expr(),
641                Keyword::TRIM => self.parse_trim_expr(),
642                Keyword::INTERVAL => self.parse_literal_interval(),
643                Keyword::NOT => Ok(Expr::UnaryOp {
644                    op: UnaryOperator::Not,
645                    expr: Box::new(self.parse_subexpr(Precedence::UnaryNot)?),
646                }),
647                Keyword::ROW => self.parse_row_expr(),
648                Keyword::ARRAY if self.peek_token() == Token::LParen => {
649                    // similar to `exists(subquery)`
650                    self.expect_token(&Token::LParen)?;
651                    let exists_node = Expr::ArraySubquery(Box::new(self.parse_query()?));
652                    self.expect_token(&Token::RParen)?;
653                    Ok(exists_node)
654                }
655                Keyword::ARRAY if self.peek_token() == Token::LBracket => self.parse_array_expr(),
656                Keyword::MAP if self.peek_token() == Token::LBrace => self.parse_map_expr(),
657                // `LEFT` and `RIGHT` are reserved as identifier but okay as function
658                Keyword::LEFT | Keyword::RIGHT => {
659                    *self = checkpoint;
660                    self.parse_function()
661                }
662                Keyword::OPERATOR if self.peek_token().token == Token::LParen => {
663                    let op = UnaryOperator::PGQualified(Box::new(self.parse_qualified_operator()?));
664                    Ok(Expr::UnaryOp {
665                        op,
666                        expr: Box::new(self.parse_subexpr(Precedence::Other)?),
667                    })
668                }
669                keyword @ (Keyword::ALL | Keyword::ANY | Keyword::SOME) => {
670                    self.expect_token(&Token::LParen)?;
671                    // In upstream's PR of parser-rs, there is `self.parser_subexpr(precedence)` here.
672                    // But it will fail to parse `select 1 = any(null and true);`.
673                    let sub = self.parse_expr()?;
674                    self.expect_token(&Token::RParen)?;
675
676                    // TODO: support `all/any/some(subquery)`.
677                    if let Expr::Subquery(_) = &sub {
678                        parser_err!("ANY/SOME/ALL(Subquery) is not implemented");
679                    }
680
681                    Ok(match keyword {
682                        Keyword::ALL => Expr::AllOp(Box::new(sub)),
683                        // `SOME` is a synonym for `ANY`.
684                        Keyword::ANY | Keyword::SOME => Expr::SomeOp(Box::new(sub)),
685                        _ => unreachable!(),
686                    })
687                }
688                k if keywords::RESERVED_FOR_COLUMN_OR_TABLE_NAME.contains(&k) => {
689                    parser_err!("syntax error at or near {token}")
690                }
691                Keyword::AGGREGATE => {
692                    *self = checkpoint;
693                    self.parse_function()
694                }
695                // Here `w` is a word, check if it's a part of a multi-part
696                // identifier, a function call, or a simple identifier:
697                _ => match self.peek_token().token {
698                    Token::LParen | Token::Period => {
699                        *self = checkpoint;
700                        if let Ok(object_name) = self.parse_object_name()
701                            && !matches!(self.peek_token().token, Token::LParen)
702                        {
703                            Ok(Expr::CompoundIdentifier(object_name.0))
704                        } else {
705                            *self = checkpoint;
706                            self.parse_function()
707                        }
708                    }
709                    _ => Ok(Expr::Identifier(w.to_ident()?)),
710                },
711            }, // End of Token::Word
712
713            tok @ Token::Minus | tok @ Token::Plus => {
714                let op = if tok == Token::Plus {
715                    UnaryOperator::Plus
716                } else {
717                    UnaryOperator::Minus
718                };
719                let mut sub_expr = self.parse_subexpr(Precedence::UnaryPosNeg)?;
720                if let Expr::Value(Value::Number(ref mut s)) = sub_expr {
721                    if tok == Token::Minus {
722                        *s = format!("-{}", s);
723                    }
724                    return Ok(sub_expr);
725                }
726                Ok(Expr::UnaryOp {
727                    op,
728                    expr: Box::new(sub_expr),
729                })
730            }
731            Token::Op(name) => {
732                let op = UnaryOperator::Custom(name);
733                // Counter-intuitively, `|/ 4 + 12` means `|/ (4+12)` rather than `(|/4) + 12` in
734                // PostgreSQL.
735                Ok(Expr::UnaryOp {
736                    op,
737                    expr: Box::new(self.parse_subexpr(Precedence::Other)?),
738                })
739            }
740            Token::Number(_)
741            | Token::SingleQuotedString(_)
742            | Token::DollarQuotedString(_)
743            | Token::NationalStringLiteral(_)
744            | Token::HexStringLiteral(_)
745            | Token::CstyleEscapesString(_) => {
746                *self = checkpoint;
747                Ok(Expr::Value(self.ensure_parse_value()?))
748            }
749            Token::Parameter(number) => self.parse_param(number),
750            Token::Pipe => {
751                let args = self.parse_comma_separated(Parser::parse_identifier)?;
752                self.expect_token(&Token::Pipe)?;
753                let body = self.parse_expr()?;
754                Ok(Expr::LambdaFunction {
755                    args,
756                    body: Box::new(body),
757                })
758            }
759            Token::LParen => {
760                let expr = if matches!(self.peek_token().token, Token::Word(w) if w.keyword == Keyword::SELECT || w.keyword == Keyword::WITH)
761                {
762                    Expr::Subquery(Box::new(self.parse_query()?))
763                } else {
764                    let mut exprs = self.parse_comma_separated(Parser::parse_expr)?;
765                    if exprs.len() == 1 {
766                        Expr::Nested(Box::new(exprs.pop().unwrap()))
767                    } else {
768                        Expr::Row(exprs)
769                    }
770                };
771                self.expect_token(&Token::RParen)?;
772                if self.peek_token() == Token::Period && matches!(expr, Expr::Nested(_)) {
773                    self.parse_struct_selection(expr)
774                } else {
775                    Ok(expr)
776                }
777            }
778            _ => self.expected_at(checkpoint, "an expression"),
779        }?;
780
781        if self.parse_keyword(Keyword::COLLATE) {
782            Ok(Expr::Collate {
783                expr: Box::new(expr),
784                collation: self.parse_object_name()?,
785            })
786        } else {
787            Ok(expr)
788        }
789    }
790
791    fn parse_param(&mut self, param: String) -> ModalResult<Expr> {
792        let Ok(index) = param.parse() else {
793            parser_err!("Parameter symbol has a invalid index {}.", param);
794        };
795        Ok(Expr::Parameter { index })
796    }
797
798    /// Parses a field selection expression. See also [`Expr::FieldIdentifier`].
799    pub fn parse_struct_selection(&mut self, expr: Expr) -> ModalResult<Expr> {
800        let mut nested_expr = expr;
801        // Unwrap parentheses
802        while let Expr::Nested(inner) = nested_expr {
803            nested_expr = *inner;
804        }
805        let fields = self.parse_fields()?;
806        Ok(Expr::FieldIdentifier(Box::new(nested_expr), fields))
807    }
808
809    /// Parses consecutive field identifiers after a period. i.e., `.foo.bar.baz`
810    pub fn parse_fields(&mut self) -> ModalResult<Vec<Ident>> {
811        repeat(.., preceded(Token::Period, cut_err(Self::parse_identifier))).parse_next(self)
812    }
813
814    pub fn parse_qualified_operator(&mut self) -> ModalResult<QualifiedOperator> {
815        self.expect_token(&Token::LParen)?;
816
817        let checkpoint = *self;
818        let schema = match self.parse_identifier_non_reserved() {
819            Ok(ident) => {
820                self.expect_token(&Token::Period)?;
821                Some(ident)
822            }
823            Err(_) => {
824                *self = checkpoint;
825                None
826            }
827        };
828
829        // https://www.postgresql.org/docs/15/sql-syntax-lexical.html#SQL-SYNTAX-OPERATORS
830        const OP_CHARS: &[char] = &[
831            '+', '-', '*', '/', '<', '>', '=', '~', '!', '@', '#', '%', '^', '&', '|', '`', '?',
832        ];
833        let name = {
834            // Unlike PostgreSQL, we only take 1 token here rather than any sequence of `OP_CHARS`.
835            // This is enough because we do not support custom operators like `x *@ y` anyways,
836            // and all builtin sequences are already single tokens.
837            //
838            // To support custom operators and be fully compatible with PostgreSQL later, the
839            // tokenizer should also be updated.
840            let checkpoint = *self;
841            let token = self.next_token();
842            let name = token.token.to_string();
843            if !name.trim_matches(OP_CHARS).is_empty() {
844                return self
845                    .expected_at(checkpoint, &format!("one of {}", OP_CHARS.iter().join(" ")));
846            }
847            name
848        };
849
850        self.expect_token(&Token::RParen)?;
851        Ok(QualifiedOperator { schema, name })
852    }
853
854    /// Parse a function call.
855    pub fn parse_function(&mut self) -> ModalResult<Expr> {
856        // [aggregate:]
857        let scalar_as_agg = if self.parse_keyword(Keyword::AGGREGATE) {
858            self.expect_token(&Token::Colon)?;
859            true
860        } else {
861            false
862        };
863        let name = self.parse_object_name()?;
864        let arg_list = self.parse_argument_list()?;
865
866        let within_group = if self.parse_keywords(&[Keyword::WITHIN, Keyword::GROUP]) {
867            self.expect_token(&Token::LParen)?;
868            self.expect_keywords(&[Keyword::ORDER, Keyword::BY])?;
869            let order_by = self.parse_order_by_expr()?;
870            self.expect_token(&Token::RParen)?;
871            Some(Box::new(order_by.clone()))
872        } else {
873            None
874        };
875
876        let filter = if self.parse_keyword(Keyword::FILTER) {
877            self.expect_token(&Token::LParen)?;
878            self.expect_keyword(Keyword::WHERE)?;
879            let filter_expr = self.parse_expr()?;
880            self.expect_token(&Token::RParen)?;
881            Some(Box::new(filter_expr))
882        } else {
883            None
884        };
885
886        let over = if self.parse_keyword(Keyword::OVER) {
887            if self.peek_token() == Token::LParen {
888                // Inline window specification: OVER (...)
889                self.expect_token(&Token::LParen)?;
890                let window_spec = self.parse_window_spec()?;
891                self.expect_token(&Token::RParen)?;
892                Some(Window::Spec(window_spec))
893            } else {
894                // Named window: OVER window_name
895                let window_name = self.parse_identifier()?;
896                Some(Window::Name(window_name))
897            }
898        } else {
899            None
900        };
901
902        Ok(Expr::Function(Function {
903            scalar_as_agg,
904            name,
905            arg_list,
906            within_group,
907            filter,
908            over,
909        }))
910    }
911
912    pub fn parse_window_frame_units(&mut self) -> ModalResult<WindowFrameUnits> {
913        dispatch! { peek(keyword);
914            Keyword::ROWS => keyword.value(WindowFrameUnits::Rows),
915            Keyword::RANGE => keyword.value(WindowFrameUnits::Range),
916            Keyword::GROUPS => keyword.value(WindowFrameUnits::Groups),
917            Keyword::SESSION => keyword.value(WindowFrameUnits::Session),
918            _ => fail,
919        }
920        .expect("ROWS, RANGE, or GROUPS")
921        .parse_next(self)
922    }
923
924    pub fn parse_window_frame(&mut self) -> ModalResult<WindowFrame> {
925        let units = self.parse_window_frame_units()?;
926        let bounds = if self.parse_keyword(Keyword::BETWEEN) {
927            // `BETWEEN <frame_start> AND <frame_end>`
928            let start = self.parse_window_frame_bound()?;
929            self.expect_keyword(Keyword::AND)?;
930            let end = Some(self.parse_window_frame_bound()?);
931            WindowFrameBounds::Bounds { start, end }
932        } else if self.parse_keywords(&[Keyword::WITH, Keyword::GAP]) {
933            // `WITH GAP <gap>`, only for session frames
934            WindowFrameBounds::Gap(Box::new(self.parse_expr()?))
935        } else {
936            // `<frame_start>`
937            WindowFrameBounds::Bounds {
938                start: self.parse_window_frame_bound()?,
939                end: None,
940            }
941        };
942        let exclusion = if self.parse_keyword(Keyword::EXCLUDE) {
943            Some(self.parse_window_frame_exclusion()?)
944        } else {
945            None
946        };
947        Ok(WindowFrame {
948            units,
949            bounds,
950            exclusion,
951        })
952    }
953
954    /// Parse `CURRENT ROW` or `{ <non-negative numeric | datetime | interval> | UNBOUNDED } { PRECEDING | FOLLOWING }`
955    pub fn parse_window_frame_bound(&mut self) -> ModalResult<WindowFrameBound> {
956        if self.parse_keywords(&[Keyword::CURRENT, Keyword::ROW]) {
957            Ok(WindowFrameBound::CurrentRow)
958        } else {
959            let rows = if self.parse_keyword(Keyword::UNBOUNDED) {
960                None
961            } else {
962                Some(Box::new(self.parse_expr()?))
963            };
964            if self.parse_keyword(Keyword::PRECEDING) {
965                Ok(WindowFrameBound::Preceding(rows))
966            } else if self.parse_keyword(Keyword::FOLLOWING) {
967                Ok(WindowFrameBound::Following(rows))
968            } else {
969                self.expected("PRECEDING or FOLLOWING")
970            }
971        }
972    }
973
974    pub fn parse_window_frame_exclusion(&mut self) -> ModalResult<WindowFrameExclusion> {
975        if self.parse_keywords(&[Keyword::CURRENT, Keyword::ROW]) {
976            Ok(WindowFrameExclusion::CurrentRow)
977        } else if self.parse_keyword(Keyword::GROUP) {
978            Ok(WindowFrameExclusion::Group)
979        } else if self.parse_keyword(Keyword::TIES) {
980            Ok(WindowFrameExclusion::Ties)
981        } else if self.parse_keywords(&[Keyword::NO, Keyword::OTHERS]) {
982            Ok(WindowFrameExclusion::NoOthers)
983        } else {
984            self.expected("CURRENT ROW, GROUP, TIES, or NO OTHERS")
985        }
986    }
987
988    /// parse a group by expr. a group by expr can be one of group sets, roll up, cube, or simple
989    /// expr.
990    fn parse_group_by_expr(&mut self) -> ModalResult<Expr> {
991        if self.parse_keywords(&[Keyword::GROUPING, Keyword::SETS]) {
992            self.expect_token(&Token::LParen)?;
993            let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?;
994            self.expect_token(&Token::RParen)?;
995            Ok(Expr::GroupingSets(result))
996        } else if self.parse_keyword(Keyword::CUBE) {
997            self.expect_token(&Token::LParen)?;
998            let result = self.parse_comma_separated(|p| p.parse_tuple(true, false))?;
999            self.expect_token(&Token::RParen)?;
1000            Ok(Expr::Cube(result))
1001        } else if self.parse_keyword(Keyword::ROLLUP) {
1002            self.expect_token(&Token::LParen)?;
1003            let result = self.parse_comma_separated(|p| p.parse_tuple(true, false))?;
1004            self.expect_token(&Token::RParen)?;
1005            Ok(Expr::Rollup(result))
1006        } else {
1007            self.parse_expr()
1008        }
1009    }
1010
1011    /// parse a tuple with `(` and `)`.
1012    /// If `lift_singleton` is true, then a singleton tuple is lifted to a tuple of length 1,
1013    /// otherwise it will fail. If `allow_empty` is true, then an empty tuple is allowed.
1014    fn parse_tuple(&mut self, lift_singleton: bool, allow_empty: bool) -> ModalResult<Vec<Expr>> {
1015        if lift_singleton {
1016            if self.consume_token(&Token::LParen) {
1017                let result = if allow_empty && self.consume_token(&Token::RParen) {
1018                    vec![]
1019                } else {
1020                    let result = self.parse_comma_separated(Parser::parse_expr)?;
1021                    self.expect_token(&Token::RParen)?;
1022                    result
1023                };
1024                Ok(result)
1025            } else {
1026                Ok(vec![self.parse_expr()?])
1027            }
1028        } else {
1029            self.expect_token(&Token::LParen)?;
1030            let result = if allow_empty && self.consume_token(&Token::RParen) {
1031                vec![]
1032            } else {
1033                let result = self.parse_comma_separated(Parser::parse_expr)?;
1034                self.expect_token(&Token::RParen)?;
1035                result
1036            };
1037            Ok(result)
1038        }
1039    }
1040
1041    pub fn parse_case_expr(&mut self) -> ModalResult<Expr> {
1042        parser_v2::expr_case(self)
1043    }
1044
1045    /// Parse a SQL CAST function e.g. `CAST(expr AS FLOAT)`
1046    pub fn parse_cast_expr(&mut self) -> ModalResult<Expr> {
1047        parser_v2::expr_cast(self)
1048    }
1049
1050    /// Parse a SQL TRY_CAST function e.g. `TRY_CAST(expr AS FLOAT)`
1051    pub fn parse_try_cast_expr(&mut self) -> ModalResult<Expr> {
1052        parser_v2::expr_try_cast(self)
1053    }
1054
1055    /// Parse a SQL EXISTS expression e.g. `WHERE EXISTS(SELECT ...)`.
1056    pub fn parse_exists_expr(&mut self) -> ModalResult<Expr> {
1057        self.expect_token(&Token::LParen)?;
1058        let exists_node = Expr::Exists(Box::new(self.parse_query()?));
1059        self.expect_token(&Token::RParen)?;
1060        Ok(exists_node)
1061    }
1062
1063    pub fn parse_extract_expr(&mut self) -> ModalResult<Expr> {
1064        parser_v2::expr_extract(self)
1065    }
1066
1067    pub fn parse_substring_expr(&mut self) -> ModalResult<Expr> {
1068        parser_v2::expr_substring(self)
1069    }
1070
1071    /// `POSITION(<expr> IN <expr>)`
1072    pub fn parse_position_expr(&mut self) -> ModalResult<Expr> {
1073        parser_v2::expr_position(self)
1074    }
1075
1076    /// `OVERLAY(<expr> PLACING <expr> FROM <expr> [ FOR <expr> ])`
1077    pub fn parse_overlay_expr(&mut self) -> ModalResult<Expr> {
1078        parser_v2::expr_overlay(self)
1079    }
1080
1081    /// `TRIM ([WHERE] ['text'] FROM 'text')`\
1082    /// `TRIM ([WHERE] [FROM] 'text' [, 'text'])`
1083    pub fn parse_trim_expr(&mut self) -> ModalResult<Expr> {
1084        self.expect_token(&Token::LParen)?;
1085        let mut trim_where = None;
1086        if let Token::Word(word) = self.peek_token().token
1087            && [Keyword::BOTH, Keyword::LEADING, Keyword::TRAILING].contains(&word.keyword)
1088        {
1089            trim_where = Some(self.parse_trim_where()?);
1090        }
1091
1092        let (mut trim_what, expr) = if self.parse_keyword(Keyword::FROM) {
1093            (None, self.parse_expr()?)
1094        } else {
1095            let mut expr = self.parse_expr()?;
1096            if self.parse_keyword(Keyword::FROM) {
1097                let trim_what = std::mem::replace(&mut expr, self.parse_expr()?);
1098                (Some(Box::new(trim_what)), expr)
1099            } else {
1100                (None, expr)
1101            }
1102        };
1103
1104        if trim_what.is_none() && self.consume_token(&Token::Comma) {
1105            trim_what = Some(Box::new(self.parse_expr()?));
1106        }
1107        self.expect_token(&Token::RParen)?;
1108
1109        Ok(Expr::Trim {
1110            expr: Box::new(expr),
1111            trim_where,
1112            trim_what,
1113        })
1114    }
1115
1116    pub fn parse_trim_where(&mut self) -> ModalResult<TrimWhereField> {
1117        dispatch! { peek(keyword);
1118            Keyword::BOTH => keyword.value(TrimWhereField::Both),
1119            Keyword::LEADING => keyword.value(TrimWhereField::Leading),
1120            Keyword::TRAILING => keyword.value(TrimWhereField::Trailing),
1121            _ => fail
1122        }
1123        .expect("BOTH, LEADING, or TRAILING")
1124        .parse_next(self)
1125    }
1126
1127    /// Parses an array expression `[ex1, ex2, ..]`
1128    pub fn parse_array_expr(&mut self) -> ModalResult<Expr> {
1129        let mut expected_depth = None;
1130        let exprs = self.parse_array_inner(0, &mut expected_depth)?;
1131        Ok(Expr::Array(Array {
1132            elem: exprs,
1133            // Top-level array is named.
1134            named: true,
1135        }))
1136    }
1137
1138    fn parse_array_inner(
1139        &mut self,
1140        depth: usize,
1141        expected_depth: &mut Option<usize>,
1142    ) -> ModalResult<Vec<Expr>> {
1143        self.expect_token(&Token::LBracket)?;
1144        if let Some(expected_depth) = *expected_depth
1145            && depth > expected_depth
1146        {
1147            return self.expected("]");
1148        }
1149        let exprs = if self.peek_token() == Token::LBracket {
1150            self.parse_comma_separated(|parser| {
1151                let exprs = parser.parse_array_inner(depth + 1, expected_depth)?;
1152                Ok(Expr::Array(Array {
1153                    elem: exprs,
1154                    named: false,
1155                }))
1156            })?
1157        } else {
1158            if let Some(expected_depth) = *expected_depth {
1159                if depth < expected_depth {
1160                    return self.expected("[");
1161                }
1162            } else {
1163                *expected_depth = Some(depth);
1164            }
1165            if self.consume_token(&Token::RBracket) {
1166                return Ok(vec![]);
1167            }
1168            self.parse_comma_separated(Self::parse_expr)?
1169        };
1170        self.expect_token(&Token::RBracket)?;
1171        Ok(exprs)
1172    }
1173
1174    /// Parses a map expression `MAP {k1:v1, k2:v2, ..}`
1175    pub fn parse_map_expr(&mut self) -> ModalResult<Expr> {
1176        self.expect_token(&Token::LBrace)?;
1177        if self.consume_token(&Token::RBrace) {
1178            return Ok(Expr::Map { entries: vec![] });
1179        }
1180        let entries = self.parse_comma_separated(|parser| {
1181            let key = parser.parse_expr()?;
1182            parser.expect_token(&Token::Colon)?;
1183            let value = parser.parse_expr()?;
1184            Ok((key, value))
1185        })?;
1186        self.expect_token(&Token::RBrace)?;
1187        Ok(Expr::Map { entries })
1188    }
1189
1190    // This function parses date/time fields for interval qualifiers.
1191    pub fn parse_date_time_field(&mut self) -> ModalResult<DateTimeField> {
1192        dispatch! { peek(keyword);
1193            Keyword::YEAR => keyword.value(DateTimeField::Year),
1194            Keyword::MONTH => keyword.value(DateTimeField::Month),
1195            Keyword::DAY => keyword.value(DateTimeField::Day),
1196            Keyword::HOUR => keyword.value(DateTimeField::Hour),
1197            Keyword::MINUTE => keyword.value(DateTimeField::Minute),
1198            Keyword::SECOND => keyword.value(DateTimeField::Second),
1199            _ => fail,
1200        }
1201        .expect("date/time field")
1202        .parse_next(self)
1203    }
1204
1205    // This function parses date/time fields for the EXTRACT function-like operator. PostgreSQL
1206    // allows arbitrary inputs including invalid ones.
1207    //
1208    // ```
1209    //   select extract(day from null::date);
1210    //   select extract(invalid from null::date);
1211    //   select extract("invaLId" from null::date);
1212    //   select extract('invaLId' from null::date);
1213    // ```
1214    pub fn parse_date_time_field_in_extract(&mut self) -> ModalResult<String> {
1215        let checkpoint = *self;
1216        let token = self.next_token();
1217        match token.token {
1218            Token::Word(w) => Ok(w.value.to_uppercase()),
1219            Token::SingleQuotedString(s) => Ok(s.to_uppercase()),
1220            _ => {
1221                *self = checkpoint;
1222                self.expected("date/time field")
1223            }
1224        }
1225    }
1226
1227    /// Parse an INTERVAL literal.
1228    ///
1229    /// Some syntactically valid intervals:
1230    ///
1231    ///   1. `INTERVAL '1' DAY`
1232    ///   2. `INTERVAL '1-1' YEAR TO MONTH`
1233    ///   3. `INTERVAL '1' SECOND`
1234    ///   4. `INTERVAL '1:1:1.1' HOUR (5) TO SECOND (5)`
1235    ///   5. `INTERVAL '1.1' SECOND (2, 2)`
1236    ///   6. `INTERVAL '1:1' HOUR (5) TO MINUTE (5)`
1237    ///
1238    /// Note that we do not currently attempt to parse the quoted value.
1239    pub fn parse_literal_interval(&mut self) -> ModalResult<Expr> {
1240        // The SQL standard allows an optional sign before the value string, but
1241        // it is not clear if any implementations support that syntax, so we
1242        // don't currently try to parse it. (The sign can instead be included
1243        // inside the value string.)
1244
1245        // The first token in an interval is a string literal which specifies
1246        // the duration of the interval.
1247        let value = self.parse_literal_string()?;
1248
1249        // Following the string literal is a qualifier which indicates the units
1250        // of the duration specified in the string literal.
1251        //
1252        // Note that PostgreSQL allows omitting the qualifier, so we provide
1253        // this more general implementation.
1254        let leading_field = match self.peek_token().token {
1255            Token::Word(kw)
1256                if [
1257                    Keyword::YEAR,
1258                    Keyword::MONTH,
1259                    Keyword::DAY,
1260                    Keyword::HOUR,
1261                    Keyword::MINUTE,
1262                    Keyword::SECOND,
1263                ]
1264                .contains(&kw.keyword) =>
1265            {
1266                Some(self.parse_date_time_field()?)
1267            }
1268            _ => None,
1269        };
1270
1271        let (leading_precision, last_field, fsec_precision) =
1272            if leading_field == Some(DateTimeField::Second) {
1273                // SQL mandates special syntax for `SECOND TO SECOND` literals.
1274                // Instead of
1275                //     `SECOND [(<leading precision>)] TO SECOND[(<fractional seconds precision>)]`
1276                // one must use the special format:
1277                //     `SECOND [( <leading precision> [ , <fractional seconds precision>] )]`
1278                let last_field = None;
1279                let (leading_precision, fsec_precision) = self.parse_optional_precision_scale()?;
1280                (leading_precision, last_field, fsec_precision)
1281            } else {
1282                let leading_precision = self.parse_optional_precision()?;
1283                if self.parse_keyword(Keyword::TO) {
1284                    let last_field = Some(self.parse_date_time_field()?);
1285                    let fsec_precision = if last_field == Some(DateTimeField::Second) {
1286                        self.parse_optional_precision()?
1287                    } else {
1288                        None
1289                    };
1290                    (leading_precision, last_field, fsec_precision)
1291                } else {
1292                    (leading_precision, None, None)
1293                }
1294            };
1295
1296        Ok(Expr::Value(Value::Interval {
1297            value,
1298            leading_field,
1299            leading_precision,
1300            last_field,
1301            fractional_seconds_precision: fsec_precision,
1302        }))
1303    }
1304
1305    /// Parse an operator following an expression
1306    pub fn parse_infix(&mut self, expr: Expr, precedence: Precedence) -> ModalResult<Expr> {
1307        let checkpoint = *self;
1308        let tok = self.next_token();
1309        debug!("parsing infix {:?}", tok.token);
1310        let regular_binary_operator = match &tok.token {
1311            Token::Eq => Some(BinaryOperator::Eq),
1312            Token::Neq => Some(BinaryOperator::NotEq),
1313            Token::Gt => Some(BinaryOperator::Gt),
1314            Token::GtEq => Some(BinaryOperator::GtEq),
1315            Token::Lt => Some(BinaryOperator::Lt),
1316            Token::LtEq => Some(BinaryOperator::LtEq),
1317            Token::Plus => Some(BinaryOperator::Plus),
1318            Token::Minus => Some(BinaryOperator::Minus),
1319            Token::Mul => Some(BinaryOperator::Multiply),
1320            Token::Mod => Some(BinaryOperator::Modulo),
1321            Token::Pipe => Some(BinaryOperator::Custom("|".to_owned())),
1322            Token::Caret => Some(BinaryOperator::Pow),
1323            Token::Div => Some(BinaryOperator::Divide),
1324            Token::Op(name) => Some(BinaryOperator::Custom(name.clone())),
1325            Token::Word(w) => match w.keyword {
1326                Keyword::AND => Some(BinaryOperator::And),
1327                Keyword::OR => Some(BinaryOperator::Or),
1328                Keyword::XOR => Some(BinaryOperator::Xor),
1329                Keyword::OPERATOR if self.peek_token() == Token::LParen => Some(
1330                    BinaryOperator::PGQualified(Box::new(self.parse_qualified_operator()?)),
1331                ),
1332                _ => None,
1333            },
1334            _ => None,
1335        };
1336
1337        if let Some(op) = regular_binary_operator {
1338            // // `all/any/some` only appears to the right of the binary op.
1339            // if let Some(keyword) =
1340            //     self.parse_one_of_keywords(&[Keyword::ANY, Keyword::ALL, Keyword::SOME])
1341            // {
1342            //     self.expect_token(&Token::LParen)?;
1343            //     // In upstream's PR of parser-rs, there is `self.parser_subexpr(precedence)` here.
1344            //     // But it will fail to parse `select 1 = any(null and true);`.
1345            //     let right = self.parse_expr()?;
1346            //     self.expect_token(&Token::RParen)?;
1347
1348            //     // TODO: support `all/any/some(subquery)`.
1349            //     if let Expr::Subquery(_) = &right {
1350            //         parser_err!("ANY/SOME/ALL(Subquery) is not implemented");
1351            //     }
1352
1353            //     let right = match keyword {
1354            //         Keyword::ALL => Box::new(Expr::AllOp(Box::new(right))),
1355            //         // `SOME` is a synonym for `ANY`.
1356            //         Keyword::ANY | Keyword::SOME => Box::new(Expr::SomeOp(Box::new(right))),
1357            //         _ => unreachable!(),
1358            //     };
1359
1360            //     Ok(Expr::BinaryOp {
1361            //         left: Box::new(expr),
1362            //         op,
1363            //         right,
1364            //     })
1365            // } else {
1366            Ok(Expr::BinaryOp {
1367                left: Box::new(expr),
1368                op,
1369                right: Box::new(self.parse_subexpr(precedence)?),
1370            })
1371            // }
1372        } else if let Token::Word(w) = &tok.token {
1373            match w.keyword {
1374                Keyword::IS => {
1375                    if self.parse_keyword(Keyword::TRUE) {
1376                        Ok(Expr::IsTrue(Box::new(expr)))
1377                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::TRUE]) {
1378                        Ok(Expr::IsNotTrue(Box::new(expr)))
1379                    } else if self.parse_keyword(Keyword::FALSE) {
1380                        Ok(Expr::IsFalse(Box::new(expr)))
1381                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::FALSE]) {
1382                        Ok(Expr::IsNotFalse(Box::new(expr)))
1383                    } else if self.parse_keyword(Keyword::UNKNOWN) {
1384                        Ok(Expr::IsUnknown(Box::new(expr)))
1385                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::UNKNOWN]) {
1386                        Ok(Expr::IsNotUnknown(Box::new(expr)))
1387                    } else if self.parse_keyword(Keyword::NULL) {
1388                        Ok(Expr::IsNull(Box::new(expr)))
1389                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) {
1390                        Ok(Expr::IsNotNull(Box::new(expr)))
1391                    } else if self.parse_keywords(&[Keyword::DISTINCT, Keyword::FROM]) {
1392                        let expr2 = self.parse_expr()?;
1393                        Ok(Expr::IsDistinctFrom(Box::new(expr), Box::new(expr2)))
1394                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::DISTINCT, Keyword::FROM])
1395                    {
1396                        let expr2 = self.parse_expr()?;
1397                        Ok(Expr::IsNotDistinctFrom(Box::new(expr), Box::new(expr2)))
1398                    } else {
1399                        let negated = self.parse_keyword(Keyword::NOT);
1400
1401                        if self.parse_keyword(Keyword::JSON) {
1402                            self.parse_is_json(expr, negated)
1403                        } else {
1404                            self.expected(
1405                                "[NOT] { TRUE | FALSE | UNKNOWN | NULL | DISTINCT FROM | JSON } after IS",
1406                            )
1407                        }
1408                    }
1409                }
1410                Keyword::AT => {
1411                    assert_eq!(precedence, Precedence::At);
1412                    let time_zone = Box::new(
1413                        preceded(
1414                            (Keyword::TIME, Keyword::ZONE),
1415                            cut_err(|p: &mut Self| p.parse_subexpr(precedence)),
1416                        )
1417                        .parse_next(self)?,
1418                    );
1419                    Ok(Expr::AtTimeZone {
1420                        timestamp: Box::new(expr),
1421                        time_zone,
1422                    })
1423                }
1424                keyword @ (Keyword::ALL | Keyword::ANY | Keyword::SOME) => {
1425                    self.expect_token(&Token::LParen)?;
1426                    // In upstream's PR of parser-rs, there is `self.parser_subexpr(precedence)` here.
1427                    // But it will fail to parse `select 1 = any(null and true);`.
1428                    let sub = self.parse_expr()?;
1429                    self.expect_token(&Token::RParen)?;
1430
1431                    // TODO: support `all/any/some(subquery)`.
1432                    if let Expr::Subquery(_) = &sub {
1433                        parser_err!("ANY/SOME/ALL(Subquery) is not implemented");
1434                    }
1435
1436                    Ok(match keyword {
1437                        Keyword::ALL => Expr::AllOp(Box::new(sub)),
1438                        // `SOME` is a synonym for `ANY`.
1439                        Keyword::ANY | Keyword::SOME => Expr::SomeOp(Box::new(sub)),
1440                        _ => unreachable!(),
1441                    })
1442                }
1443                Keyword::NOT
1444                | Keyword::IN
1445                | Keyword::BETWEEN
1446                | Keyword::LIKE
1447                | Keyword::ILIKE
1448                | Keyword::SIMILAR => {
1449                    *self = checkpoint;
1450                    let negated = self.parse_keyword(Keyword::NOT);
1451                    if self.parse_keyword(Keyword::IN) {
1452                        self.parse_in(expr, negated)
1453                    } else if self.parse_keyword(Keyword::BETWEEN) {
1454                        self.parse_between(expr, negated)
1455                    } else if self.parse_keyword(Keyword::LIKE) {
1456                        Ok(Expr::Like {
1457                            negated,
1458                            expr: Box::new(expr),
1459                            pattern: Box::new(self.parse_subexpr(Precedence::Like)?),
1460                            escape_char: self.parse_escape()?,
1461                        })
1462                    } else if self.parse_keyword(Keyword::ILIKE) {
1463                        Ok(Expr::ILike {
1464                            negated,
1465                            expr: Box::new(expr),
1466                            pattern: Box::new(self.parse_subexpr(Precedence::Like)?),
1467                            escape_char: self.parse_escape()?,
1468                        })
1469                    } else if self.parse_keywords(&[Keyword::SIMILAR, Keyword::TO]) {
1470                        Ok(Expr::SimilarTo {
1471                            negated,
1472                            expr: Box::new(expr),
1473                            pattern: Box::new(self.parse_subexpr(Precedence::Like)?),
1474                            escape_char: self.parse_escape()?,
1475                        })
1476                    } else {
1477                        self.expected("IN, BETWEEN or SIMILAR TO after NOT")
1478                    }
1479                }
1480                // Can only happen if `get_next_precedence` got out of sync with this function
1481                _ => parser_err!("No infix parser for token {:?}", tok),
1482            }
1483        } else if Token::DoubleColon == tok {
1484            self.parse_pg_cast(expr)
1485        } else if Token::LBracket == tok {
1486            self.parse_array_index(expr)
1487        } else {
1488            // Can only happen if `get_next_precedence` got out of sync with this function
1489            parser_err!("No infix parser for token {:?}", tok)
1490        }
1491    }
1492
1493    /// parse the ESCAPE CHAR portion of LIKE, ILIKE, and SIMILAR TO
1494    pub fn parse_escape(&mut self) -> ModalResult<Option<EscapeChar>> {
1495        if self.parse_keyword(Keyword::ESCAPE) {
1496            let s = self.parse_literal_string()?;
1497            let mut chs = s.chars();
1498            if let Some(ch) = chs.next() {
1499                if chs.next().is_some() {
1500                    parser_err!("Escape string must be empty or one character, found {s:?}")
1501                } else {
1502                    Ok(Some(EscapeChar::escape(ch)))
1503                }
1504            } else {
1505                Ok(Some(EscapeChar::empty()))
1506            }
1507        } else {
1508            Ok(None)
1509        }
1510    }
1511
1512    /// We parse both `array[1,9][1]`, `array[1,9][1:2]`, `array[1,9][:2]`, `array[1,9][1:]` and
1513    /// `array[1,9][:]` in this function.
1514    pub fn parse_array_index(&mut self, expr: Expr) -> ModalResult<Expr> {
1515        let new_expr = match self.peek_token().token {
1516            Token::Colon => {
1517                // [:] or [:N]
1518                assert!(self.consume_token(&Token::Colon));
1519                let end = match self.peek_token().token {
1520                    Token::RBracket => None,
1521                    _ => {
1522                        let end_index = Box::new(self.parse_expr()?);
1523                        Some(end_index)
1524                    }
1525                };
1526                Expr::ArrayRangeIndex {
1527                    obj: Box::new(expr),
1528                    start: None,
1529                    end,
1530                }
1531            }
1532            _ => {
1533                // [N], [N:], [N:M]
1534                let index = Box::new(self.parse_expr()?);
1535                match self.peek_token().token {
1536                    Token::Colon => {
1537                        // [N:], [N:M]
1538                        assert!(self.consume_token(&Token::Colon));
1539                        match self.peek_token().token {
1540                            Token::RBracket => {
1541                                // [N:]
1542                                Expr::ArrayRangeIndex {
1543                                    obj: Box::new(expr),
1544                                    start: Some(index),
1545                                    end: None,
1546                                }
1547                            }
1548                            _ => {
1549                                // [N:M]
1550                                let end = Some(Box::new(self.parse_expr()?));
1551                                Expr::ArrayRangeIndex {
1552                                    obj: Box::new(expr),
1553                                    start: Some(index),
1554                                    end,
1555                                }
1556                            }
1557                        }
1558                    }
1559                    _ => {
1560                        // [N]
1561                        Expr::Index {
1562                            obj: Box::new(expr),
1563                            index,
1564                        }
1565                    }
1566                }
1567            }
1568        };
1569        self.expect_token(&Token::RBracket)?;
1570        // recursively checking for more indices
1571        if self.consume_token(&Token::LBracket) {
1572            self.parse_array_index(new_expr)
1573        } else {
1574            Ok(new_expr)
1575        }
1576    }
1577
1578    /// Parses the optional constraints following the `IS [NOT] JSON` predicate
1579    pub fn parse_is_json(&mut self, expr: Expr, negated: bool) -> ModalResult<Expr> {
1580        let item_type = match self.peek_token().token {
1581            Token::Word(w) => match w.keyword {
1582                Keyword::VALUE => Some(JsonPredicateType::Value),
1583                Keyword::ARRAY => Some(JsonPredicateType::Array),
1584                Keyword::OBJECT => Some(JsonPredicateType::Object),
1585                Keyword::SCALAR => Some(JsonPredicateType::Scalar),
1586                _ => None,
1587            },
1588            _ => None,
1589        };
1590        if item_type.is_some() {
1591            self.next_token();
1592        }
1593        let item_type = item_type.unwrap_or_default();
1594
1595        let unique_keys = self.parse_one_of_keywords(&[Keyword::WITH, Keyword::WITHOUT]);
1596        if unique_keys.is_some() {
1597            self.expect_keyword(Keyword::UNIQUE)?;
1598            _ = self.parse_keyword(Keyword::KEYS);
1599        }
1600        let unique_keys = unique_keys.is_some_and(|w| w == Keyword::WITH);
1601
1602        Ok(Expr::IsJson {
1603            expr: Box::new(expr),
1604            negated,
1605            item_type,
1606            unique_keys,
1607        })
1608    }
1609
1610    /// Parses the parens following the `[ NOT ] IN` operator
1611    pub fn parse_in(&mut self, expr: Expr, negated: bool) -> ModalResult<Expr> {
1612        self.expect_token(&Token::LParen)?;
1613        let in_op = if matches!(self.peek_token().token, Token::Word(w) if w.keyword == Keyword::SELECT || w.keyword == Keyword::WITH)
1614        {
1615            Expr::InSubquery {
1616                expr: Box::new(expr),
1617                subquery: Box::new(self.parse_query()?),
1618                negated,
1619            }
1620        } else {
1621            Expr::InList {
1622                expr: Box::new(expr),
1623                list: self.parse_comma_separated(Parser::parse_expr)?,
1624                negated,
1625            }
1626        };
1627        self.expect_token(&Token::RParen)?;
1628        Ok(in_op)
1629    }
1630
1631    /// Parses `BETWEEN <low> AND <high>`, assuming the `BETWEEN` keyword was already consumed
1632    pub fn parse_between(&mut self, expr: Expr, negated: bool) -> ModalResult<Expr> {
1633        // Stop parsing subexpressions for <low> and <high> on tokens with
1634        // precedence lower than that of `BETWEEN`, such as `AND`, `IS`, etc.
1635        let low = self.parse_subexpr(Precedence::Between)?;
1636        self.expect_keyword(Keyword::AND)?;
1637        let high = self.parse_subexpr(Precedence::Between)?;
1638        Ok(Expr::Between {
1639            expr: Box::new(expr),
1640            negated,
1641            low: Box::new(low),
1642            high: Box::new(high),
1643        })
1644    }
1645
1646    /// Parse a postgresql casting style which is in the form of `expr::datatype`
1647    pub fn parse_pg_cast(&mut self, expr: Expr) -> ModalResult<Expr> {
1648        Ok(Expr::Cast {
1649            expr: Box::new(expr),
1650            data_type: self.parse_data_type()?,
1651        })
1652    }
1653
1654    /// Get the precedence of the next token
1655    pub fn get_next_precedence(&self) -> ModalResult<Precedence> {
1656        use Precedence as P;
1657
1658        let token = self.peek_token();
1659        debug!("get_next_precedence() {:?}", token);
1660        match token.token {
1661            Token::Word(w) if w.keyword == Keyword::OR => Ok(P::LogicalOr),
1662            Token::Word(w) if w.keyword == Keyword::XOR => Ok(P::LogicalXor),
1663            Token::Word(w) if w.keyword == Keyword::AND => Ok(P::LogicalAnd),
1664            Token::Word(w) if w.keyword == Keyword::AT => {
1665                match (self.peek_nth_token(1).token, self.peek_nth_token(2).token) {
1666                    (Token::Word(w), Token::Word(w2))
1667                        if w.keyword == Keyword::TIME && w2.keyword == Keyword::ZONE =>
1668                    {
1669                        Ok(P::At)
1670                    }
1671                    _ => Ok(P::Zero),
1672                }
1673            }
1674
1675            Token::Word(w) if w.keyword == Keyword::NOT => match self.peek_nth_token(1).token {
1676                // The precedence of NOT varies depending on keyword that
1677                // follows it. If it is followed by IN, BETWEEN, or LIKE,
1678                // it takes on the precedence of those tokens. Otherwise it
1679                // is not an infix operator, and therefore has zero
1680                // precedence.
1681                Token::Word(w) if w.keyword == Keyword::BETWEEN => Ok(P::Between),
1682                Token::Word(w) if w.keyword == Keyword::IN => Ok(P::Between),
1683                Token::Word(w) if w.keyword == Keyword::LIKE => Ok(P::Like),
1684                Token::Word(w) if w.keyword == Keyword::ILIKE => Ok(P::Like),
1685                Token::Word(w) if w.keyword == Keyword::SIMILAR => Ok(P::Like),
1686                _ => Ok(P::Zero),
1687            },
1688
1689            Token::Word(w) if w.keyword == Keyword::IS => Ok(P::Is),
1690            Token::Word(w) if w.keyword == Keyword::ISNULL => Ok(P::Is),
1691            Token::Word(w) if w.keyword == Keyword::NOTNULL => Ok(P::Is),
1692            Token::Eq | Token::Lt | Token::LtEq | Token::Neq | Token::Gt | Token::GtEq => {
1693                Ok(P::Cmp)
1694            }
1695            Token::Word(w) if w.keyword == Keyword::IN => Ok(P::Between),
1696            Token::Word(w) if w.keyword == Keyword::BETWEEN => Ok(P::Between),
1697            Token::Word(w) if w.keyword == Keyword::LIKE => Ok(P::Like),
1698            Token::Word(w) if w.keyword == Keyword::ILIKE => Ok(P::Like),
1699            Token::Word(w) if w.keyword == Keyword::SIMILAR => Ok(P::Like),
1700            Token::Word(w) if w.keyword == Keyword::ALL => Ok(P::Other),
1701            Token::Word(w) if w.keyword == Keyword::ANY => Ok(P::Other),
1702            Token::Word(w) if w.keyword == Keyword::SOME => Ok(P::Other),
1703            Token::Op(_) => Ok(P::Other),
1704            Token::Word(w)
1705                if w.keyword == Keyword::OPERATOR && self.peek_nth_token(1) == Token::LParen =>
1706            {
1707                Ok(P::Other)
1708            }
1709            // In some languages (incl. rust, c), bitwise operators have precedence:
1710            //   or < xor < and < shift
1711            // But in PostgreSQL, they are just left to right. So `2 | 3 & 4` is 0.
1712            Token::Pipe => Ok(P::Other),
1713            Token::Plus | Token::Minus => Ok(P::PlusMinus),
1714            Token::Mul | Token::Div | Token::Mod => Ok(P::MulDiv),
1715            Token::Caret => Ok(P::Exp),
1716            Token::LBracket => Ok(P::Array),
1717            Token::DoubleColon => Ok(P::DoubleColon),
1718            _ => Ok(P::Zero),
1719        }
1720    }
1721
1722    /// Return the first non-whitespace token that has not yet been processed
1723    /// (or None if reached end-of-file)
1724    pub fn peek_token(&self) -> TokenWithLocation {
1725        self.peek_nth_token(0)
1726    }
1727
1728    /// Return nth non-whitespace token that has not yet been processed
1729    pub fn peek_nth_token(&self, mut n: usize) -> TokenWithLocation {
1730        let mut index = 0;
1731        loop {
1732            let token = self.0.get(index);
1733            index += 1;
1734            match token.map(|x| &x.token) {
1735                Some(Token::Whitespace(_)) => continue,
1736                _ => {
1737                    if n == 0 {
1738                        return token.cloned().unwrap_or(TokenWithLocation::eof());
1739                    }
1740                    n -= 1;
1741                }
1742            }
1743        }
1744    }
1745
1746    /// Return the first non-whitespace token that has not yet been processed
1747    /// (or None if reached end-of-file) and mark it as processed. OK to call
1748    /// repeatedly after reaching EOF.
1749    pub fn next_token(&mut self) -> TokenWithLocation {
1750        loop {
1751            let Some(token) = self.0.first() else {
1752                return TokenWithLocation::eof();
1753            };
1754            self.0 = &self.0[1..];
1755            match token.token {
1756                Token::Whitespace(_) => continue,
1757                _ => return token.clone(),
1758            }
1759        }
1760    }
1761
1762    /// Return the first unprocessed token, possibly whitespace.
1763    pub fn next_token_no_skip(&mut self) -> Option<&TokenWithLocation> {
1764        if self.0.is_empty() {
1765            None
1766        } else {
1767            let (first, rest) = self.0.split_at(1);
1768            self.0 = rest;
1769            Some(&first[0])
1770        }
1771    }
1772
1773    /// Report an expected error at the current position.
1774    pub fn expected<T>(&self, expected: &str) -> ModalResult<T> {
1775        parser_err!("expected {}, found: {}", expected, self.peek_token().token)
1776    }
1777
1778    /// Revert the parser to a previous position and report an expected error.
1779    pub fn expected_at<T>(&mut self, checkpoint: Self, expected: &str) -> ModalResult<T> {
1780        *self = checkpoint;
1781        self.expected(expected)
1782    }
1783
1784    /// Check if the expected match is the next token.
1785    /// The equality check is case-insensitive.
1786    pub fn parse_word(&mut self, expected: &str) -> bool {
1787        match self.peek_token().token {
1788            Token::Word(w) if w.value.to_uppercase() == expected => {
1789                self.next_token();
1790                true
1791            }
1792            _ => false,
1793        }
1794    }
1795
1796    pub fn expect_word(&mut self, expected: &str) -> ModalResult<()> {
1797        if self.parse_word(expected) {
1798            Ok(())
1799        } else {
1800            self.expected(expected)
1801        }
1802    }
1803
1804    /// Look for an expected keyword and consume it if it exists
1805    #[must_use]
1806    pub fn parse_keyword(&mut self, expected: Keyword) -> bool {
1807        match self.peek_token().token {
1808            Token::Word(w) if expected == w.keyword => {
1809                self.next_token();
1810                true
1811            }
1812            _ => false,
1813        }
1814    }
1815
1816    /// Look for an expected sequence of keywords and consume them if they exist
1817    #[must_use]
1818    pub fn parse_keywords(&mut self, keywords: &[Keyword]) -> bool {
1819        let checkpoint = *self;
1820        for &keyword in keywords {
1821            if !self.parse_keyword(keyword) {
1822                // println!("parse_keywords aborting .. did not find {:?}", keyword);
1823                // reset index and return immediately
1824                *self = checkpoint;
1825                return false;
1826            }
1827        }
1828        true
1829    }
1830
1831    /// Look for one of the given keywords and return the one that matches.
1832    #[must_use]
1833    pub fn parse_one_of_keywords(&mut self, keywords: &[Keyword]) -> Option<Keyword> {
1834        match self.peek_token().token {
1835            Token::Word(w) => {
1836                keywords
1837                    .iter()
1838                    .find(|keyword| **keyword == w.keyword)
1839                    .map(|keyword| {
1840                        self.next_token();
1841                        *keyword
1842                    })
1843            }
1844            _ => None,
1845        }
1846    }
1847
1848    pub fn peek_nth_any_of_keywords(&mut self, n: usize, keywords: &[Keyword]) -> bool {
1849        match self.peek_nth_token(n).token {
1850            Token::Word(w) => keywords.contains(&w.keyword),
1851            _ => false,
1852        }
1853    }
1854
1855    /// Bail out if the current token is not one of the expected keywords, or consume it if it is
1856    pub fn expect_one_of_keywords(&mut self, keywords: &[Keyword]) -> ModalResult<Keyword> {
1857        if let Some(keyword) = self.parse_one_of_keywords(keywords) {
1858            Ok(keyword)
1859        } else {
1860            let keywords: Vec<String> = keywords.iter().map(|x| format!("{:?}", x)).collect();
1861            self.expected(&format!("one of {}", keywords.join(" or ")))
1862        }
1863    }
1864
1865    /// Bail out if the current token is not an expected keyword, or consume it if it is
1866    pub fn expect_keyword(&mut self, expected: Keyword) -> ModalResult<()> {
1867        if self.parse_keyword(expected) {
1868            Ok(())
1869        } else {
1870            self.expected(format!("{:?}", &expected).as_str())
1871        }
1872    }
1873
1874    /// Bail out if the following tokens are not the expected sequence of
1875    /// keywords, or consume them if they are.
1876    pub fn expect_keywords(&mut self, expected: &[Keyword]) -> ModalResult<()> {
1877        for &kw in expected {
1878            self.expect_keyword(kw)?;
1879        }
1880        Ok(())
1881    }
1882
1883    /// Consume the next token if it matches the expected token, otherwise return false
1884    #[must_use]
1885    pub fn consume_token(&mut self, expected: &Token) -> bool {
1886        if self.peek_token() == *expected {
1887            self.next_token();
1888            true
1889        } else {
1890            false
1891        }
1892    }
1893
1894    /// Bail out if the current token is not an expected keyword, or consume it if it is
1895    pub fn expect_token(&mut self, expected: &Token) -> ModalResult<()> {
1896        if self.consume_token(expected) {
1897            Ok(())
1898        } else {
1899            self.expected(&expected.to_string())
1900        }
1901    }
1902
1903    /// Parse a comma-separated list of 1+ items accepted by `F`
1904    pub fn parse_comma_separated<T, F>(&mut self, mut f: F) -> ModalResult<Vec<T>>
1905    where
1906        F: FnMut(&mut Self) -> ModalResult<T>,
1907    {
1908        let mut values = vec![];
1909        loop {
1910            values.push(f(self)?);
1911            if !self.consume_token(&Token::Comma) {
1912                break;
1913            }
1914        }
1915        Ok(values)
1916    }
1917
1918    /// Run a parser method `f`, reverting back to the current position
1919    /// if unsuccessful.
1920    #[must_use]
1921    fn maybe_parse<T, F>(&mut self, mut f: F) -> Option<T>
1922    where
1923        F: FnMut(&mut Self) -> ModalResult<T>,
1924    {
1925        let checkpoint = *self;
1926        match f(self) {
1927            Ok(t) => Some(t),
1928            _ => {
1929                *self = checkpoint;
1930                None
1931            }
1932        }
1933    }
1934
1935    /// Parse either `ALL` or `DISTINCT`. Returns `true` if `DISTINCT` is parsed and results in a
1936    /// `ParserError` if both `ALL` and `DISTINCT` are fround.
1937    pub fn parse_all_or_distinct(&mut self) -> ModalResult<bool> {
1938        let all = self.parse_keyword(Keyword::ALL);
1939        let distinct = self.parse_keyword(Keyword::DISTINCT);
1940        if all && distinct {
1941            parser_err!("Cannot specify both ALL and DISTINCT")
1942        } else {
1943            Ok(distinct)
1944        }
1945    }
1946
1947    /// Parse either `ALL` or `DISTINCT` or `DISTINCT ON (<expr>)`.
1948    pub fn parse_all_or_distinct_on(&mut self) -> ModalResult<Distinct> {
1949        if self.parse_keywords(&[Keyword::DISTINCT, Keyword::ON]) {
1950            self.expect_token(&Token::LParen)?;
1951            let exprs = self.parse_comma_separated(Parser::parse_expr)?;
1952            self.expect_token(&Token::RParen)?;
1953            return Ok(Distinct::DistinctOn(exprs));
1954        } else if self.parse_keyword(Keyword::DISTINCT) {
1955            return Ok(Distinct::Distinct);
1956        };
1957        _ = self.parse_keyword(Keyword::ALL);
1958        Ok(Distinct::All)
1959    }
1960
1961    /// Parse a SQL CREATE statement
1962    pub fn parse_create(&mut self) -> ModalResult<Statement> {
1963        let or_replace = self.parse_keywords(&[Keyword::OR, Keyword::REPLACE]);
1964        let temporary = self
1965            .parse_one_of_keywords(&[Keyword::TEMP, Keyword::TEMPORARY])
1966            .is_some();
1967        if self.parse_keyword(Keyword::TABLE) {
1968            self.parse_create_table(or_replace, temporary)
1969        } else if self.parse_keyword(Keyword::VIEW) {
1970            self.parse_create_view(false, or_replace)
1971        } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEW]) {
1972            self.parse_create_view(true, or_replace)
1973        } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::SOURCE]) {
1974            parser_err!("CREATE MATERIALIZED SOURCE has been deprecated, use CREATE TABLE instead")
1975        } else if self.parse_keyword(Keyword::SOURCE) {
1976            self.parse_create_source(or_replace, temporary)
1977        } else if self.parse_keyword(Keyword::SINK) {
1978            self.parse_create_sink(or_replace)
1979        } else if self.parse_keyword(Keyword::SUBSCRIPTION) {
1980            self.parse_create_subscription(or_replace)
1981        } else if self.parse_keyword(Keyword::CONNECTION) {
1982            self.parse_create_connection()
1983        } else if self.parse_keyword(Keyword::FUNCTION) {
1984            self.parse_create_function(or_replace, temporary)
1985        } else if self.parse_keyword(Keyword::AGGREGATE) {
1986            self.parse_create_aggregate(or_replace)
1987        } else if or_replace {
1988            self.expected(
1989                "[EXTERNAL] TABLE or [MATERIALIZED] VIEW or [MATERIALIZED] SOURCE or SINK or FUNCTION after CREATE OR REPLACE",
1990            )
1991        } else if self.parse_keyword(Keyword::INDEX) {
1992            self.parse_create_index(false)
1993        } else if self.parse_keywords(&[Keyword::UNIQUE, Keyword::INDEX]) {
1994            self.parse_create_index(true)
1995        } else if self.parse_keyword(Keyword::SCHEMA) {
1996            self.parse_create_schema()
1997        } else if self.parse_keyword(Keyword::DATABASE) {
1998            self.parse_create_database()
1999        } else if self.parse_keyword(Keyword::USER) {
2000            self.parse_create_user()
2001        } else if self.parse_keyword(Keyword::SECRET) {
2002            self.parse_create_secret()
2003        } else {
2004            self.expected("an object type after CREATE")
2005        }
2006    }
2007
2008    pub fn parse_create_schema(&mut self) -> ModalResult<Statement> {
2009        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
2010        let (schema_name, owner) = if self.parse_keyword(Keyword::AUTHORIZATION) {
2011            let owner = self.parse_object_name()?;
2012            (owner.clone(), Some(owner))
2013        } else {
2014            let schema_name = self.parse_object_name()?;
2015            let owner = if self.parse_keyword(Keyword::AUTHORIZATION) {
2016                Some(self.parse_object_name()?)
2017            } else {
2018                None
2019            };
2020            (schema_name, owner)
2021        };
2022        Ok(Statement::CreateSchema {
2023            schema_name,
2024            if_not_exists,
2025            owner,
2026        })
2027    }
2028
2029    pub fn parse_create_database(&mut self) -> ModalResult<Statement> {
2030        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
2031        let db_name = self.parse_object_name()?;
2032        let _ = self.parse_keyword(Keyword::WITH);
2033
2034        let mut owner = None;
2035        let mut resource_group = None;
2036        let mut barrier_interval_ms = None;
2037        let mut checkpoint_frequency = None;
2038
2039        loop {
2040            if let Some(keyword) =
2041                self.parse_one_of_keywords(&[Keyword::OWNER, Keyword::RESOURCE_GROUP])
2042            {
2043                match keyword {
2044                    Keyword::OWNER => {
2045                        if owner.is_some() {
2046                            parser_err!("duplicate OWNER clause in CREATE DATABASE");
2047                        }
2048
2049                        let _ = self.consume_token(&Token::Eq);
2050                        owner = Some(self.parse_object_name()?);
2051                    }
2052                    Keyword::RESOURCE_GROUP => {
2053                        if resource_group.is_some() {
2054                            parser_err!("duplicate RESOURCE_GROUP clause in CREATE DATABASE");
2055                        }
2056
2057                        let _ = self.consume_token(&Token::Eq);
2058                        resource_group = Some(self.parse_set_variable()?);
2059                    }
2060                    _ => unreachable!(),
2061                }
2062            } else if self.parse_word("BARRIER_INTERVAL_MS") {
2063                if barrier_interval_ms.is_some() {
2064                    parser_err!("duplicate BARRIER_INTERVAL_MS clause in CREATE DATABASE");
2065                }
2066
2067                let _ = self.consume_token(&Token::Eq);
2068                barrier_interval_ms = Some(self.parse_literal_u32()?);
2069            } else if self.parse_word("CHECKPOINT_FREQUENCY") {
2070                if checkpoint_frequency.is_some() {
2071                    parser_err!("duplicate CHECKPOINT_FREQUENCY clause in CREATE DATABASE");
2072                }
2073
2074                let _ = self.consume_token(&Token::Eq);
2075                checkpoint_frequency = Some(self.parse_literal_u64()?);
2076            } else {
2077                break;
2078            }
2079        }
2080
2081        Ok(Statement::CreateDatabase {
2082            db_name,
2083            if_not_exists,
2084            owner,
2085            resource_group,
2086            barrier_interval_ms,
2087            checkpoint_frequency,
2088        })
2089    }
2090
2091    pub fn parse_create_view(
2092        &mut self,
2093        materialized: bool,
2094        or_replace: bool,
2095    ) -> ModalResult<Statement> {
2096        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
2097        // Many dialects support `OR ALTER` right after `CREATE`, but we don't (yet).
2098        // ANSI SQL and Postgres support RECURSIVE here, but we don't support it either.
2099        let name = self.parse_object_name()?;
2100        let columns = self.parse_parenthesized_column_list(Optional)?;
2101        let with_options = self.parse_options_with_preceding_keyword(Keyword::WITH)?;
2102        self.expect_keyword(Keyword::AS)?;
2103        let query = Box::new(self.parse_query()?);
2104        let emit_mode = if materialized {
2105            self.parse_emit_mode()?
2106        } else {
2107            None
2108        };
2109        // Optional `WITH [ CASCADED | LOCAL ] CHECK OPTION` is widely supported here.
2110        Ok(Statement::CreateView {
2111            if_not_exists,
2112            name,
2113            columns,
2114            query,
2115            materialized,
2116            or_replace,
2117            with_options,
2118            emit_mode,
2119        })
2120    }
2121
2122    // CREATE [OR REPLACE]?
2123    // [TEMPORARY] SOURCE
2124    // [IF NOT EXISTS]?
2125    // <source_name: Ident>
2126    // [COLUMNS]?
2127    // [WITH (properties)]?
2128    // ROW FORMAT <row_format: Ident>
2129    // [ROW SCHEMA LOCATION <row_schema_location: String>]?
2130    pub fn parse_create_source(
2131        &mut self,
2132        _or_replace: bool,
2133        temporary: bool,
2134    ) -> ModalResult<Statement> {
2135        impl_parse_to!(if_not_exists => [Keyword::IF, Keyword::NOT, Keyword::EXISTS], self);
2136        impl_parse_to!(source_name: ObjectName, self);
2137
2138        // parse columns
2139        let (columns, constraints, source_watermarks, wildcard_idx) =
2140            self.parse_columns_with_watermark()?;
2141        let include_options = self.parse_include_options()?;
2142
2143        let with_options = self.parse_with_properties()?;
2144        let option = with_options
2145            .iter()
2146            .find(|&opt| opt.name.real_value() == UPSTREAM_SOURCE_KEY);
2147        let connector: String = option.map(|opt| opt.value.to_string()).unwrap_or_default();
2148        let cdc_source_job = connector.contains("-cdc");
2149        if cdc_source_job && (!columns.is_empty() || !constraints.is_empty()) {
2150            parser_err!("CDC source cannot define columns and constraints");
2151        }
2152
2153        // row format for nexmark source must be native
2154        // default row format for datagen source is native
2155        let format_encode = self.parse_format_encode_with_connector(&connector, cdc_source_job)?;
2156
2157        let stmt = CreateSourceStatement {
2158            temporary,
2159            if_not_exists,
2160            columns,
2161            wildcard_idx,
2162            constraints,
2163            source_name,
2164            with_properties: WithProperties(with_options),
2165            format_encode,
2166            source_watermarks,
2167            include_column_options: include_options,
2168        };
2169
2170        Ok(Statement::CreateSource { stmt })
2171    }
2172
2173    // CREATE [OR REPLACE]?
2174    // SINK
2175    // [IF NOT EXISTS]?
2176    // <sink_name: Ident>
2177    // FROM
2178    // <materialized_view: Ident>
2179    // [WITH (properties)]?
2180    pub fn parse_create_sink(&mut self, _or_replace: bool) -> ModalResult<Statement> {
2181        Ok(Statement::CreateSink {
2182            stmt: CreateSinkStatement::parse_to(self)?,
2183        })
2184    }
2185
2186    // CREATE
2187    // SUBSCRIPTION
2188    // [IF NOT EXISTS]?
2189    // <subscription_name: Ident>
2190    // FROM
2191    // <materialized_view: Ident>
2192    // [WITH (properties)]?
2193    pub fn parse_create_subscription(&mut self, _or_replace: bool) -> ModalResult<Statement> {
2194        Ok(Statement::CreateSubscription {
2195            stmt: CreateSubscriptionStatement::parse_to(self)?,
2196        })
2197    }
2198
2199    // CREATE
2200    // CONNECTION
2201    // [IF NOT EXISTS]?
2202    // <connection_name: Ident>
2203    // [WITH (properties)]?
2204    pub fn parse_create_connection(&mut self) -> ModalResult<Statement> {
2205        Ok(Statement::CreateConnection {
2206            stmt: CreateConnectionStatement::parse_to(self)?,
2207        })
2208    }
2209
2210    pub fn parse_create_function(
2211        &mut self,
2212        or_replace: bool,
2213        temporary: bool,
2214    ) -> ModalResult<Statement> {
2215        impl_parse_to!(if_not_exists => [Keyword::IF, Keyword::NOT, Keyword::EXISTS], self);
2216
2217        let FunctionDesc { name, args } = self.parse_function_desc()?;
2218
2219        let return_type = if self.parse_keyword(Keyword::RETURNS) {
2220            if self.parse_keyword(Keyword::TABLE) {
2221                self.expect_token(&Token::LParen)?;
2222                let mut values = vec![];
2223                loop {
2224                    values.push(self.parse_table_column_def()?);
2225                    let comma = self.consume_token(&Token::Comma);
2226                    if self.consume_token(&Token::RParen) {
2227                        // allow a trailing comma, even though it's not in standard
2228                        break;
2229                    } else if !comma {
2230                        return self.expected("',' or ')'");
2231                    }
2232                }
2233                Some(CreateFunctionReturns::Table(values))
2234            } else {
2235                Some(CreateFunctionReturns::Value(self.parse_data_type()?))
2236            }
2237        } else {
2238            None
2239        };
2240
2241        let params = self.parse_create_function_body()?;
2242        let with_options = self.parse_options_with_preceding_keyword(Keyword::WITH)?;
2243        let with_options = with_options.try_into()?;
2244        Ok(Statement::CreateFunction {
2245            or_replace,
2246            temporary,
2247            if_not_exists,
2248            name,
2249            args,
2250            returns: return_type,
2251            params,
2252            with_options,
2253        })
2254    }
2255
2256    fn parse_create_aggregate(&mut self, or_replace: bool) -> ModalResult<Statement> {
2257        impl_parse_to!(if_not_exists => [Keyword::IF, Keyword::NOT, Keyword::EXISTS], self);
2258
2259        let name = self.parse_object_name()?;
2260        self.expect_token(&Token::LParen)?;
2261        let args = self.parse_comma_separated(Parser::parse_function_arg)?;
2262        self.expect_token(&Token::RParen)?;
2263
2264        self.expect_keyword(Keyword::RETURNS)?;
2265        let returns = self.parse_data_type()?;
2266
2267        let append_only = self.parse_keywords(&[Keyword::APPEND, Keyword::ONLY]);
2268        let params = self.parse_create_function_body()?;
2269
2270        Ok(Statement::CreateAggregate {
2271            or_replace,
2272            if_not_exists,
2273            name,
2274            args,
2275            returns,
2276            append_only,
2277            params,
2278        })
2279    }
2280
2281    pub fn parse_declare(&mut self) -> ModalResult<Statement> {
2282        Ok(Statement::DeclareCursor {
2283            stmt: DeclareCursorStatement::parse_to(self)?,
2284        })
2285    }
2286
2287    pub fn parse_fetch_cursor(&mut self) -> ModalResult<Statement> {
2288        Ok(Statement::FetchCursor {
2289            stmt: FetchCursorStatement::parse_to(self)?,
2290        })
2291    }
2292
2293    pub fn parse_close_cursor(&mut self) -> ModalResult<Statement> {
2294        Ok(Statement::CloseCursor {
2295            stmt: CloseCursorStatement::parse_to(self)?,
2296        })
2297    }
2298
2299    fn parse_table_column_def(&mut self) -> ModalResult<TableColumnDef> {
2300        Ok(TableColumnDef {
2301            name: self.parse_identifier_non_reserved()?,
2302            data_type: self.parse_data_type()?,
2303        })
2304    }
2305
2306    fn parse_function_arg(&mut self) -> ModalResult<OperateFunctionArg> {
2307        let mode = if self.parse_keyword(Keyword::IN) {
2308            Some(ArgMode::In)
2309        } else if self.parse_keyword(Keyword::OUT) {
2310            Some(ArgMode::Out)
2311        } else if self.parse_keyword(Keyword::INOUT) {
2312            Some(ArgMode::InOut)
2313        } else {
2314            None
2315        };
2316
2317        // parse: [ argname ] argtype
2318        let mut name = None;
2319        let mut data_type = self.parse_data_type()?;
2320        if let DataType::Custom(n) = &data_type
2321            && !matches!(self.peek_token().token, Token::Comma | Token::RParen)
2322        {
2323            // the first token is actually a name
2324            name = Some(n.0[0].clone());
2325            data_type = self.parse_data_type()?;
2326        }
2327
2328        let default_expr = if self.parse_keyword(Keyword::DEFAULT) || self.consume_token(&Token::Eq)
2329        {
2330            Some(self.parse_expr()?)
2331        } else {
2332            None
2333        };
2334        Ok(OperateFunctionArg {
2335            mode,
2336            name,
2337            data_type,
2338            default_expr,
2339        })
2340    }
2341
2342    fn parse_create_function_body(&mut self) -> ModalResult<CreateFunctionBody> {
2343        let mut body = CreateFunctionBody::default();
2344        loop {
2345            fn ensure_not_set<T>(field: &Option<T>, name: &str) -> ModalResult<()> {
2346                if field.is_some() {
2347                    parser_err!("{name} specified more than once");
2348                }
2349                Ok(())
2350            }
2351            if self.parse_keyword(Keyword::AS) {
2352                ensure_not_set(&body.as_, "AS")?;
2353                body.as_ = Some(self.parse_function_definition()?);
2354            } else if self.parse_keyword(Keyword::LANGUAGE) {
2355                ensure_not_set(&body.language, "LANGUAGE")?;
2356                body.language = Some(self.parse_identifier()?);
2357            } else if self.parse_keyword(Keyword::RUNTIME) {
2358                ensure_not_set(&body.runtime, "RUNTIME")?;
2359                body.runtime = Some(self.parse_identifier()?);
2360            } else if self.parse_keyword(Keyword::IMMUTABLE) {
2361                ensure_not_set(&body.behavior, "IMMUTABLE | STABLE | VOLATILE")?;
2362                body.behavior = Some(FunctionBehavior::Immutable);
2363            } else if self.parse_keyword(Keyword::STABLE) {
2364                ensure_not_set(&body.behavior, "IMMUTABLE | STABLE | VOLATILE")?;
2365                body.behavior = Some(FunctionBehavior::Stable);
2366            } else if self.parse_keyword(Keyword::VOLATILE) {
2367                ensure_not_set(&body.behavior, "IMMUTABLE | STABLE | VOLATILE")?;
2368                body.behavior = Some(FunctionBehavior::Volatile);
2369            } else if self.parse_keyword(Keyword::RETURN) {
2370                ensure_not_set(&body.return_, "RETURN")?;
2371                body.return_ = Some(self.parse_expr()?);
2372            } else if self.parse_keyword(Keyword::USING) {
2373                ensure_not_set(&body.using, "USING")?;
2374                body.using = Some(self.parse_create_function_using()?);
2375            } else {
2376                return Ok(body);
2377            }
2378        }
2379    }
2380
2381    fn parse_create_function_using(&mut self) -> ModalResult<CreateFunctionUsing> {
2382        let keyword = self.expect_one_of_keywords(&[Keyword::LINK, Keyword::BASE64])?;
2383
2384        match keyword {
2385            Keyword::LINK => {
2386                let uri = self.parse_literal_string()?;
2387                Ok(CreateFunctionUsing::Link(uri))
2388            }
2389            Keyword::BASE64 => {
2390                let base64 = self.parse_literal_string()?;
2391                Ok(CreateFunctionUsing::Base64(base64))
2392            }
2393            _ => unreachable!("{}", keyword),
2394        }
2395    }
2396
2397    // CREATE USER name [ [ WITH ] option [ ... ] ]
2398    // where option can be:
2399    //       SUPERUSER | NOSUPERUSER
2400    //     | CREATEDB | NOCREATEDB
2401    //     | CREATEUSER | NOCREATEUSER
2402    //     | LOGIN | NOLOGIN
2403    //     | [ ENCRYPTED ] PASSWORD 'password' | PASSWORD NULL | OAUTH
2404    fn parse_create_user(&mut self) -> ModalResult<Statement> {
2405        Ok(Statement::CreateUser(CreateUserStatement::parse_to(self)?))
2406    }
2407
2408    fn parse_create_secret(&mut self) -> ModalResult<Statement> {
2409        Ok(Statement::CreateSecret {
2410            stmt: CreateSecretStatement::parse_to(self)?,
2411        })
2412    }
2413
2414    pub fn parse_with_properties(&mut self) -> ModalResult<Vec<SqlOption>> {
2415        Ok(self
2416            .parse_options_with_preceding_keyword(Keyword::WITH)?
2417            .to_vec())
2418    }
2419
2420    pub fn parse_discard(&mut self) -> ModalResult<Statement> {
2421        self.expect_keyword(Keyword::ALL)?;
2422        Ok(Statement::Discard(DiscardType::All))
2423    }
2424
2425    pub fn parse_drop(&mut self) -> ModalResult<Statement> {
2426        if self.parse_keyword(Keyword::FUNCTION) {
2427            return self.parse_drop_function();
2428        } else if self.parse_keyword(Keyword::AGGREGATE) {
2429            return self.parse_drop_aggregate();
2430        }
2431        Ok(Statement::Drop(DropStatement::parse_to(self)?))
2432    }
2433
2434    /// ```sql
2435    /// DROP FUNCTION [ IF EXISTS ] name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ] [, ...]
2436    /// [ CASCADE | RESTRICT ]
2437    /// ```
2438    fn parse_drop_function(&mut self) -> ModalResult<Statement> {
2439        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
2440        let func_desc = self.parse_comma_separated(Parser::parse_function_desc)?;
2441        let option = match self.parse_one_of_keywords(&[Keyword::CASCADE, Keyword::RESTRICT]) {
2442            Some(Keyword::CASCADE) => Some(ReferentialAction::Cascade),
2443            Some(Keyword::RESTRICT) => Some(ReferentialAction::Restrict),
2444            _ => None,
2445        };
2446        Ok(Statement::DropFunction {
2447            if_exists,
2448            func_desc,
2449            option,
2450        })
2451    }
2452
2453    /// ```sql
2454    /// DROP AGGREGATE [ IF EXISTS ] name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ] [, ...]
2455    /// [ CASCADE | RESTRICT ]
2456    /// ```
2457    fn parse_drop_aggregate(&mut self) -> ModalResult<Statement> {
2458        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
2459        let func_desc = self.parse_comma_separated(Parser::parse_function_desc)?;
2460        let option = match self.parse_one_of_keywords(&[Keyword::CASCADE, Keyword::RESTRICT]) {
2461            Some(Keyword::CASCADE) => Some(ReferentialAction::Cascade),
2462            Some(Keyword::RESTRICT) => Some(ReferentialAction::Restrict),
2463            _ => None,
2464        };
2465        Ok(Statement::DropAggregate {
2466            if_exists,
2467            func_desc,
2468            option,
2469        })
2470    }
2471
2472    fn parse_function_desc(&mut self) -> ModalResult<FunctionDesc> {
2473        let name = self.parse_object_name()?;
2474
2475        let args = if self.consume_token(&Token::LParen) {
2476            if self.consume_token(&Token::RParen) {
2477                Some(vec![])
2478            } else {
2479                let args = self.parse_comma_separated(Parser::parse_function_arg)?;
2480                self.expect_token(&Token::RParen)?;
2481                Some(args)
2482            }
2483        } else {
2484            None
2485        };
2486
2487        Ok(FunctionDesc { name, args })
2488    }
2489
2490    pub fn parse_create_index(&mut self, unique: bool) -> ModalResult<Statement> {
2491        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
2492        let index_name = self.parse_object_name()?;
2493        self.expect_keyword(Keyword::ON)?;
2494        let table_name = self.parse_object_name()?;
2495        self.expect_token(&Token::LParen)?;
2496        let columns = self.parse_comma_separated(Parser::parse_order_by_expr)?;
2497        self.expect_token(&Token::RParen)?;
2498        let mut include = vec![];
2499        if self.parse_keyword(Keyword::INCLUDE) {
2500            self.expect_token(&Token::LParen)?;
2501            include = self.parse_comma_separated(Parser::parse_identifier_non_reserved)?;
2502            self.expect_token(&Token::RParen)?;
2503        }
2504        let mut distributed_by = vec![];
2505        if self.parse_keywords(&[Keyword::DISTRIBUTED, Keyword::BY]) {
2506            self.expect_token(&Token::LParen)?;
2507            distributed_by = self.parse_comma_separated(Parser::parse_expr)?;
2508            self.expect_token(&Token::RParen)?;
2509        }
2510        Ok(Statement::CreateIndex {
2511            name: index_name,
2512            table_name,
2513            columns,
2514            include,
2515            distributed_by,
2516            unique,
2517            if_not_exists,
2518        })
2519    }
2520
2521    pub fn parse_with_version_column(&mut self) -> ModalResult<Option<Ident>> {
2522        if self.parse_keywords(&[Keyword::WITH, Keyword::VERSION, Keyword::COLUMN]) {
2523            self.expect_token(&Token::LParen)?;
2524            let name = self.parse_identifier_non_reserved()?;
2525            self.expect_token(&Token::RParen)?;
2526            Ok(Some(name))
2527        } else {
2528            Ok(None)
2529        }
2530    }
2531
2532    pub fn parse_on_conflict(&mut self) -> ModalResult<Option<OnConflict>> {
2533        if self.parse_keywords(&[Keyword::ON, Keyword::CONFLICT]) {
2534            self.parse_handle_conflict_behavior()
2535        } else {
2536            Ok(None)
2537        }
2538    }
2539
2540    pub fn parse_create_table(
2541        &mut self,
2542        or_replace: bool,
2543        temporary: bool,
2544    ) -> ModalResult<Statement> {
2545        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
2546        let table_name = self.parse_object_name()?;
2547        // parse optional column list (schema) and watermarks on source.
2548        let (columns, constraints, source_watermarks, wildcard_idx) =
2549            self.parse_columns_with_watermark()?;
2550
2551        let append_only = if self.parse_keyword(Keyword::APPEND) {
2552            self.expect_keyword(Keyword::ONLY)?;
2553            true
2554        } else {
2555            false
2556        };
2557
2558        let on_conflict = self.parse_on_conflict()?;
2559
2560        let with_version_column = self.parse_with_version_column()?;
2561        let include_options = self.parse_include_options()?;
2562
2563        // PostgreSQL supports `WITH ( options )`, before `AS`
2564        let with_options = self.parse_with_properties()?;
2565
2566        let option = with_options
2567            .iter()
2568            .find(|&opt| opt.name.real_value() == UPSTREAM_SOURCE_KEY);
2569        let connector = option.map(|opt| opt.value.to_string());
2570        let contain_webhook =
2571            connector.is_some() && connector.as_ref().unwrap().contains(WEBHOOK_CONNECTOR);
2572
2573        // webhook connector does not require row format
2574        let format_encode = if let Some(connector) = connector
2575            && !contain_webhook
2576        {
2577            Some(self.parse_format_encode_with_connector(&connector, false)?)
2578        } else {
2579            None // Table is NOT created with an external connector.
2580        };
2581        // Parse optional `AS ( query )`
2582        let query = if self.parse_keyword(Keyword::AS) {
2583            if !source_watermarks.is_empty() {
2584                parser_err!("Watermarks can't be defined on table created by CREATE TABLE AS");
2585            }
2586            Some(Box::new(self.parse_query()?))
2587        } else {
2588            None
2589        };
2590
2591        let cdc_table_info = if self.parse_keyword(Keyword::FROM) {
2592            let source_name = self.parse_object_name()?;
2593            self.expect_keyword(Keyword::TABLE)?;
2594            let external_table_name = self.parse_literal_string()?;
2595            Some(CdcTableInfo {
2596                source_name,
2597                external_table_name,
2598            })
2599        } else {
2600            None
2601        };
2602
2603        let webhook_info = if self.parse_keyword(Keyword::VALIDATE) {
2604            if !contain_webhook {
2605                parser_err!("VALIDATE is only supported for tables created with webhook source");
2606            }
2607
2608            let wait_for_persistence = with_options
2609                .iter()
2610                .find(|&opt| opt.name.real_value() == WEBHOOK_WAIT_FOR_PERSISTENCE)
2611                .map(|opt| opt.value.to_string().eq_ignore_ascii_case("true"))
2612                .unwrap_or(true);
2613            let secret_ref = if self.parse_keyword(Keyword::SECRET) {
2614                let secret_ref = self.parse_secret_ref()?;
2615                if secret_ref.ref_as == SecretRefAsType::File {
2616                    parser_err!("Secret for SECURE_COMPARE() does not support AS FILE");
2617                };
2618                Some(secret_ref)
2619            } else {
2620                None
2621            };
2622
2623            self.expect_keyword(Keyword::AS)?;
2624            let signature_expr = self.parse_function()?;
2625
2626            let is_batched = with_options
2627                .iter()
2628                .find(|&opt| opt.name.real_value() == WEBHOOK_IS_BATCHED)
2629                .map(|opt| opt.value.to_string().eq_ignore_ascii_case("true"))
2630                .unwrap_or(false);
2631
2632            Some(WebhookSourceInfo {
2633                secret_ref,
2634                signature_expr,
2635                wait_for_persistence,
2636                is_batched,
2637            })
2638        } else {
2639            None
2640        };
2641
2642        let engine = if self.parse_keyword(Keyword::ENGINE) {
2643            self.expect_token(&Token::Eq)?;
2644            let engine_name = self.parse_object_name()?;
2645            if "iceberg".eq_ignore_ascii_case(&engine_name.real_value()) {
2646                Engine::Iceberg
2647            } else if "hummock".eq_ignore_ascii_case(&engine_name.real_value()) {
2648                Engine::Hummock
2649            } else {
2650                parser_err!("Unsupported engine: {}", engine_name);
2651            }
2652        } else {
2653            Engine::Hummock
2654        };
2655
2656        Ok(Statement::CreateTable {
2657            name: table_name,
2658            temporary,
2659            columns,
2660            wildcard_idx,
2661            constraints,
2662            with_options,
2663            or_replace,
2664            if_not_exists,
2665            format_encode,
2666            source_watermarks,
2667            append_only,
2668            on_conflict,
2669            with_version_column,
2670            query,
2671            cdc_table_info,
2672            include_column_options: include_options,
2673            webhook_info,
2674            engine,
2675        })
2676    }
2677
2678    pub fn parse_include_options(&mut self) -> ModalResult<IncludeOption> {
2679        let mut options = vec![];
2680        while self.parse_keyword(Keyword::INCLUDE) {
2681            let column_type = self.parse_identifier()?;
2682
2683            let mut column_inner_field = None;
2684            let mut header_inner_expect_type = None;
2685            if let Token::SingleQuotedString(inner_field) = self.peek_token().token {
2686                self.next_token();
2687                column_inner_field = Some(inner_field);
2688
2689                // `verify` rejects `DataType::Custom` so that a following `INCLUDE` (or even `WITH`)
2690                // will not be misrecognized as a DataType.
2691                //
2692                // For example, the following look structurally the same because `INCLUDE` is not a
2693                // reserved keyword. (`AS` is reserved.)
2694                // * `INCLUDE header 'foo' varchar`
2695                // * `INCLUDE header 'foo' INCLUDE`
2696                //
2697                // To be honest `bytea` shall be a `DataType::Custom` rather than a keyword, and the
2698                // logic here shall be:
2699                // ```
2700                // match dt {
2701                //     DataType::Custom(name) => allowed.contains(name.real_value()),
2702                //     _ => true,
2703                // }
2704                // ```
2705                // An allowlist is better than a denylist, as the following token may be other than
2706                // `INCLUDE` or `WITH` in the future.
2707                //
2708                // If this sounds too complicated - it means we should have designed this extension
2709                // syntax differently to make ambiguity handling easier.
2710                header_inner_expect_type =
2711                    opt(parser_v2::data_type.verify(|dt| !matches!(dt, DataType::Custom(_))))
2712                        .parse_next(self)?;
2713            }
2714
2715            let mut column_alias = None;
2716            if self.parse_keyword(Keyword::AS) {
2717                column_alias = Some(self.parse_identifier()?);
2718            }
2719
2720            options.push(IncludeOptionItem {
2721                column_type,
2722                inner_field: column_inner_field,
2723                column_alias,
2724                header_inner_expect_type,
2725            });
2726
2727            // tolerate previous bug #18800 of displaying with comma separation
2728            let _ = self.consume_token(&Token::Comma);
2729        }
2730        Ok(options)
2731    }
2732
2733    pub fn parse_columns_with_watermark(&mut self) -> ModalResult<ColumnsDefTuple> {
2734        let mut columns = vec![];
2735        let mut constraints = vec![];
2736        let mut watermarks = vec![];
2737        let mut wildcard_idx = None;
2738        if !self.consume_token(&Token::LParen) || self.consume_token(&Token::RParen) {
2739            return Ok((columns, constraints, watermarks, wildcard_idx));
2740        }
2741
2742        loop {
2743            if self.consume_token(&Token::Mul) {
2744                if wildcard_idx.is_none() {
2745                    wildcard_idx = Some(columns.len());
2746                } else {
2747                    parser_err!("At most 1 wildcard is allowed in source definetion");
2748                }
2749            } else if let Some(constraint) = self.parse_optional_table_constraint()? {
2750                constraints.push(constraint);
2751            } else if let Some(watermark) = self.parse_optional_watermark()? {
2752                watermarks.push(watermark);
2753                if watermarks.len() > 1 {
2754                    // TODO(yuhao): allow multiple watermark on source.
2755                    parser_err!("Only 1 watermark is allowed to be defined on source.");
2756                }
2757            } else if let Token::Word(_) = self.peek_token().token {
2758                columns.push(self.parse_column_def()?);
2759            } else {
2760                return self.expected("column name or constraint definition");
2761            }
2762            let comma = self.consume_token(&Token::Comma);
2763            if self.consume_token(&Token::RParen) {
2764                // allow a trailing comma, even though it's not in standard
2765                break;
2766            } else if !comma {
2767                return self.expected("',' or ')' after column definition");
2768            }
2769        }
2770
2771        Ok((columns, constraints, watermarks, wildcard_idx))
2772    }
2773
2774    fn parse_column_def(&mut self) -> ModalResult<ColumnDef> {
2775        let name = self.parse_identifier_non_reserved()?;
2776        let data_type = if let Token::Word(_) = self.peek_token().token {
2777            Some(self.parse_data_type()?)
2778        } else {
2779            None
2780        };
2781
2782        let collation = if self.parse_keyword(Keyword::COLLATE) {
2783            Some(self.parse_object_name()?)
2784        } else {
2785            None
2786        };
2787        let mut options = vec![];
2788        loop {
2789            if self.parse_keyword(Keyword::CONSTRAINT) {
2790                let name = Some(self.parse_identifier_non_reserved()?);
2791                if let Some(option) = self.parse_optional_column_option()? {
2792                    options.push(ColumnOptionDef { name, option });
2793                } else {
2794                    return self.expected("constraint details after CONSTRAINT <name>");
2795                }
2796            } else if let Some(option) = self.parse_optional_column_option()? {
2797                options.push(ColumnOptionDef { name: None, option });
2798            } else {
2799                break;
2800            };
2801        }
2802        Ok(ColumnDef {
2803            name,
2804            data_type,
2805            collation,
2806            options,
2807        })
2808    }
2809
2810    pub fn parse_optional_column_option(&mut self) -> ModalResult<Option<ColumnOption>> {
2811        if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) {
2812            Ok(Some(ColumnOption::NotNull))
2813        } else if self.parse_keyword(Keyword::NULL) {
2814            Ok(Some(ColumnOption::Null))
2815        } else if self.parse_keyword(Keyword::DEFAULT) {
2816            if self.parse_keyword(Keyword::INTERNAL) {
2817                Ok(Some(ColumnOption::DefaultValueInternal {
2818                    // Placeholder. Will fill during definition purification for schema change.
2819                    persisted: Default::default(),
2820                    expr: None,
2821                }))
2822            } else {
2823                Ok(Some(ColumnOption::DefaultValue(self.parse_expr()?)))
2824            }
2825        } else if self.parse_keywords(&[Keyword::PRIMARY, Keyword::KEY]) {
2826            Ok(Some(ColumnOption::Unique { is_primary: true }))
2827        } else if self.parse_keyword(Keyword::UNIQUE) {
2828            Ok(Some(ColumnOption::Unique { is_primary: false }))
2829        } else if self.parse_keyword(Keyword::REFERENCES) {
2830            let foreign_table = self.parse_object_name()?;
2831            // PostgreSQL allows omitting the column list and
2832            // uses the primary key column of the foreign table by default
2833            let referred_columns = self.parse_parenthesized_column_list(Optional)?;
2834            let mut on_delete = None;
2835            let mut on_update = None;
2836            loop {
2837                if on_delete.is_none() && self.parse_keywords(&[Keyword::ON, Keyword::DELETE]) {
2838                    on_delete = Some(self.parse_referential_action()?);
2839                } else if on_update.is_none()
2840                    && self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
2841                {
2842                    on_update = Some(self.parse_referential_action()?);
2843                } else {
2844                    break;
2845                }
2846            }
2847            Ok(Some(ColumnOption::ForeignKey {
2848                foreign_table,
2849                referred_columns,
2850                on_delete,
2851                on_update,
2852            }))
2853        } else if self.parse_keyword(Keyword::CHECK) {
2854            self.expect_token(&Token::LParen)?;
2855            let expr = self.parse_expr()?;
2856            self.expect_token(&Token::RParen)?;
2857            Ok(Some(ColumnOption::Check(expr)))
2858        } else if self.parse_keyword(Keyword::AS) {
2859            Ok(Some(ColumnOption::GeneratedColumns(self.parse_expr()?)))
2860        } else {
2861            Ok(None)
2862        }
2863    }
2864
2865    pub fn parse_handle_conflict_behavior(&mut self) -> ModalResult<Option<OnConflict>> {
2866        if self.parse_keyword(Keyword::OVERWRITE) {
2867            // compatible with v1.9 - v2.0
2868            Ok(Some(OnConflict::UpdateFull))
2869        } else if self.parse_keyword(Keyword::IGNORE) {
2870            // compatible with v1.9 - v2.0
2871            Ok(Some(OnConflict::Nothing))
2872        } else if self.parse_keywords(&[
2873            Keyword::DO,
2874            Keyword::UPDATE,
2875            Keyword::IF,
2876            Keyword::NOT,
2877            Keyword::NULL,
2878        ]) {
2879            Ok(Some(OnConflict::UpdateIfNotNull))
2880        } else if self.parse_keywords(&[Keyword::DO, Keyword::UPDATE, Keyword::FULL]) {
2881            Ok(Some(OnConflict::UpdateFull))
2882        } else if self.parse_keywords(&[Keyword::DO, Keyword::NOTHING]) {
2883            Ok(Some(OnConflict::Nothing))
2884        } else {
2885            Ok(None)
2886        }
2887    }
2888
2889    pub fn parse_referential_action(&mut self) -> ModalResult<ReferentialAction> {
2890        if self.parse_keyword(Keyword::RESTRICT) {
2891            Ok(ReferentialAction::Restrict)
2892        } else if self.parse_keyword(Keyword::CASCADE) {
2893            Ok(ReferentialAction::Cascade)
2894        } else if self.parse_keywords(&[Keyword::SET, Keyword::NULL]) {
2895            Ok(ReferentialAction::SetNull)
2896        } else if self.parse_keywords(&[Keyword::NO, Keyword::ACTION]) {
2897            Ok(ReferentialAction::NoAction)
2898        } else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
2899            Ok(ReferentialAction::SetDefault)
2900        } else {
2901            self.expected("one of RESTRICT, CASCADE, SET NULL, NO ACTION or SET DEFAULT")
2902        }
2903    }
2904
2905    pub fn parse_optional_watermark(&mut self) -> ModalResult<Option<SourceWatermark>> {
2906        if self.parse_keyword(Keyword::WATERMARK) {
2907            self.expect_keyword(Keyword::FOR)?;
2908            let column = self.parse_identifier_non_reserved()?;
2909            self.expect_keyword(Keyword::AS)?;
2910            let expr = self.parse_expr()?;
2911            Ok(Some(SourceWatermark { column, expr }))
2912        } else {
2913            Ok(None)
2914        }
2915    }
2916
2917    pub fn parse_optional_table_constraint(&mut self) -> ModalResult<Option<TableConstraint>> {
2918        let name = if self.parse_keyword(Keyword::CONSTRAINT) {
2919            Some(self.parse_identifier_non_reserved()?)
2920        } else {
2921            None
2922        };
2923        let checkpoint = *self;
2924        let token = self.next_token();
2925        match token.token {
2926            Token::Word(w) if w.keyword == Keyword::PRIMARY || w.keyword == Keyword::UNIQUE => {
2927                let is_primary = w.keyword == Keyword::PRIMARY;
2928                if is_primary {
2929                    self.expect_keyword(Keyword::KEY)?;
2930                }
2931                let columns = self.parse_parenthesized_column_list(Mandatory)?;
2932                Ok(Some(TableConstraint::Unique {
2933                    name,
2934                    columns,
2935                    is_primary,
2936                }))
2937            }
2938            Token::Word(w) if w.keyword == Keyword::FOREIGN => {
2939                self.expect_keyword(Keyword::KEY)?;
2940                let columns = self.parse_parenthesized_column_list(Mandatory)?;
2941                self.expect_keyword(Keyword::REFERENCES)?;
2942                let foreign_table = self.parse_object_name()?;
2943                let referred_columns = self.parse_parenthesized_column_list(Mandatory)?;
2944                let mut on_delete = None;
2945                let mut on_update = None;
2946                loop {
2947                    if on_delete.is_none() && self.parse_keywords(&[Keyword::ON, Keyword::DELETE]) {
2948                        on_delete = Some(self.parse_referential_action()?);
2949                    } else if on_update.is_none()
2950                        && self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
2951                    {
2952                        on_update = Some(self.parse_referential_action()?);
2953                    } else {
2954                        break;
2955                    }
2956                }
2957                Ok(Some(TableConstraint::ForeignKey {
2958                    name,
2959                    columns,
2960                    foreign_table,
2961                    referred_columns,
2962                    on_delete,
2963                    on_update,
2964                }))
2965            }
2966            Token::Word(w) if w.keyword == Keyword::CHECK => {
2967                self.expect_token(&Token::LParen)?;
2968                let expr = Box::new(self.parse_expr()?);
2969                self.expect_token(&Token::RParen)?;
2970                Ok(Some(TableConstraint::Check { name, expr }))
2971            }
2972            _ => {
2973                *self = checkpoint;
2974                if name.is_some() {
2975                    self.expected("PRIMARY, UNIQUE, FOREIGN, or CHECK")
2976                } else {
2977                    Ok(None)
2978                }
2979            }
2980        }
2981    }
2982
2983    pub fn parse_options_with_preceding_keyword(
2984        &mut self,
2985        keyword: Keyword,
2986    ) -> ModalResult<Vec<SqlOption>> {
2987        if self.parse_keyword(keyword) {
2988            self.expect_token(&Token::LParen)?;
2989            self.parse_options_inner()
2990        } else {
2991            Ok(vec![])
2992        }
2993    }
2994
2995    pub fn parse_options(&mut self) -> ModalResult<Vec<SqlOption>> {
2996        if self.peek_token() == Token::LParen {
2997            self.next_token();
2998            self.parse_options_inner()
2999        } else {
3000            Ok(vec![])
3001        }
3002    }
3003
3004    // has parsed a LParen
3005    pub fn parse_options_inner(&mut self) -> ModalResult<Vec<SqlOption>> {
3006        let mut values = vec![];
3007        loop {
3008            values.push(Parser::parse_sql_option(self)?);
3009            let comma = self.consume_token(&Token::Comma);
3010            if self.consume_token(&Token::RParen) {
3011                // allow a trailing comma, even though it's not in standard
3012                break;
3013            } else if !comma {
3014                return self.expected("',' or ')' after option definition");
3015            }
3016        }
3017        Ok(values)
3018    }
3019
3020    pub fn parse_sql_option(&mut self) -> ModalResult<SqlOption> {
3021        const CONNECTION_REF_KEY: &str = "connection";
3022        const BACKFILL_ORDER: &str = "backfill_order";
3023
3024        let name = self.parse_object_name()?;
3025        self.expect_token(&Token::Eq)?;
3026        let value = {
3027            if name.real_value().eq_ignore_ascii_case(CONNECTION_REF_KEY) {
3028                let connection_name = self.parse_object_name()?;
3029                // tolerate previous buggy Display that outputs `connection = connection foo`
3030                let connection_name = match connection_name.0.as_slice() {
3031                    [ident] if ident.real_value() == CONNECTION_REF_KEY => {
3032                        self.parse_object_name()?
3033                    }
3034                    _ => connection_name,
3035                };
3036                SqlOptionValue::ConnectionRef(ConnectionRefValue { connection_name })
3037            } else if name.real_value().eq_ignore_ascii_case(BACKFILL_ORDER) {
3038                let order = self.parse_backfill_order_strategy()?;
3039                SqlOptionValue::BackfillOrder(order)
3040            } else {
3041                self.parse_value_and_obj_ref::<false>()?
3042            }
3043        };
3044        Ok(SqlOption { name, value })
3045    }
3046
3047    // <config_param> { TO | = } { <value> | DEFAULT }
3048    // <config_param> is not a keyword, but an identifier
3049    pub fn parse_config_param(&mut self) -> ModalResult<ConfigParam> {
3050        let param = self.parse_identifier()?;
3051        if !self.consume_token(&Token::Eq) && !self.parse_keyword(Keyword::TO) {
3052            return self.expected("'=' or 'TO' after config parameter");
3053        }
3054        let value = self.parse_set_variable()?;
3055        Ok(ConfigParam { param, value })
3056    }
3057
3058    pub fn parse_since(&mut self) -> ModalResult<Since> {
3059        if self.parse_keyword(Keyword::SINCE) {
3060            let checkpoint = *self;
3061            let token = self.next_token();
3062            match token.token {
3063                Token::Word(w) => {
3064                    let ident = w.to_ident()?;
3065                    // Backward compatibility for now.
3066                    if ident.real_value() == "proctime" || ident.real_value() == "now" {
3067                        self.expect_token(&Token::LParen)?;
3068                        self.expect_token(&Token::RParen)?;
3069                        Ok(Since::ProcessTime)
3070                    } else if ident.real_value() == "begin" {
3071                        self.expect_token(&Token::LParen)?;
3072                        self.expect_token(&Token::RParen)?;
3073                        Ok(Since::Begin)
3074                    } else {
3075                        parser_err!(
3076                            "Expected proctime(), begin() or now(), found: {}",
3077                            ident.real_value()
3078                        )
3079                    }
3080                }
3081                Token::Number(s) => {
3082                    let num = s
3083                        .parse::<u64>()
3084                        .map_err(|e| StrError(format!("Could not parse '{}' as u64: {}", s, e)))?;
3085                    Ok(Since::TimestampMsNum(num))
3086                }
3087                _ => self.expected_at(checkpoint, "proctime(), begin() , now(), Number"),
3088            }
3089        } else if self.parse_word("FULL") {
3090            Ok(Since::Full)
3091        } else {
3092            Ok(Since::ProcessTime)
3093        }
3094    }
3095
3096    pub fn parse_emit_mode(&mut self) -> ModalResult<Option<EmitMode>> {
3097        if self.parse_keyword(Keyword::EMIT) {
3098            match self.parse_one_of_keywords(&[Keyword::IMMEDIATELY, Keyword::ON]) {
3099                Some(Keyword::IMMEDIATELY) => Ok(Some(EmitMode::Immediately)),
3100                Some(Keyword::ON) => {
3101                    self.expect_keywords(&[Keyword::WINDOW, Keyword::CLOSE])?;
3102                    Ok(Some(EmitMode::OnWindowClose))
3103                }
3104                Some(_) => unreachable!(),
3105                None => self.expected("IMMEDIATELY or ON WINDOW CLOSE after EMIT"),
3106            }
3107        } else {
3108            Ok(None)
3109        }
3110    }
3111
3112    pub fn parse_alter(&mut self) -> ModalResult<Statement> {
3113        if self.parse_keyword(Keyword::DATABASE) {
3114            self.parse_alter_database()
3115        } else if self.parse_keyword(Keyword::SCHEMA) {
3116            self.parse_alter_schema()
3117        } else if self.parse_keyword(Keyword::TABLE) {
3118            self.parse_alter_table()
3119        } else if self.parse_keyword(Keyword::INDEX) {
3120            self.parse_alter_index()
3121        } else if self.parse_keyword(Keyword::VIEW) {
3122            self.parse_alter_view(false)
3123        } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEW]) {
3124            self.parse_alter_view(true)
3125        } else if self.parse_keyword(Keyword::SINK) {
3126            self.parse_alter_sink()
3127        } else if self.parse_keyword(Keyword::SOURCE) {
3128            self.parse_alter_source()
3129        } else if self.parse_keyword(Keyword::FUNCTION) {
3130            self.parse_alter_function()
3131        } else if self.parse_keyword(Keyword::CONNECTION) {
3132            self.parse_alter_connection()
3133        } else if self.parse_keyword(Keyword::USER) {
3134            self.parse_alter_user()
3135        } else if self.parse_keyword(Keyword::SYSTEM) {
3136            self.parse_alter_system()
3137        } else if self.parse_keyword(Keyword::SUBSCRIPTION) {
3138            self.parse_alter_subscription()
3139        } else if self.parse_keyword(Keyword::SECRET) {
3140            self.parse_alter_secret()
3141        } else if self.parse_word("FRAGMENT") {
3142            self.parse_alter_fragment()
3143        } else if self.parse_keywords(&[Keyword::DEFAULT, Keyword::PRIVILEGES]) {
3144            self.parse_alter_default_privileges()
3145        } else {
3146            self.expected(
3147                "DATABASE, FRAGMENT, SCHEMA, TABLE, INDEX, MATERIALIZED, VIEW, SINK, SUBSCRIPTION, SOURCE, FUNCTION, USER, SECRET or SYSTEM after ALTER"
3148            )
3149        }
3150    }
3151
3152    pub fn parse_alter_database(&mut self) -> ModalResult<Statement> {
3153        let database_name = self.parse_object_name()?;
3154        let operation = if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3155            let owner_name: Ident = self.parse_identifier()?;
3156            AlterDatabaseOperation::ChangeOwner {
3157                new_owner_name: owner_name,
3158            }
3159        } else if self.parse_keyword(Keyword::RENAME) {
3160            if self.parse_keyword(Keyword::TO) {
3161                let database_name = self.parse_object_name()?;
3162                AlterDatabaseOperation::RenameDatabase { database_name }
3163            } else {
3164                return self.expected("TO after RENAME");
3165            }
3166        } else if self.parse_keyword(Keyword::SET) {
3167            // check will be delayed to frontend
3168            AlterDatabaseOperation::SetParam(self.parse_config_param()?)
3169        } else {
3170            return self.expected("RENAME, OWNER TO, OR SET after ALTER DATABASE");
3171        };
3172
3173        Ok(Statement::AlterDatabase {
3174            name: database_name,
3175            operation,
3176        })
3177    }
3178
3179    pub fn parse_alter_schema(&mut self) -> ModalResult<Statement> {
3180        let schema_name = self.parse_object_name()?;
3181        let operation = if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3182            let owner_name: Ident = self.parse_identifier()?;
3183            AlterSchemaOperation::ChangeOwner {
3184                new_owner_name: owner_name,
3185            }
3186        } else if self.parse_keyword(Keyword::RENAME) {
3187            self.expect_keyword(Keyword::TO)?;
3188            let schema_name = self.parse_object_name()?;
3189            AlterSchemaOperation::RenameSchema { schema_name }
3190        } else if self.parse_keywords(&[Keyword::SWAP, Keyword::WITH]) {
3191            let target_schema = self.parse_object_name()?;
3192            AlterSchemaOperation::SwapRenameSchema { target_schema }
3193        } else {
3194            return self.expected("RENAME, OWNER TO, OR SWAP WITH after ALTER SCHEMA");
3195        };
3196
3197        Ok(Statement::AlterSchema {
3198            name: schema_name,
3199            operation,
3200        })
3201    }
3202
3203    pub fn parse_alter_user(&mut self) -> ModalResult<Statement> {
3204        Ok(Statement::AlterUser(AlterUserStatement::parse_to(self)?))
3205    }
3206
3207    pub fn parse_alter_table(&mut self) -> ModalResult<Statement> {
3208        let _ = self.parse_keyword(Keyword::ONLY);
3209        let table_name = self.parse_object_name()?;
3210        let operation = if self.parse_keyword(Keyword::ADD) {
3211            if let Some(constraint) = self.parse_optional_table_constraint()? {
3212                AlterTableOperation::AddConstraint(constraint)
3213            } else {
3214                let _ = self.parse_keyword(Keyword::COLUMN);
3215                let _if_not_exists =
3216                    self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
3217                let column_def = self.parse_column_def()?;
3218                AlterTableOperation::AddColumn { column_def }
3219            }
3220        } else if self.parse_keywords(&[Keyword::DROP, Keyword::CONNECTOR]) {
3221            AlterTableOperation::DropConnector
3222        } else if self.parse_keyword(Keyword::RENAME) {
3223            if self.parse_keyword(Keyword::CONSTRAINT) {
3224                let old_name = self.parse_identifier_non_reserved()?;
3225                self.expect_keyword(Keyword::TO)?;
3226                let new_name = self.parse_identifier_non_reserved()?;
3227                AlterTableOperation::RenameConstraint { old_name, new_name }
3228            } else if self.parse_keyword(Keyword::TO) {
3229                let table_name = self.parse_object_name()?;
3230                AlterTableOperation::RenameTable { table_name }
3231            } else {
3232                let _ = self.parse_keyword(Keyword::COLUMN);
3233                let old_column_name = self.parse_identifier_non_reserved()?;
3234                self.expect_keyword(Keyword::TO)?;
3235                let new_column_name = self.parse_identifier_non_reserved()?;
3236                AlterTableOperation::RenameColumn {
3237                    old_column_name,
3238                    new_column_name,
3239                }
3240            }
3241        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3242            let owner_name: Ident = self.parse_identifier()?;
3243            AlterTableOperation::ChangeOwner {
3244                new_owner_name: owner_name,
3245            }
3246        } else if self.parse_keyword(Keyword::SET) {
3247            if self.parse_keyword(Keyword::SCHEMA) {
3248                let schema_name = self.parse_object_name()?;
3249                AlterTableOperation::SetSchema {
3250                    new_schema_name: schema_name,
3251                }
3252            } else if self.parse_keyword(Keyword::PARALLELISM) {
3253                if self.expect_keyword(Keyword::TO).is_err()
3254                    && self.expect_token(&Token::Eq).is_err()
3255                {
3256                    return self.expected("TO or = after ALTER TABLE SET PARALLELISM");
3257                }
3258
3259                let value = self.parse_set_variable()?;
3260
3261                let deferred = self.parse_keyword(Keyword::DEFERRED);
3262
3263                AlterTableOperation::SetParallelism {
3264                    parallelism: value,
3265                    deferred,
3266                }
3267            } else if let Some(rate_limit) = self.parse_alter_source_rate_limit(true)? {
3268                AlterTableOperation::SetSourceRateLimit { rate_limit }
3269            } else if let Some(rate_limit) = self.parse_alter_backfill_rate_limit()? {
3270                AlterTableOperation::SetBackfillRateLimit { rate_limit }
3271            } else if let Some(rate_limit) = self.parse_alter_dml_rate_limit()? {
3272                AlterTableOperation::SetDmlRateLimit { rate_limit }
3273            } else {
3274                return self
3275                    .expected("SCHEMA/PARALLELISM/SOURCE_RATE_LIMIT/DML_RATE_LIMIT after SET");
3276            }
3277        } else if self.parse_keyword(Keyword::DROP) {
3278            let _ = self.parse_keyword(Keyword::COLUMN);
3279            let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
3280            let column_name = self.parse_identifier_non_reserved()?;
3281            let cascade = self.parse_keyword(Keyword::CASCADE);
3282            AlterTableOperation::DropColumn {
3283                column_name,
3284                if_exists,
3285                cascade,
3286            }
3287        } else if self.parse_keyword(Keyword::ALTER) {
3288            let _ = self.parse_keyword(Keyword::COLUMN);
3289            let column_name = self.parse_identifier_non_reserved()?;
3290
3291            let op = if self.parse_keywords(&[Keyword::SET, Keyword::NOT, Keyword::NULL]) {
3292                AlterColumnOperation::SetNotNull {}
3293            } else if self.parse_keywords(&[Keyword::DROP, Keyword::NOT, Keyword::NULL]) {
3294                AlterColumnOperation::DropNotNull {}
3295            } else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
3296                AlterColumnOperation::SetDefault {
3297                    value: self.parse_expr()?,
3298                }
3299            } else if self.parse_keywords(&[Keyword::DROP, Keyword::DEFAULT]) {
3300                AlterColumnOperation::DropDefault {}
3301            } else if self.parse_keywords(&[Keyword::SET, Keyword::DATA, Keyword::TYPE])
3302                || (self.parse_keyword(Keyword::TYPE))
3303            {
3304                let data_type = self.parse_data_type()?;
3305                let using = if self.parse_keyword(Keyword::USING) {
3306                    Some(self.parse_expr()?)
3307                } else {
3308                    None
3309                };
3310                AlterColumnOperation::SetDataType { data_type, using }
3311            } else {
3312                return self
3313                    .expected("SET/DROP NOT NULL, SET DEFAULT, SET DATA TYPE after ALTER COLUMN");
3314            };
3315            AlterTableOperation::AlterColumn { column_name, op }
3316        } else if self.parse_keywords(&[Keyword::REFRESH, Keyword::SCHEMA]) {
3317            AlterTableOperation::RefreshSchema
3318        } else if self.parse_keywords(&[Keyword::SWAP, Keyword::WITH]) {
3319            let target_table = self.parse_object_name()?;
3320            AlterTableOperation::SwapRenameTable { target_table }
3321        } else if self.parse_keyword(Keyword::CONNECTOR) {
3322            let with_options = self.parse_with_properties()?;
3323            AlterTableOperation::AlterConnectorProps {
3324                alter_props: with_options,
3325            }
3326        } else {
3327            return self.expected(
3328                "ADD or RENAME or OWNER TO or SET or DROP or SWAP or CONNECTOR after ALTER TABLE",
3329            );
3330        };
3331        Ok(Statement::AlterTable {
3332            name: table_name,
3333            operation,
3334        })
3335    }
3336
3337    /// BACKFILL_RATE_LIMIT = default | NUMBER
3338    /// BACKFILL_RATE_LIMIT TO default | NUMBER
3339    pub fn parse_alter_backfill_rate_limit(&mut self) -> ModalResult<Option<i32>> {
3340        if !self.parse_word("BACKFILL_RATE_LIMIT") {
3341            return Ok(None);
3342        }
3343        if self.expect_keyword(Keyword::TO).is_err() && self.expect_token(&Token::Eq).is_err() {
3344            return self.expected("TO or = after ALTER TABLE SET BACKFILL_RATE_LIMIT");
3345        }
3346        let rate_limit = if self.parse_keyword(Keyword::DEFAULT) {
3347            -1
3348        } else {
3349            let s = self.parse_number_value()?;
3350            if let Ok(n) = s.parse::<i32>() {
3351                n
3352            } else {
3353                return self.expected("number or DEFAULT");
3354            }
3355        };
3356        Ok(Some(rate_limit))
3357    }
3358
3359    /// DML_RATE_LIMIT = default | NUMBER
3360    /// DML_RATE_LIMIT TO default | NUMBER
3361    pub fn parse_alter_dml_rate_limit(&mut self) -> ModalResult<Option<i32>> {
3362        if !self.parse_word("DML_RATE_LIMIT") {
3363            return Ok(None);
3364        }
3365        if self.expect_keyword(Keyword::TO).is_err() && self.expect_token(&Token::Eq).is_err() {
3366            return self.expected("TO or = after ALTER TABLE SET DML_RATE_LIMIT");
3367        }
3368        let rate_limit = if self.parse_keyword(Keyword::DEFAULT) {
3369            -1
3370        } else {
3371            let s = self.parse_number_value()?;
3372            if let Ok(n) = s.parse::<i32>() {
3373                n
3374            } else {
3375                return self.expected("number or DEFAULT");
3376            }
3377        };
3378        Ok(Some(rate_limit))
3379    }
3380
3381    /// SOURCE_RATE_LIMIT = default | NUMBER
3382    /// SOURCE_RATE_LIMIT TO default | NUMBER
3383    pub fn parse_alter_source_rate_limit(&mut self, is_table: bool) -> ModalResult<Option<i32>> {
3384        if !self.parse_word("SOURCE_RATE_LIMIT") {
3385            return Ok(None);
3386        }
3387        if self.expect_keyword(Keyword::TO).is_err() && self.expect_token(&Token::Eq).is_err() {
3388            let ddl = if is_table { "TABLE" } else { "SOURCE" };
3389            return self.expected(&format!("TO or = after ALTER {ddl} SET SOURCE_RATE_LIMIT"));
3390        }
3391        let rate_limit = if self.parse_keyword(Keyword::DEFAULT) {
3392            -1
3393        } else {
3394            let s = self.parse_number_value()?;
3395            if let Ok(n) = s.parse::<i32>() {
3396                n
3397            } else {
3398                return self.expected("number or DEFAULT");
3399            }
3400        };
3401        Ok(Some(rate_limit))
3402    }
3403
3404    pub fn parse_alter_index(&mut self) -> ModalResult<Statement> {
3405        let index_name = self.parse_object_name()?;
3406        let operation = if self.parse_keyword(Keyword::RENAME) {
3407            if self.parse_keyword(Keyword::TO) {
3408                let index_name = self.parse_object_name()?;
3409                AlterIndexOperation::RenameIndex { index_name }
3410            } else {
3411                return self.expected("TO after RENAME");
3412            }
3413        } else if self.parse_keyword(Keyword::SET) {
3414            if self.parse_keyword(Keyword::PARALLELISM) {
3415                if self.expect_keyword(Keyword::TO).is_err()
3416                    && self.expect_token(&Token::Eq).is_err()
3417                {
3418                    return self.expected("TO or = after ALTER TABLE SET PARALLELISM");
3419                }
3420
3421                let value = self.parse_set_variable()?;
3422
3423                let deferred = self.parse_keyword(Keyword::DEFERRED);
3424
3425                AlterIndexOperation::SetParallelism {
3426                    parallelism: value,
3427                    deferred,
3428                }
3429            } else {
3430                return self.expected("PARALLELISM after SET");
3431            }
3432        } else {
3433            return self.expected("RENAME after ALTER INDEX");
3434        };
3435
3436        Ok(Statement::AlterIndex {
3437            name: index_name,
3438            operation,
3439        })
3440    }
3441
3442    pub fn parse_alter_view(&mut self, materialized: bool) -> ModalResult<Statement> {
3443        let view_name = self.parse_object_name()?;
3444        let operation = if self.parse_keyword(Keyword::AS) {
3445            let query = Box::new(self.parse_query()?);
3446            AlterViewOperation::AsQuery { query }
3447        } else if self.parse_keyword(Keyword::RENAME) {
3448            if self.parse_keyword(Keyword::TO) {
3449                let view_name = self.parse_object_name()?;
3450                AlterViewOperation::RenameView { view_name }
3451            } else {
3452                return self.expected("TO after RENAME");
3453            }
3454        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3455            let owner_name: Ident = self.parse_identifier()?;
3456            AlterViewOperation::ChangeOwner {
3457                new_owner_name: owner_name,
3458            }
3459        } else if self.parse_keywords(&[Keyword::SWAP, Keyword::WITH]) {
3460            let target_view = self.parse_object_name()?;
3461            AlterViewOperation::SwapRenameView { target_view }
3462        } else if self.parse_keyword(Keyword::SET) {
3463            if self.parse_keyword(Keyword::SCHEMA) {
3464                let schema_name = self.parse_object_name()?;
3465                AlterViewOperation::SetSchema {
3466                    new_schema_name: schema_name,
3467                }
3468            } else if self.parse_word("STREAMING_ENABLE_UNALIGNED_JOIN") {
3469                if self.expect_keyword(Keyword::TO).is_err()
3470                    && self.expect_token(&Token::Eq).is_err()
3471                {
3472                    return self
3473                        .expected("TO or = after ALTER TABLE SET STREAMING_ENABLE_UNALIGNED_JOIN");
3474                }
3475                let value = self.parse_boolean()?;
3476                AlterViewOperation::SetStreamingEnableUnalignedJoin { enable: value }
3477            } else if self.parse_keyword(Keyword::PARALLELISM) && materialized {
3478                if self.expect_keyword(Keyword::TO).is_err()
3479                    && self.expect_token(&Token::Eq).is_err()
3480                {
3481                    return self.expected("TO or = after ALTER TABLE SET PARALLELISM");
3482                }
3483
3484                let value = self.parse_set_variable()?;
3485
3486                let deferred = self.parse_keyword(Keyword::DEFERRED);
3487
3488                AlterViewOperation::SetParallelism {
3489                    parallelism: value,
3490                    deferred,
3491                }
3492            } else if self.parse_keyword(Keyword::RESOURCE_GROUP) && materialized {
3493                if self.expect_keyword(Keyword::TO).is_err()
3494                    && self.expect_token(&Token::Eq).is_err()
3495                {
3496                    return self
3497                        .expected("TO or = after ALTER MATERIALIZED VIEW SET RESOURCE_GROUP");
3498                }
3499                let value = self.parse_set_variable()?;
3500                let deferred = self.parse_keyword(Keyword::DEFERRED);
3501
3502                AlterViewOperation::SetResourceGroup {
3503                    resource_group: Some(value),
3504                    deferred,
3505                }
3506            } else if materialized
3507                && let Some(rate_limit) = self.parse_alter_backfill_rate_limit()?
3508            {
3509                AlterViewOperation::SetBackfillRateLimit { rate_limit }
3510            } else {
3511                return self.expected("SCHEMA/PARALLELISM/BACKFILL_RATE_LIMIT after SET");
3512            }
3513        } else if self.parse_keyword(Keyword::RESET) {
3514            if self.parse_keyword(Keyword::RESOURCE_GROUP) && materialized {
3515                let deferred = self.parse_keyword(Keyword::DEFERRED);
3516
3517                AlterViewOperation::SetResourceGroup {
3518                    resource_group: None,
3519                    deferred,
3520                }
3521            } else {
3522                return self.expected("RESOURCE_GROUP after RESET");
3523            }
3524        } else {
3525            return self.expected(&format!(
3526                "AS, RENAME, OWNER TO, SET, or SWAP after ALTER {}VIEW",
3527                if materialized { "MATERIALIZED " } else { "" }
3528            ));
3529        };
3530
3531        Ok(Statement::AlterView {
3532            materialized,
3533            name: view_name,
3534            operation,
3535        })
3536    }
3537
3538    /// SINK_RATE_LIMIT = default | NUMBER
3539    /// SINK_RATE_LIMIT TO default | NUMBER
3540    pub fn parse_alter_sink_rate_limit(&mut self) -> ModalResult<Option<i32>> {
3541        if !self.parse_word("SINK_RATE_LIMIT") {
3542            return Ok(None);
3543        }
3544        if self.expect_keyword(Keyword::TO).is_err() && self.expect_token(&Token::Eq).is_err() {
3545            return self.expected("TO or = after ALTER SINK SET SINK_RATE_LIMIT");
3546        }
3547        let rate_limit = if self.parse_keyword(Keyword::DEFAULT) {
3548            -1
3549        } else {
3550            let s = self.parse_number_value()?;
3551            if let Ok(n) = s.parse::<i32>() {
3552                n
3553            } else {
3554                return self.expected("number or DEFAULT");
3555            }
3556        };
3557        Ok(Some(rate_limit))
3558    }
3559
3560    pub fn parse_alter_sink(&mut self) -> ModalResult<Statement> {
3561        let sink_name = self.parse_object_name()?;
3562        let operation = if self.parse_keyword(Keyword::RENAME) {
3563            if self.parse_keyword(Keyword::TO) {
3564                let sink_name = self.parse_object_name()?;
3565                AlterSinkOperation::RenameSink { sink_name }
3566            } else {
3567                return self.expected("TO after RENAME");
3568            }
3569        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3570            let owner_name: Ident = self.parse_identifier()?;
3571            AlterSinkOperation::ChangeOwner {
3572                new_owner_name: owner_name,
3573            }
3574        } else if self.parse_keyword(Keyword::SET) {
3575            if self.parse_keyword(Keyword::SCHEMA) {
3576                let schema_name = self.parse_object_name()?;
3577                AlterSinkOperation::SetSchema {
3578                    new_schema_name: schema_name,
3579                }
3580            } else if self.parse_word("STREAMING_ENABLE_UNALIGNED_JOIN") {
3581                self.expect_keyword(Keyword::TO)?;
3582                let value = self.parse_boolean()?;
3583                AlterSinkOperation::SetStreamingEnableUnalignedJoin { enable: value }
3584            } else if self.parse_keyword(Keyword::PARALLELISM) {
3585                if self.expect_keyword(Keyword::TO).is_err()
3586                    && self.expect_token(&Token::Eq).is_err()
3587                {
3588                    return self.expected("TO or = after ALTER TABLE SET PARALLELISM");
3589                }
3590
3591                let value = self.parse_set_variable()?;
3592                let deferred = self.parse_keyword(Keyword::DEFERRED);
3593
3594                AlterSinkOperation::SetParallelism {
3595                    parallelism: value,
3596                    deferred,
3597                }
3598            } else if let Some(rate_limit) = self.parse_alter_sink_rate_limit()? {
3599                AlterSinkOperation::SetSinkRateLimit { rate_limit }
3600            } else {
3601                return self.expected("SCHEMA/PARALLELISM after SET");
3602            }
3603        } else if self.parse_keywords(&[Keyword::SWAP, Keyword::WITH]) {
3604            let target_sink = self.parse_object_name()?;
3605            AlterSinkOperation::SwapRenameSink { target_sink }
3606        } else if self.parse_keyword(Keyword::CONNECTOR) {
3607            let changed_props = self.parse_with_properties()?;
3608            AlterSinkOperation::AlterConnectorProps {
3609                alter_props: changed_props,
3610            }
3611        } else {
3612            return self.expected("RENAME or OWNER TO or SET or CONNECTOR WITH after ALTER SINK");
3613        };
3614
3615        Ok(Statement::AlterSink {
3616            name: sink_name,
3617            operation,
3618        })
3619    }
3620
3621    pub fn parse_alter_subscription(&mut self) -> ModalResult<Statement> {
3622        let subscription_name = self.parse_object_name()?;
3623        let operation = if self.parse_keyword(Keyword::RENAME) {
3624            if self.parse_keyword(Keyword::TO) {
3625                let subscription_name = self.parse_object_name()?;
3626                AlterSubscriptionOperation::RenameSubscription { subscription_name }
3627            } else {
3628                return self.expected("TO after RENAME");
3629            }
3630        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3631            let owner_name: Ident = self.parse_identifier()?;
3632            AlterSubscriptionOperation::ChangeOwner {
3633                new_owner_name: owner_name,
3634            }
3635        } else if self.parse_keyword(Keyword::SET) {
3636            if self.parse_keyword(Keyword::SCHEMA) {
3637                let schema_name = self.parse_object_name()?;
3638                AlterSubscriptionOperation::SetSchema {
3639                    new_schema_name: schema_name,
3640                }
3641            } else {
3642                return self.expected("SCHEMA after SET");
3643            }
3644        } else if self.parse_keywords(&[Keyword::SWAP, Keyword::WITH]) {
3645            let target_subscription = self.parse_object_name()?;
3646            AlterSubscriptionOperation::SwapRenameSubscription {
3647                target_subscription,
3648            }
3649        } else {
3650            return self.expected("RENAME or OWNER TO or SET or SWAP after ALTER SUBSCRIPTION");
3651        };
3652
3653        Ok(Statement::AlterSubscription {
3654            name: subscription_name,
3655            operation,
3656        })
3657    }
3658
3659    pub fn parse_alter_source(&mut self) -> ModalResult<Statement> {
3660        let source_name = self.parse_object_name()?;
3661        let operation = if self.parse_keyword(Keyword::RENAME) {
3662            if self.parse_keyword(Keyword::TO) {
3663                let source_name = self.parse_object_name()?;
3664                AlterSourceOperation::RenameSource { source_name }
3665            } else {
3666                return self.expected("TO after RENAME");
3667            }
3668        } else if self.parse_keyword(Keyword::ADD) {
3669            let _ = self.parse_keyword(Keyword::COLUMN);
3670            let _if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
3671            let column_def = self.parse_column_def()?;
3672            AlterSourceOperation::AddColumn { column_def }
3673        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3674            let owner_name: Ident = self.parse_identifier()?;
3675            AlterSourceOperation::ChangeOwner {
3676                new_owner_name: owner_name,
3677            }
3678        } else if self.parse_keyword(Keyword::SET) {
3679            if self.parse_keyword(Keyword::SCHEMA) {
3680                let schema_name = self.parse_object_name()?;
3681                AlterSourceOperation::SetSchema {
3682                    new_schema_name: schema_name,
3683                }
3684            } else if let Some(rate_limit) = self.parse_alter_source_rate_limit(false)? {
3685                AlterSourceOperation::SetSourceRateLimit { rate_limit }
3686            } else if self.parse_keyword(Keyword::PARALLELISM) {
3687                if self.expect_keyword(Keyword::TO).is_err()
3688                    && self.expect_token(&Token::Eq).is_err()
3689                {
3690                    return self.expected("TO or = after ALTER SOURCE SET PARALLELISM");
3691                }
3692
3693                let value = self.parse_set_variable()?;
3694                let deferred = self.parse_keyword(Keyword::DEFERRED);
3695
3696                AlterSourceOperation::SetParallelism {
3697                    parallelism: value,
3698                    deferred,
3699                }
3700            } else {
3701                return self.expected("SCHEMA, SOURCE_RATE_LIMIT or PARALLELISM after SET");
3702            }
3703        } else if self.peek_nth_any_of_keywords(0, &[Keyword::FORMAT]) {
3704            let format_encode = self.parse_schema()?.unwrap();
3705            if format_encode.key_encode.is_some() {
3706                parser_err!("key encode clause is not supported in source schema");
3707            }
3708            AlterSourceOperation::FormatEncode { format_encode }
3709        } else if self.parse_keywords(&[Keyword::REFRESH, Keyword::SCHEMA]) {
3710            AlterSourceOperation::RefreshSchema
3711        } else if self.parse_keywords(&[Keyword::SWAP, Keyword::WITH]) {
3712            let target_source = self.parse_object_name()?;
3713            AlterSourceOperation::SwapRenameSource { target_source }
3714        } else if self.parse_keyword(Keyword::CONNECTOR) {
3715            let with_options = self.parse_with_properties()?;
3716            AlterSourceOperation::AlterConnectorProps {
3717                alter_props: with_options,
3718            }
3719        } else {
3720            return self
3721                .expected("RENAME, ADD COLUMN, OWNER TO, CONNECTOR or SET after ALTER SOURCE");
3722        };
3723
3724        Ok(Statement::AlterSource {
3725            name: source_name,
3726            operation,
3727        })
3728    }
3729
3730    pub fn parse_alter_function(&mut self) -> ModalResult<Statement> {
3731        let FunctionDesc { name, args } = self.parse_function_desc()?;
3732
3733        let operation = if self.parse_keyword(Keyword::SET) {
3734            if self.parse_keyword(Keyword::SCHEMA) {
3735                let schema_name = self.parse_object_name()?;
3736                AlterFunctionOperation::SetSchema {
3737                    new_schema_name: schema_name,
3738                }
3739            } else {
3740                return self.expected("SCHEMA after SET");
3741            }
3742        } else {
3743            return self.expected("SET after ALTER FUNCTION");
3744        };
3745
3746        Ok(Statement::AlterFunction {
3747            name,
3748            args,
3749            operation,
3750        })
3751    }
3752
3753    pub fn parse_alter_connection(&mut self) -> ModalResult<Statement> {
3754        let connection_name = self.parse_object_name()?;
3755        let operation = if self.parse_keyword(Keyword::SET) {
3756            if self.parse_keyword(Keyword::SCHEMA) {
3757                let schema_name = self.parse_object_name()?;
3758                AlterConnectionOperation::SetSchema {
3759                    new_schema_name: schema_name,
3760                }
3761            } else {
3762                return self.expected("SCHEMA after SET");
3763            }
3764        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
3765            let owner_name: Ident = self.parse_identifier()?;
3766            AlterConnectionOperation::ChangeOwner {
3767                new_owner_name: owner_name,
3768            }
3769        } else {
3770            return self.expected("SET, or OWNER TO after ALTER CONNECTION");
3771        };
3772
3773        Ok(Statement::AlterConnection {
3774            name: connection_name,
3775            operation,
3776        })
3777    }
3778
3779    pub fn parse_alter_system(&mut self) -> ModalResult<Statement> {
3780        self.expect_keyword(Keyword::SET)?;
3781        let param = self.parse_identifier()?;
3782        if self.expect_keyword(Keyword::TO).is_err() && self.expect_token(&Token::Eq).is_err() {
3783            return self.expected("TO or = after ALTER SYSTEM SET");
3784        }
3785        let value = self.parse_set_variable()?;
3786        Ok(Statement::AlterSystem { param, value })
3787    }
3788
3789    pub fn parse_alter_secret(&mut self) -> ModalResult<Statement> {
3790        let secret_name = self.parse_object_name()?;
3791        let with_options = self.parse_with_properties()?;
3792        self.expect_keyword(Keyword::AS)?;
3793        let new_credential = self.ensure_parse_value()?;
3794        let operation = AlterSecretOperation::ChangeCredential { new_credential };
3795        Ok(Statement::AlterSecret {
3796            name: secret_name,
3797            with_options,
3798            operation,
3799        })
3800    }
3801
3802    pub fn parse_alter_fragment(&mut self) -> ModalResult<Statement> {
3803        let fragment_id = self.parse_literal_u32()?;
3804        if !self.parse_keyword(Keyword::SET) {
3805            return self.expected("SET after ALTER FRAGMENT");
3806        }
3807        let rate_limit = self.parse_alter_fragment_rate_limit()?;
3808        let operation = AlterFragmentOperation::AlterBackfillRateLimit { rate_limit };
3809        Ok(Statement::AlterFragment {
3810            fragment_id,
3811            operation,
3812        })
3813    }
3814
3815    fn parse_alter_fragment_rate_limit(&mut self) -> ModalResult<i32> {
3816        if !self.parse_word("RATE_LIMIT") {
3817            return self.expected("expected RATE_LIMIT after SET");
3818        }
3819        if self.expect_keyword(Keyword::TO).is_err() && self.expect_token(&Token::Eq).is_err() {
3820            return self.expected("TO or = after RATE_LIMIT");
3821        }
3822        let rate_limit = if self.parse_keyword(Keyword::DEFAULT) {
3823            -1
3824        } else {
3825            let s = self.parse_number_value()?;
3826            if let Ok(n) = s.parse::<i32>() {
3827                n
3828            } else {
3829                return self.expected("number or DEFAULT");
3830            }
3831        };
3832        Ok(rate_limit)
3833    }
3834
3835    /// Parse a copy statement
3836    pub fn parse_copy(&mut self) -> ModalResult<Statement> {
3837        let table_name = self.parse_object_name()?;
3838        let columns = self.parse_parenthesized_column_list(Optional)?;
3839        self.expect_keywords(&[Keyword::FROM, Keyword::STDIN])?;
3840        self.expect_token(&Token::SemiColon)?;
3841        let values = self.parse_tsv();
3842        Ok(Statement::Copy {
3843            table_name,
3844            columns,
3845            values,
3846        })
3847    }
3848
3849    /// Parse a tab separated values in
3850    /// COPY payload
3851    fn parse_tsv(&mut self) -> Vec<Option<String>> {
3852        self.parse_tab_value()
3853    }
3854
3855    fn parse_tab_value(&mut self) -> Vec<Option<String>> {
3856        let mut values = vec![];
3857        let mut content = String::from("");
3858        while let Some(t) = self.next_token_no_skip() {
3859            match t.token {
3860                Token::Whitespace(Whitespace::Tab) => {
3861                    values.push(Some(content.clone()));
3862                    content.clear();
3863                }
3864                Token::Whitespace(Whitespace::Newline) => {
3865                    values.push(Some(content.clone()));
3866                    content.clear();
3867                }
3868                Token::Backslash => {
3869                    if self.consume_token(&Token::Period) {
3870                        return values;
3871                    }
3872                    if let Token::Word(w) = self.next_token().token
3873                        && w.value == "N"
3874                    {
3875                        values.push(None);
3876                    }
3877                }
3878                _ => {
3879                    content.push_str(&t.to_string());
3880                }
3881            }
3882        }
3883        values
3884    }
3885
3886    pub fn ensure_parse_value(&mut self) -> ModalResult<Value> {
3887        match self.parse_value_and_obj_ref::<true>()? {
3888            SqlOptionValue::Value(value) => Ok(value),
3889            SqlOptionValue::SecretRef(_)
3890            | SqlOptionValue::ConnectionRef(_)
3891            | SqlOptionValue::BackfillOrder(_) => unreachable!(),
3892        }
3893    }
3894
3895    /// Parse a literal value (numbers, strings, date/time, booleans)
3896    pub fn parse_value_and_obj_ref<const FORBID_OBJ_REF: bool>(
3897        &mut self,
3898    ) -> ModalResult<SqlOptionValue> {
3899        let checkpoint = *self;
3900        let token = self.next_token();
3901        match token.token {
3902            Token::Word(w) => match w.keyword {
3903                Keyword::TRUE => Ok(Value::Boolean(true).into()),
3904                Keyword::FALSE => Ok(Value::Boolean(false).into()),
3905                Keyword::NULL => Ok(Value::Null.into()),
3906                Keyword::NoKeyword if w.quote_style.is_some() => match w.quote_style {
3907                    Some('"') => Ok(Value::DoubleQuotedString(w.value).into()),
3908                    Some('\'') => Ok(Value::SingleQuotedString(w.value).into()),
3909                    _ => self.expected_at(checkpoint, "A value")?,
3910                },
3911                Keyword::SECRET => {
3912                    if FORBID_OBJ_REF {
3913                        return self.expected_at(
3914                            checkpoint,
3915                            "a concrete value rather than a secret reference",
3916                        );
3917                    }
3918                    let secret = self.parse_secret_ref()?;
3919                    Ok(SqlOptionValue::SecretRef(secret))
3920                }
3921                _ => self.expected_at(checkpoint, "a concrete value"),
3922            },
3923            Token::Number(ref n) => Ok(Value::Number(n.clone()).into()),
3924            Token::SingleQuotedString(ref s) => Ok(Value::SingleQuotedString(s.clone()).into()),
3925            Token::DollarQuotedString(ref s) => Ok(Value::DollarQuotedString(s.clone()).into()),
3926            Token::CstyleEscapesString(ref s) => Ok(Value::CstyleEscapedString(s.clone()).into()),
3927            Token::NationalStringLiteral(ref s) => {
3928                Ok(Value::NationalStringLiteral(s.clone()).into())
3929            }
3930            Token::HexStringLiteral(ref s) => Ok(Value::HexStringLiteral(s.clone()).into()),
3931            _ => self.expected_at(checkpoint, "a value"),
3932        }
3933    }
3934
3935    fn parse_secret_ref(&mut self) -> ModalResult<SecretRefValue> {
3936        let secret_name = self.parse_object_name()?;
3937        let ref_as = if self.parse_keywords(&[Keyword::AS, Keyword::FILE]) {
3938            SecretRefAsType::File
3939        } else {
3940            SecretRefAsType::Text
3941        };
3942        Ok(SecretRefValue {
3943            secret_name,
3944            ref_as,
3945        })
3946    }
3947
3948    fn parse_set_variable(&mut self) -> ModalResult<SetVariableValue> {
3949        alt((
3950            Keyword::DEFAULT.value(SetVariableValue::Default),
3951            separated(
3952                1..,
3953                alt((
3954                    Self::ensure_parse_value.map(SetVariableValueSingle::Literal),
3955                    |parser: &mut Self| {
3956                        let checkpoint = *parser;
3957                        let ident = parser.parse_identifier()?;
3958                        if ident.value == "default" {
3959                            *parser = checkpoint;
3960                            return parser.expected("parameter list value").map_err(|e| e.cut());
3961                        }
3962                        Ok(SetVariableValueSingle::Ident(ident))
3963                    },
3964                    fail.expect("parameter value"),
3965                )),
3966                Token::Comma,
3967            )
3968            .map(|list: Vec<SetVariableValueSingle>| {
3969                if list.len() == 1 {
3970                    SetVariableValue::Single(list[0].clone())
3971                } else {
3972                    SetVariableValue::List(list)
3973                }
3974            }),
3975        ))
3976        .parse_next(self)
3977    }
3978
3979    fn parse_backfill_order_strategy(&mut self) -> ModalResult<BackfillOrderStrategy> {
3980        alt((
3981            Keyword::DEFAULT.value(BackfillOrderStrategy::Default),
3982            Keyword::NONE.value(BackfillOrderStrategy::None),
3983            Keyword::AUTO.value(BackfillOrderStrategy::Auto),
3984            Self::parse_fixed_backfill_order.map(BackfillOrderStrategy::Fixed),
3985            fail.expect("backfill order strategy"),
3986        ))
3987        .parse_next(self)
3988    }
3989
3990    fn parse_fixed_backfill_order(&mut self) -> ModalResult<Vec<(ObjectName, ObjectName)>> {
3991        self.expect_word("FIXED")?;
3992        self.expect_token(&Token::LParen)?;
3993        let edges = separated(
3994            0..,
3995            separated_pair(
3996                Self::parse_object_name,
3997                Token::Op("->".to_owned()),
3998                Self::parse_object_name,
3999            ),
4000            Token::Comma,
4001        )
4002        .parse_next(self)?;
4003        self.expect_token(&Token::RParen)?;
4004        Ok(edges)
4005    }
4006
4007    pub fn parse_number_value(&mut self) -> ModalResult<String> {
4008        let checkpoint = *self;
4009        match self.ensure_parse_value()? {
4010            Value::Number(v) => Ok(v),
4011            _ => self.expected_at(checkpoint, "literal number"),
4012        }
4013    }
4014
4015    pub fn parse_literal_u32(&mut self) -> ModalResult<u32> {
4016        literal_u32(self)
4017    }
4018
4019    pub fn parse_literal_u64(&mut self) -> ModalResult<u64> {
4020        literal_u64(self)
4021    }
4022
4023    pub fn parse_function_definition(&mut self) -> ModalResult<FunctionDefinition> {
4024        alt((
4025            single_quoted_string.map(FunctionDefinition::SingleQuotedDef),
4026            dollar_quoted_string.map(FunctionDefinition::DoubleDollarDef),
4027            Self::parse_identifier.map(|i| FunctionDefinition::Identifier(i.value)),
4028            fail.expect("function definition"),
4029        ))
4030        .parse_next(self)
4031    }
4032
4033    /// Parse a literal string
4034    pub fn parse_literal_string(&mut self) -> ModalResult<String> {
4035        let checkpoint = *self;
4036        let token = self.next_token();
4037        match token.token {
4038            Token::SingleQuotedString(s) => Ok(s),
4039            _ => self.expected_at(checkpoint, "literal string"),
4040        }
4041    }
4042
4043    /// Parse a SQL datatype (in the context of a CREATE TABLE statement for example)
4044    pub fn parse_data_type(&mut self) -> ModalResult<DataType> {
4045        parser_v2::data_type(self)
4046    }
4047
4048    /// Parse `AS identifier` (or simply `identifier` if it's not a reserved keyword)
4049    /// Some examples with aliases: `SELECT 1 foo`, `SELECT COUNT(*) AS cnt`,
4050    /// `SELECT ... FROM t1 foo, t2 bar`, `SELECT ... FROM (...) AS bar`
4051    pub fn parse_optional_alias(
4052        &mut self,
4053        reserved_kwds: &[Keyword],
4054    ) -> ModalResult<Option<Ident>> {
4055        let after_as = self.parse_keyword(Keyword::AS);
4056        let checkpoint = *self;
4057        let token = self.next_token();
4058        match token.token {
4059            // Accept any identifier after `AS` (though many dialects have restrictions on
4060            // keywords that may appear here). If there's no `AS`: don't parse keywords,
4061            // which may start a construct allowed in this position, to be parsed as aliases.
4062            // (For example, in `FROM t1 JOIN` the `JOIN` will always be parsed as a keyword,
4063            // not an alias.)
4064            Token::Word(w) if after_as || (!reserved_kwds.contains(&w.keyword)) => {
4065                Ok(Some(w.to_ident()?))
4066            }
4067            _ => {
4068                *self = checkpoint;
4069                if after_as {
4070                    return self.expected("an identifier after AS");
4071                }
4072                Ok(None) // no alias found
4073            }
4074        }
4075    }
4076
4077    /// Parse `AS identifier` when the AS is describing a table-valued object,
4078    /// like in `... FROM generate_series(1, 10) AS t (col)`. In this case
4079    /// the alias is allowed to optionally name the columns in the table, in
4080    /// addition to the table itself.
4081    pub fn parse_optional_table_alias(
4082        &mut self,
4083        reserved_kwds: &[Keyword],
4084    ) -> ModalResult<Option<TableAlias>> {
4085        match self.parse_optional_alias(reserved_kwds)? {
4086            Some(name) => {
4087                let columns = self.parse_parenthesized_column_list(Optional)?;
4088                Ok(Some(TableAlias { name, columns }))
4089            }
4090            None => Ok(None),
4091        }
4092    }
4093
4094    /// syntax `FOR SYSTEM_TIME AS OF PROCTIME()` is used for temporal join.
4095    pub fn parse_as_of(&mut self) -> ModalResult<AsOf> {
4096        Keyword::FOR.parse_next(self)?;
4097        alt((
4098            preceded(
4099                (Keyword::SYSTEM_TIME, Keyword::AS, Keyword::OF),
4100                cut_err(
4101                    alt((
4102                        preceded(
4103                            (
4104                                Self::parse_identifier.verify(|ident| ident.real_value() == "now"),
4105                                cut_err(Token::LParen),
4106                                cut_err(Token::RParen),
4107                                Token::Minus,
4108                            ),
4109                            Self::parse_literal_interval.try_map(|e| match e {
4110                                Expr::Value(v) => match v {
4111                                    Value::Interval {
4112                                        value,
4113                                        leading_field,
4114                                        ..
4115                                    } => {
4116                                        let Some(leading_field) = leading_field else {
4117                                            return Err(StrError("expect duration unit".into()));
4118                                        };
4119                                        Ok(AsOf::ProcessTimeWithInterval((value, leading_field)))
4120                                    }
4121                                    _ => Err(StrError("expect Value::Interval".into())),
4122                                },
4123                                _ => Err(StrError("expect Expr::Value".into())),
4124                            }),
4125                        ),
4126                        (
4127                            Self::parse_identifier.verify(|ident| ident.real_value() == "now"),
4128                            cut_err(Token::LParen),
4129                            cut_err(Token::RParen),
4130                        )
4131                            .value(AsOf::ProcessTimeWithInterval((
4132                                "0".to_owned(),
4133                                DateTimeField::Second,
4134                            ))),
4135                        (
4136                            Self::parse_identifier.verify(|ident| ident.real_value() == "proctime"),
4137                            cut_err(Token::LParen),
4138                            cut_err(Token::RParen),
4139                        )
4140                            .value(AsOf::ProcessTime),
4141                        literal_i64.map(AsOf::TimestampNum),
4142                        single_quoted_string.map(AsOf::TimestampString),
4143                    ))
4144                    .expect("proctime(), now(), number or string"),
4145                ),
4146            ),
4147            preceded(
4148                (Keyword::SYSTEM_VERSION, Keyword::AS, Keyword::OF),
4149                cut_err(
4150                    alt((
4151                        literal_i64.map(AsOf::VersionNum),
4152                        single_quoted_string.map(AsOf::VersionString),
4153                    ))
4154                    .expect("number or string"),
4155                ),
4156            ),
4157        ))
4158        .parse_next(self)
4159    }
4160
4161    /// Parse a possibly qualified, possibly quoted identifier, e.g.
4162    /// `foo` or `myschema."table"
4163    pub fn parse_object_name(&mut self) -> ModalResult<ObjectName> {
4164        let mut idents = vec![];
4165        loop {
4166            idents.push(self.parse_identifier()?);
4167            if !self.consume_token(&Token::Period) {
4168                break;
4169            }
4170        }
4171        Ok(ObjectName(idents))
4172    }
4173
4174    /// Parse identifiers strictly i.e. don't parse keywords
4175    pub fn parse_identifiers_non_keywords(&mut self) -> ModalResult<Vec<Ident>> {
4176        let mut idents = vec![];
4177        loop {
4178            match self.peek_token().token {
4179                Token::Word(w) => {
4180                    if w.keyword != Keyword::NoKeyword {
4181                        break;
4182                    }
4183
4184                    idents.push(w.to_ident()?);
4185                }
4186                Token::EOF | Token::Eq => break,
4187                _ => {}
4188            }
4189
4190            self.next_token();
4191        }
4192
4193        Ok(idents)
4194    }
4195
4196    /// Parse identifiers
4197    pub fn parse_identifiers(&mut self) -> ModalResult<Vec<Ident>> {
4198        let mut idents = vec![];
4199        loop {
4200            let token = self.next_token();
4201            match token.token {
4202                Token::Word(w) => {
4203                    idents.push(w.to_ident()?);
4204                }
4205                Token::EOF => break,
4206                _ => {}
4207            }
4208        }
4209
4210        Ok(idents)
4211    }
4212
4213    /// Parse a simple one-word identifier (possibly quoted, possibly a keyword)
4214    pub fn parse_identifier(&mut self) -> ModalResult<Ident> {
4215        let checkpoint = *self;
4216        let token = self.next_token();
4217        match token.token {
4218            Token::Word(w) => Ok(w.to_ident()?),
4219            _ => self.expected_at(checkpoint, "identifier"),
4220        }
4221    }
4222
4223    /// Parse a simple one-word identifier (possibly quoted, possibly a non-reserved keyword)
4224    pub fn parse_identifier_non_reserved(&mut self) -> ModalResult<Ident> {
4225        let checkpoint = *self;
4226        let token = self.next_token();
4227        match token.token {
4228            Token::Word(w) => {
4229                match keywords::RESERVED_FOR_COLUMN_OR_TABLE_NAME.contains(&w.keyword) {
4230                    true => parser_err!("syntax error at or near {w}"),
4231                    false => Ok(w.to_ident()?),
4232                }
4233            }
4234            _ => self.expected_at(checkpoint, "identifier"),
4235        }
4236    }
4237
4238    /// Parse a parenthesized comma-separated list of unqualified, possibly quoted identifiers
4239    pub fn parse_parenthesized_column_list(
4240        &mut self,
4241        optional: IsOptional,
4242    ) -> ModalResult<Vec<Ident>> {
4243        if self.consume_token(&Token::LParen) {
4244            let cols = self.parse_comma_separated(Parser::parse_identifier_non_reserved)?;
4245            self.expect_token(&Token::RParen)?;
4246            Ok(cols)
4247        } else if optional == Optional {
4248            Ok(vec![])
4249        } else {
4250            self.expected("a list of columns in parentheses")
4251        }
4252    }
4253
4254    pub fn parse_returning(&mut self, optional: IsOptional) -> ModalResult<Vec<SelectItem>> {
4255        if self.parse_keyword(Keyword::RETURNING) {
4256            let cols = self.parse_comma_separated(Parser::parse_select_item)?;
4257            Ok(cols)
4258        } else if optional == Optional {
4259            Ok(vec![])
4260        } else {
4261            self.expected("a list of columns or * after returning")
4262        }
4263    }
4264
4265    pub fn parse_row_expr(&mut self) -> ModalResult<Expr> {
4266        Ok(Expr::Row(self.parse_token_wrapped_exprs(
4267            &Token::LParen,
4268            &Token::RParen,
4269        )?))
4270    }
4271
4272    /// Parse a comma-separated list (maybe empty) from a wrapped expression
4273    pub fn parse_token_wrapped_exprs(
4274        &mut self,
4275        left: &Token,
4276        right: &Token,
4277    ) -> ModalResult<Vec<Expr>> {
4278        if self.consume_token(left) {
4279            let exprs = if self.consume_token(right) {
4280                vec![]
4281            } else {
4282                let exprs = self.parse_comma_separated(Parser::parse_expr)?;
4283                self.expect_token(right)?;
4284                exprs
4285            };
4286            Ok(exprs)
4287        } else {
4288            self.expected(left.to_string().as_str())
4289        }
4290    }
4291
4292    pub fn parse_optional_precision(&mut self) -> ModalResult<Option<u64>> {
4293        if self.consume_token(&Token::LParen) {
4294            let n = self.parse_literal_u64()?;
4295            self.expect_token(&Token::RParen)?;
4296            Ok(Some(n))
4297        } else {
4298            Ok(None)
4299        }
4300    }
4301
4302    pub fn parse_optional_precision_scale(&mut self) -> ModalResult<(Option<u64>, Option<u64>)> {
4303        if self.consume_token(&Token::LParen) {
4304            let n = self.parse_literal_u64()?;
4305            let scale = if self.consume_token(&Token::Comma) {
4306                Some(self.parse_literal_u64()?)
4307            } else {
4308                None
4309            };
4310            self.expect_token(&Token::RParen)?;
4311            Ok((Some(n), scale))
4312        } else {
4313            Ok((None, None))
4314        }
4315    }
4316
4317    pub fn parse_delete(&mut self) -> ModalResult<Statement> {
4318        self.expect_keyword(Keyword::FROM)?;
4319        let table_name = self.parse_object_name()?;
4320        let selection = if self.parse_keyword(Keyword::WHERE) {
4321            Some(self.parse_expr()?)
4322        } else {
4323            None
4324        };
4325        let returning = self.parse_returning(Optional)?;
4326
4327        Ok(Statement::Delete {
4328            table_name,
4329            selection,
4330            returning,
4331        })
4332    }
4333
4334    pub fn parse_boolean(&mut self) -> ModalResult<bool> {
4335        if let Some(keyword) = self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]) {
4336            match keyword {
4337                Keyword::TRUE => Ok(true),
4338                Keyword::FALSE => Ok(false),
4339                _ => unreachable!(),
4340            }
4341        } else {
4342            self.expected("TRUE or FALSE")
4343        }
4344    }
4345
4346    pub fn parse_optional_boolean(&mut self, default: bool) -> bool {
4347        self.parse_boolean().unwrap_or(default)
4348    }
4349
4350    fn parse_explain_options(&mut self) -> ModalResult<(ExplainOptions, Option<u64>)> {
4351        let mut options = ExplainOptions::default();
4352        let mut analyze_duration = None;
4353
4354        let explain_key_words = [
4355            Keyword::BACKFILL,
4356            Keyword::VERBOSE,
4357            Keyword::TRACE,
4358            Keyword::TYPE,
4359            Keyword::LOGICAL,
4360            Keyword::PHYSICAL,
4361            Keyword::DISTSQL,
4362            Keyword::FORMAT,
4363            Keyword::DURATION_SECS,
4364        ];
4365
4366        let parse_explain_option = |parser: &mut Parser<'_>| -> ModalResult<()> {
4367            let keyword = parser.expect_one_of_keywords(&explain_key_words)?;
4368            match keyword {
4369                Keyword::VERBOSE => options.verbose = parser.parse_optional_boolean(true),
4370                Keyword::TRACE => options.trace = parser.parse_optional_boolean(true),
4371                Keyword::BACKFILL => options.backfill = parser.parse_optional_boolean(true),
4372                Keyword::TYPE => {
4373                    let explain_type = parser.expect_one_of_keywords(&[
4374                        Keyword::LOGICAL,
4375                        Keyword::PHYSICAL,
4376                        Keyword::DISTSQL,
4377                    ])?;
4378                    match explain_type {
4379                        Keyword::LOGICAL => options.explain_type = ExplainType::Logical,
4380                        Keyword::PHYSICAL => options.explain_type = ExplainType::Physical,
4381                        Keyword::DISTSQL => options.explain_type = ExplainType::DistSql,
4382                        _ => unreachable!("{}", keyword),
4383                    }
4384                }
4385                Keyword::LOGICAL => options.explain_type = ExplainType::Logical,
4386                Keyword::PHYSICAL => options.explain_type = ExplainType::Physical,
4387                Keyword::DISTSQL => options.explain_type = ExplainType::DistSql,
4388                Keyword::FORMAT => {
4389                    options.explain_format = {
4390                        match parser.expect_one_of_keywords(&[
4391                            Keyword::TEXT,
4392                            Keyword::JSON,
4393                            Keyword::XML,
4394                            Keyword::YAML,
4395                            Keyword::DOT,
4396                        ])? {
4397                            Keyword::TEXT => ExplainFormat::Text,
4398                            Keyword::JSON => ExplainFormat::Json,
4399                            Keyword::XML => ExplainFormat::Xml,
4400                            Keyword::YAML => ExplainFormat::Yaml,
4401                            Keyword::DOT => ExplainFormat::Dot,
4402                            _ => unreachable!("{}", keyword),
4403                        }
4404                    }
4405                }
4406                Keyword::DURATION_SECS => {
4407                    analyze_duration = Some(parser.parse_literal_u64()?);
4408                }
4409                _ => unreachable!("{}", keyword),
4410            };
4411            Ok(())
4412        };
4413
4414        // In order to support following statement, we need to peek before consume.
4415        // explain (select 1) union (select 1)
4416        if self.peek_token() == Token::LParen
4417            && self.peek_nth_any_of_keywords(1, &explain_key_words)
4418            && self.consume_token(&Token::LParen)
4419        {
4420            self.parse_comma_separated(parse_explain_option)?;
4421            self.expect_token(&Token::RParen)?;
4422        }
4423
4424        Ok((options, analyze_duration))
4425    }
4426
4427    pub fn parse_explain(&mut self) -> ModalResult<Statement> {
4428        let analyze = self.parse_keyword(Keyword::ANALYZE);
4429        let (options, analyze_duration) = self.parse_explain_options()?;
4430
4431        if analyze {
4432            fn parse_analyze_target(parser: &mut Parser<'_>) -> ModalResult<Option<AnalyzeTarget>> {
4433                if parser.parse_keyword(Keyword::TABLE) {
4434                    let table_name = parser.parse_object_name()?;
4435                    Ok(Some(AnalyzeTarget::Table(table_name)))
4436                } else if parser.parse_keyword(Keyword::INDEX) {
4437                    let index_name = parser.parse_object_name()?;
4438                    Ok(Some(AnalyzeTarget::Index(index_name)))
4439                } else if parser.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEW]) {
4440                    let view_name = parser.parse_object_name()?;
4441                    Ok(Some(AnalyzeTarget::MaterializedView(view_name)))
4442                } else if parser.parse_keyword(Keyword::INDEX) {
4443                    let index_name = parser.parse_object_name()?;
4444                    Ok(Some(AnalyzeTarget::Index(index_name)))
4445                } else if parser.parse_keyword(Keyword::SINK) {
4446                    let sink_name = parser.parse_object_name()?;
4447                    Ok(Some(AnalyzeTarget::Sink(sink_name)))
4448                } else if parser.parse_word("ID") {
4449                    let job_id = parser.parse_literal_u32()?;
4450                    Ok(Some(AnalyzeTarget::Id(job_id)))
4451                } else {
4452                    Ok(None)
4453                }
4454            }
4455            if let Some(target) = parse_analyze_target(self)? {
4456                let statement = Statement::ExplainAnalyzeStreamJob {
4457                    target,
4458                    duration_secs: analyze_duration,
4459                };
4460                return Ok(statement);
4461            }
4462        }
4463
4464        let statement = match self.parse_statement() {
4465            Ok(statement) => statement,
4466            error @ Err(_) => {
4467                return if analyze {
4468                    self.expected_at(
4469                        *self,
4470                        "SINK, TABLE, MATERIALIZED VIEW, INDEX or a statement after ANALYZE",
4471                    )
4472                } else {
4473                    error
4474                };
4475            }
4476        };
4477        Ok(Statement::Explain {
4478            analyze,
4479            statement: Box::new(statement),
4480            options,
4481        })
4482    }
4483
4484    pub fn parse_describe(&mut self) -> ModalResult<Statement> {
4485        let kind = match self.parse_one_of_keywords(&[Keyword::FRAGMENT, Keyword::FRAGMENTS]) {
4486            Some(Keyword::FRAGMENT) => {
4487                let fragment_id = self.parse_literal_u32()?;
4488                return Ok(Statement::DescribeFragment { fragment_id });
4489            }
4490            Some(Keyword::FRAGMENTS) => DescribeKind::Fragments,
4491            None => DescribeKind::Plain,
4492            Some(_) => unreachable!(),
4493        };
4494        let name = self.parse_object_name()?;
4495        Ok(Statement::Describe { name, kind })
4496    }
4497
4498    /// Parse a query expression, i.e. a `SELECT` statement optionally
4499    /// preceded with some `WITH` CTE declarations and optionally followed
4500    /// by `ORDER BY`. Unlike some other parse_... methods, this one doesn't
4501    /// expect the initial keyword to be already consumed
4502    pub fn parse_query(&mut self) -> ModalResult<Query> {
4503        let with = if self.parse_keyword(Keyword::WITH) {
4504            Some(With {
4505                recursive: self.parse_keyword(Keyword::RECURSIVE),
4506                cte_tables: self.parse_comma_separated(Parser::parse_cte)?,
4507            })
4508        } else {
4509            None
4510        };
4511
4512        let body = self.parse_query_body(0)?;
4513
4514        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
4515            self.parse_comma_separated(Parser::parse_order_by_expr)?
4516        } else {
4517            vec![]
4518        };
4519
4520        let mut limit = None;
4521        let mut offset = None;
4522        for _x in 0..2 {
4523            if limit.is_none() && self.parse_keyword(Keyword::LIMIT) {
4524                limit = self.parse_limit()?
4525            }
4526
4527            if offset.is_none() && self.parse_keyword(Keyword::OFFSET) {
4528                offset = Some(self.parse_offset()?)
4529            }
4530        }
4531
4532        let fetch = if self.parse_keyword(Keyword::FETCH) {
4533            if limit.is_some() {
4534                parser_err!("Cannot specify both LIMIT and FETCH");
4535            }
4536            let fetch = self.parse_fetch()?;
4537            if fetch.with_ties && order_by.is_empty() {
4538                parser_err!("WITH TIES cannot be specified without ORDER BY clause");
4539            }
4540            Some(fetch)
4541        } else {
4542            None
4543        };
4544
4545        Ok(Query {
4546            with,
4547            body,
4548            order_by,
4549            limit,
4550            offset,
4551            fetch,
4552        })
4553    }
4554
4555    /// Parse a CTE (`alias [( col1, col2, ... )] AS (subquery)`)
4556    fn parse_cte(&mut self) -> ModalResult<Cte> {
4557        let name = self.parse_identifier_non_reserved()?;
4558        let cte = if self.parse_keyword(Keyword::AS) {
4559            let cte_inner = self.parse_cte_inner()?;
4560            let alias = TableAlias {
4561                name,
4562                columns: vec![],
4563            };
4564            Cte { alias, cte_inner }
4565        } else {
4566            let columns = self.parse_parenthesized_column_list(Optional)?;
4567            self.expect_keyword(Keyword::AS)?;
4568            let cte_inner = self.parse_cte_inner()?;
4569            let alias = TableAlias { name, columns };
4570            Cte { alias, cte_inner }
4571        };
4572        Ok(cte)
4573    }
4574
4575    fn parse_cte_inner(&mut self) -> ModalResult<CteInner> {
4576        match self.expect_token(&Token::LParen) {
4577            Ok(()) => {
4578                let query = self.parse_query()?;
4579                self.expect_token(&Token::RParen)?;
4580                Ok(CteInner::Query(Box::new(query)))
4581            }
4582            _ => {
4583                let changelog = self.parse_identifier_non_reserved()?;
4584                if changelog.to_string().to_lowercase() != "changelog" {
4585                    parser_err!("Expected 'changelog' but found '{}'", changelog);
4586                }
4587                self.expect_keyword(Keyword::FROM)?;
4588                Ok(CteInner::ChangeLog(self.parse_object_name()?))
4589            }
4590        }
4591    }
4592
4593    /// Parse a "query body", which is an expression with roughly the
4594    /// following grammar:
4595    /// ```text
4596    ///   query_body ::= restricted_select | '(' subquery ')' | set_operation
4597    ///   restricted_select ::= 'SELECT' [expr_list] [ from ] [ where ] [ groupby_having ]
4598    ///   subquery ::= query_body [ order_by_limit ]
4599    ///   set_operation ::= query_body { 'UNION' | 'EXCEPT' | 'INTERSECT' } [ 'ALL' ] query_body
4600    /// ```
4601    fn parse_query_body(&mut self, precedence: u8) -> ModalResult<SetExpr> {
4602        // We parse the expression using a Pratt parser, as in `parse_expr()`.
4603        // Start by parsing a restricted SELECT or a `(subquery)`:
4604        let mut expr = if self.parse_keyword(Keyword::SELECT) {
4605            SetExpr::Select(Box::new(self.parse_select()?))
4606        } else if self.consume_token(&Token::LParen) {
4607            // CTEs are not allowed here, but the parser currently accepts them
4608            let subquery = self.parse_query()?;
4609            self.expect_token(&Token::RParen)?;
4610            SetExpr::Query(Box::new(subquery))
4611        } else if self.parse_keyword(Keyword::VALUES) {
4612            SetExpr::Values(self.parse_values()?)
4613        } else {
4614            return self.expected("SELECT, VALUES, or a subquery in the query body");
4615        };
4616
4617        loop {
4618            // The query can be optionally followed by a set operator:
4619            let op = self.parse_set_operator(&self.peek_token().token);
4620            let next_precedence = match op {
4621                // UNION and EXCEPT have the same binding power and evaluate left-to-right
4622                Some(SetOperator::Union) | Some(SetOperator::Except) => 10,
4623                // INTERSECT has higher precedence than UNION/EXCEPT
4624                Some(SetOperator::Intersect) => 20,
4625                // Unexpected token or EOF => stop parsing the query body
4626                None => break,
4627            };
4628            if precedence >= next_precedence {
4629                break;
4630            }
4631            self.next_token(); // skip past the set operator
4632
4633            let all = self.parse_keyword(Keyword::ALL);
4634            let corresponding = self.parse_corresponding()?;
4635
4636            expr = SetExpr::SetOperation {
4637                left: Box::new(expr),
4638                op: op.unwrap(),
4639                corresponding,
4640                all,
4641                right: Box::new(self.parse_query_body(next_precedence)?),
4642            };
4643        }
4644
4645        Ok(expr)
4646    }
4647
4648    fn parse_set_operator(&mut self, token: &Token) -> Option<SetOperator> {
4649        match token {
4650            Token::Word(w) if w.keyword == Keyword::UNION => Some(SetOperator::Union),
4651            Token::Word(w) if w.keyword == Keyword::EXCEPT => Some(SetOperator::Except),
4652            Token::Word(w) if w.keyword == Keyword::INTERSECT => Some(SetOperator::Intersect),
4653            _ => None,
4654        }
4655    }
4656
4657    fn parse_corresponding(&mut self) -> ModalResult<Corresponding> {
4658        let corresponding = if self.parse_keyword(Keyword::CORRESPONDING) {
4659            let column_list = if self.parse_keyword(Keyword::BY) {
4660                Some(self.parse_parenthesized_column_list(IsOptional::Mandatory)?)
4661            } else {
4662                None
4663            };
4664            Corresponding::with_column_list(column_list)
4665        } else {
4666            Corresponding::none()
4667        };
4668        Ok(corresponding)
4669    }
4670
4671    /// Parse a restricted `SELECT` statement (no CTEs / `UNION` / `ORDER BY`),
4672    /// assuming the initial `SELECT` was already consumed
4673    pub fn parse_select(&mut self) -> ModalResult<Select> {
4674        let distinct = self.parse_all_or_distinct_on()?;
4675
4676        let projection = self.parse_comma_separated(Parser::parse_select_item)?;
4677
4678        // Note that for keywords to be properly handled here, they need to be
4679        // added to `RESERVED_FOR_COLUMN_ALIAS` / `RESERVED_FOR_TABLE_ALIAS`,
4680        // otherwise they may be parsed as an alias as part of the `projection`
4681        // or `from`.
4682
4683        let from = if self.parse_keyword(Keyword::FROM) {
4684            self.parse_comma_separated(Parser::parse_table_and_joins)?
4685        } else {
4686            vec![]
4687        };
4688        let mut lateral_views = vec![];
4689        loop {
4690            if self.parse_keywords(&[Keyword::LATERAL, Keyword::VIEW]) {
4691                let outer = self.parse_keyword(Keyword::OUTER);
4692                let lateral_view = self.parse_expr()?;
4693                let lateral_view_name = self.parse_object_name()?;
4694                let lateral_col_alias = self
4695                    .parse_comma_separated(|parser| {
4696                        parser.parse_optional_alias(&[
4697                            Keyword::WHERE,
4698                            Keyword::GROUP,
4699                            Keyword::CLUSTER,
4700                            Keyword::HAVING,
4701                            Keyword::LATERAL,
4702                        ]) // This couldn't possibly be a bad idea
4703                    })?
4704                    .into_iter()
4705                    .flatten()
4706                    .collect();
4707
4708                lateral_views.push(LateralView {
4709                    lateral_view,
4710                    lateral_view_name,
4711                    lateral_col_alias,
4712                    outer,
4713                });
4714            } else {
4715                break;
4716            }
4717        }
4718
4719        let selection = if self.parse_keyword(Keyword::WHERE) {
4720            Some(self.parse_expr()?)
4721        } else {
4722            None
4723        };
4724
4725        let group_by = if self.parse_keywords(&[Keyword::GROUP, Keyword::BY]) {
4726            self.parse_comma_separated(Parser::parse_group_by_expr)?
4727        } else {
4728            vec![]
4729        };
4730
4731        let having = if self.parse_keyword(Keyword::HAVING) {
4732            Some(self.parse_expr()?)
4733        } else {
4734            None
4735        };
4736
4737        let window = if self.parse_keyword(Keyword::WINDOW) {
4738            self.parse_comma_separated(Parser::parse_named_window)?
4739        } else {
4740            vec![]
4741        };
4742
4743        Ok(Select {
4744            distinct,
4745            projection,
4746            from,
4747            lateral_views,
4748            selection,
4749            group_by,
4750            having,
4751            window,
4752        })
4753    }
4754
4755    pub fn parse_set(&mut self) -> ModalResult<Statement> {
4756        let modifier = self.parse_one_of_keywords(&[Keyword::SESSION, Keyword::LOCAL]);
4757        if self.parse_keywords(&[Keyword::TIME, Keyword::ZONE]) {
4758            let value = alt((
4759                Keyword::DEFAULT.value(SetTimeZoneValue::Default),
4760                Keyword::LOCAL.value(SetTimeZoneValue::Local),
4761                preceded(
4762                    Keyword::INTERVAL,
4763                    cut_err(Self::parse_literal_interval.try_map(|e| match e {
4764                        // support a special case for clients which would send when initializing the connection
4765                        // like: SET TIME ZONE INTERVAL '+00:00' HOUR TO MINUTE;
4766                        Expr::Value(v) => match v {
4767                            Value::Interval { value, .. } => {
4768                                if value != "+00:00" {
4769                                    return Err(StrError("only support \"+00:00\" ".into()));
4770                                }
4771                                Ok(SetTimeZoneValue::Ident(Ident::with_quote_unchecked(
4772                                    '\'',
4773                                    "UTC".to_owned(),
4774                                )))
4775                            }
4776                            _ => Err(StrError("expect Value::Interval".into())),
4777                        },
4778                        _ => Err(StrError("expect Expr::Value".into())),
4779                    })),
4780                ),
4781                Self::parse_identifier.map(SetTimeZoneValue::Ident),
4782                Self::ensure_parse_value.map(SetTimeZoneValue::Literal),
4783            ))
4784            .expect("variable")
4785            .parse_next(self)?;
4786
4787            Ok(Statement::SetTimeZone {
4788                local: modifier == Some(Keyword::LOCAL),
4789                value,
4790            })
4791        } else if self.parse_keyword(Keyword::CHARACTERISTICS) && modifier == Some(Keyword::SESSION)
4792        {
4793            self.expect_keywords(&[Keyword::AS, Keyword::TRANSACTION])?;
4794            Ok(Statement::SetTransaction {
4795                modes: self.parse_transaction_modes()?,
4796                snapshot: None,
4797                session: true,
4798            })
4799        } else if self.parse_keyword(Keyword::TRANSACTION) && modifier.is_none() {
4800            if self.parse_keyword(Keyword::SNAPSHOT) {
4801                let snapshot_id = self.ensure_parse_value()?;
4802                return Ok(Statement::SetTransaction {
4803                    modes: vec![],
4804                    snapshot: Some(snapshot_id),
4805                    session: false,
4806                });
4807            }
4808            Ok(Statement::SetTransaction {
4809                modes: self.parse_transaction_modes()?,
4810                snapshot: None,
4811                session: false,
4812            })
4813        } else {
4814            let config_param = self.parse_config_param()?;
4815            Ok(Statement::SetVariable {
4816                local: modifier == Some(Keyword::LOCAL),
4817                variable: config_param.param,
4818                value: config_param.value,
4819            })
4820        }
4821    }
4822
4823    /// If have `databases`,`tables`,`columns`,`schemas` and `materialized views` after show,
4824    /// return `Statement::ShowCommand` or `Statement::ShowColumn`,
4825    /// otherwise, return `Statement::ShowVariable`.
4826    pub fn parse_show(&mut self) -> ModalResult<Statement> {
4827        let checkpoint = *self;
4828        if let Token::Word(w) = self.next_token().token {
4829            match w.keyword {
4830                Keyword::TABLES => {
4831                    return Ok(Statement::ShowObjects {
4832                        object: ShowObject::Table {
4833                            schema: self.parse_from_and_identifier()?,
4834                        },
4835                        filter: self.parse_show_statement_filter()?,
4836                    });
4837                }
4838                Keyword::INTERNAL => {
4839                    self.expect_keyword(Keyword::TABLES)?;
4840                    return Ok(Statement::ShowObjects {
4841                        object: ShowObject::InternalTable {
4842                            schema: self.parse_from_and_identifier()?,
4843                        },
4844                        filter: self.parse_show_statement_filter()?,
4845                    });
4846                }
4847                Keyword::SOURCES => {
4848                    return Ok(Statement::ShowObjects {
4849                        object: ShowObject::Source {
4850                            schema: self.parse_from_and_identifier()?,
4851                        },
4852                        filter: self.parse_show_statement_filter()?,
4853                    });
4854                }
4855                Keyword::SINKS => {
4856                    return Ok(Statement::ShowObjects {
4857                        object: ShowObject::Sink {
4858                            schema: self.parse_from_and_identifier()?,
4859                        },
4860                        filter: self.parse_show_statement_filter()?,
4861                    });
4862                }
4863                Keyword::SUBSCRIPTIONS => {
4864                    return Ok(Statement::ShowObjects {
4865                        object: ShowObject::Subscription {
4866                            schema: self.parse_from_and_identifier()?,
4867                        },
4868                        filter: self.parse_show_statement_filter()?,
4869                    });
4870                }
4871                Keyword::DATABASES => {
4872                    return Ok(Statement::ShowObjects {
4873                        object: ShowObject::Database,
4874                        filter: self.parse_show_statement_filter()?,
4875                    });
4876                }
4877                Keyword::SCHEMAS => {
4878                    return Ok(Statement::ShowObjects {
4879                        object: ShowObject::Schema,
4880                        filter: self.parse_show_statement_filter()?,
4881                    });
4882                }
4883                Keyword::VIEWS => {
4884                    return Ok(Statement::ShowObjects {
4885                        object: ShowObject::View {
4886                            schema: self.parse_from_and_identifier()?,
4887                        },
4888                        filter: self.parse_show_statement_filter()?,
4889                    });
4890                }
4891                Keyword::MATERIALIZED => {
4892                    if self.parse_keyword(Keyword::VIEWS) {
4893                        return Ok(Statement::ShowObjects {
4894                            object: ShowObject::MaterializedView {
4895                                schema: self.parse_from_and_identifier()?,
4896                            },
4897                            filter: self.parse_show_statement_filter()?,
4898                        });
4899                    } else {
4900                        return self.expected("VIEWS after MATERIALIZED");
4901                    }
4902                }
4903                Keyword::COLUMNS => {
4904                    if self.parse_keyword(Keyword::FROM) {
4905                        return Ok(Statement::ShowObjects {
4906                            object: ShowObject::Columns {
4907                                table: self.parse_object_name()?,
4908                            },
4909                            filter: self.parse_show_statement_filter()?,
4910                        });
4911                    } else {
4912                        return self.expected("from after columns");
4913                    }
4914                }
4915                Keyword::SECRETS => {
4916                    return Ok(Statement::ShowObjects {
4917                        object: ShowObject::Secret {
4918                            schema: self.parse_from_and_identifier()?,
4919                        },
4920                        filter: self.parse_show_statement_filter()?,
4921                    });
4922                }
4923                Keyword::CONNECTIONS => {
4924                    return Ok(Statement::ShowObjects {
4925                        object: ShowObject::Connection {
4926                            schema: self.parse_from_and_identifier()?,
4927                        },
4928                        filter: self.parse_show_statement_filter()?,
4929                    });
4930                }
4931                Keyword::FUNCTIONS => {
4932                    return Ok(Statement::ShowObjects {
4933                        object: ShowObject::Function {
4934                            schema: self.parse_from_and_identifier()?,
4935                        },
4936                        filter: self.parse_show_statement_filter()?,
4937                    });
4938                }
4939                Keyword::INDEXES => {
4940                    if self.parse_keyword(Keyword::FROM) {
4941                        return Ok(Statement::ShowObjects {
4942                            object: ShowObject::Indexes {
4943                                table: self.parse_object_name()?,
4944                            },
4945                            filter: self.parse_show_statement_filter()?,
4946                        });
4947                    } else {
4948                        return self.expected("from after indexes");
4949                    }
4950                }
4951                Keyword::CLUSTER => {
4952                    return Ok(Statement::ShowObjects {
4953                        object: ShowObject::Cluster,
4954                        filter: self.parse_show_statement_filter()?,
4955                    });
4956                }
4957                Keyword::JOBS => {
4958                    return Ok(Statement::ShowObjects {
4959                        object: ShowObject::Jobs,
4960                        filter: self.parse_show_statement_filter()?,
4961                    });
4962                }
4963                Keyword::PROCESSLIST => {
4964                    return Ok(Statement::ShowObjects {
4965                        object: ShowObject::ProcessList,
4966                        filter: self.parse_show_statement_filter()?,
4967                    });
4968                }
4969                Keyword::TRANSACTION => {
4970                    self.expect_keywords(&[Keyword::ISOLATION, Keyword::LEVEL])?;
4971                    return Ok(Statement::ShowTransactionIsolationLevel);
4972                }
4973                Keyword::CURSORS => {
4974                    return Ok(Statement::ShowObjects {
4975                        object: ShowObject::Cursor,
4976                        filter: None,
4977                    });
4978                }
4979                Keyword::SUBSCRIPTION => {
4980                    self.expect_keyword(Keyword::CURSORS)?;
4981                    return Ok(Statement::ShowObjects {
4982                        object: ShowObject::SubscriptionCursor,
4983                        filter: None,
4984                    });
4985                }
4986                _ => {}
4987            }
4988        }
4989        *self = checkpoint;
4990        Ok(Statement::ShowVariable {
4991            variable: self.parse_identifiers()?,
4992        })
4993    }
4994
4995    pub fn parse_cancel_job(&mut self) -> ModalResult<Statement> {
4996        // CANCEL [JOBS|JOB] job_ids
4997        match self.peek_token().token {
4998            Token::Word(w) if Keyword::JOBS == w.keyword || Keyword::JOB == w.keyword => {
4999                self.next_token();
5000            }
5001            _ => return self.expected("JOBS or JOB after CANCEL"),
5002        }
5003
5004        let mut job_ids = vec![];
5005        loop {
5006            job_ids.push(self.parse_literal_u32()?);
5007            if !self.consume_token(&Token::Comma) {
5008                break;
5009            }
5010        }
5011        Ok(Statement::CancelJobs(JobIdents(job_ids)))
5012    }
5013
5014    pub fn parse_kill_process(&mut self) -> ModalResult<Statement> {
5015        let worker_process_id = self.parse_literal_string()?;
5016        Ok(Statement::Kill(worker_process_id))
5017    }
5018
5019    /// Parser `from schema` after `show tables` and `show materialized views`, if not conclude
5020    /// `from` then use default schema name.
5021    pub fn parse_from_and_identifier(&mut self) -> ModalResult<Option<Ident>> {
5022        if self.parse_keyword(Keyword::FROM) {
5023            Ok(Some(self.parse_identifier_non_reserved()?))
5024        } else {
5025            Ok(None)
5026        }
5027    }
5028
5029    /// Parse object type and name after `show create`.
5030    pub fn parse_show_create(&mut self) -> ModalResult<Statement> {
5031        if let Token::Word(w) = self.next_token().token {
5032            let show_type = match w.keyword {
5033                Keyword::TABLE => ShowCreateType::Table,
5034                Keyword::MATERIALIZED => {
5035                    if self.parse_keyword(Keyword::VIEW) {
5036                        ShowCreateType::MaterializedView
5037                    } else {
5038                        return self.expected("VIEW after MATERIALIZED");
5039                    }
5040                }
5041                Keyword::VIEW => ShowCreateType::View,
5042                Keyword::INDEX => ShowCreateType::Index,
5043                Keyword::SOURCE => ShowCreateType::Source,
5044                Keyword::SINK => ShowCreateType::Sink,
5045                Keyword::SUBSCRIPTION => ShowCreateType::Subscription,
5046                Keyword::FUNCTION => ShowCreateType::Function,
5047                _ => return self.expected(
5048                    "TABLE, MATERIALIZED VIEW, VIEW, INDEX, FUNCTION, SOURCE, SUBSCRIPTION or SINK",
5049                ),
5050            };
5051            return Ok(Statement::ShowCreateObject {
5052                create_type: show_type,
5053                name: self.parse_object_name()?,
5054            });
5055        }
5056        self.expected(
5057            "TABLE, MATERIALIZED VIEW, VIEW, INDEX, FUNCTION, SOURCE, SUBSCRIPTION or SINK",
5058        )
5059    }
5060
5061    pub fn parse_show_statement_filter(&mut self) -> ModalResult<Option<ShowStatementFilter>> {
5062        if self.parse_keyword(Keyword::LIKE) {
5063            Ok(Some(ShowStatementFilter::Like(
5064                self.parse_literal_string()?,
5065            )))
5066        } else if self.parse_keyword(Keyword::ILIKE) {
5067            Ok(Some(ShowStatementFilter::ILike(
5068                self.parse_literal_string()?,
5069            )))
5070        } else if self.parse_keyword(Keyword::WHERE) {
5071            Ok(Some(ShowStatementFilter::Where(self.parse_expr()?)))
5072        } else {
5073            Ok(None)
5074        }
5075    }
5076
5077    pub fn parse_table_and_joins(&mut self) -> ModalResult<TableWithJoins> {
5078        let relation = self.parse_table_factor()?;
5079
5080        // Note that for keywords to be properly handled here, they need to be
5081        // added to `RESERVED_FOR_TABLE_ALIAS`, otherwise they may be parsed as
5082        // a table alias.
5083        let mut joins = vec![];
5084        loop {
5085            let join = if self.parse_keyword(Keyword::CROSS) {
5086                let join_operator = if self.parse_keyword(Keyword::JOIN) {
5087                    JoinOperator::CrossJoin
5088                } else {
5089                    return self.expected("JOIN after CROSS");
5090                };
5091                Join {
5092                    relation: self.parse_table_factor()?,
5093                    join_operator,
5094                }
5095            } else {
5096                let (natural, asof) =
5097                    match self.parse_one_of_keywords(&[Keyword::NATURAL, Keyword::ASOF]) {
5098                        Some(Keyword::NATURAL) => (true, false),
5099                        Some(Keyword::ASOF) => (false, true),
5100                        Some(_) => unreachable!(),
5101                        None => (false, false),
5102                    };
5103                let peek_keyword = if let Token::Word(w) = self.peek_token().token {
5104                    w.keyword
5105                } else {
5106                    Keyword::NoKeyword
5107                };
5108
5109                let join_operator_type = match peek_keyword {
5110                    Keyword::INNER | Keyword::JOIN => {
5111                        let _ = self.parse_keyword(Keyword::INNER);
5112                        self.expect_keyword(Keyword::JOIN)?;
5113                        if asof {
5114                            JoinOperator::AsOfInner
5115                        } else {
5116                            JoinOperator::Inner
5117                        }
5118                    }
5119                    kw @ Keyword::LEFT | kw @ Keyword::RIGHT | kw @ Keyword::FULL => {
5120                        let checkpoint = *self;
5121                        let _ = self.next_token();
5122                        let _ = self.parse_keyword(Keyword::OUTER);
5123                        self.expect_keyword(Keyword::JOIN)?;
5124                        if asof {
5125                            if Keyword::LEFT == kw {
5126                                JoinOperator::AsOfLeft
5127                            } else {
5128                                return self.expected_at(
5129                                    checkpoint,
5130                                    "LEFT after ASOF. RIGHT or FULL are not supported",
5131                                );
5132                            }
5133                        } else {
5134                            match kw {
5135                                Keyword::LEFT => JoinOperator::LeftOuter,
5136                                Keyword::RIGHT => JoinOperator::RightOuter,
5137                                Keyword::FULL => JoinOperator::FullOuter,
5138                                _ => unreachable!(),
5139                            }
5140                        }
5141                    }
5142                    Keyword::OUTER => {
5143                        return self.expected("LEFT, RIGHT, or FULL");
5144                    }
5145                    _ if natural => {
5146                        return self.expected("a join type after NATURAL");
5147                    }
5148                    _ if asof => {
5149                        return self.expected("a join type after ASOF");
5150                    }
5151                    _ => break,
5152                };
5153                let relation = self.parse_table_factor()?;
5154                let join_constraint = self.parse_join_constraint(natural)?;
5155                let join_operator = join_operator_type(join_constraint);
5156                let need_constraint = match join_operator {
5157                    JoinOperator::Inner(JoinConstraint::None) => Some("INNER JOIN"),
5158                    JoinOperator::AsOfInner(JoinConstraint::None) => Some("ASOF INNER JOIN"),
5159                    JoinOperator::AsOfLeft(JoinConstraint::None) => Some("ASOF LEFT JOIN"),
5160                    _ => None,
5161                };
5162                if let Some(join_type) = need_constraint {
5163                    return self.expected(&format!("join constraint after {join_type}"));
5164                }
5165
5166                Join {
5167                    relation,
5168                    join_operator,
5169                }
5170            };
5171            joins.push(join);
5172        }
5173        Ok(TableWithJoins { relation, joins })
5174    }
5175
5176    /// A table name or a parenthesized subquery, followed by optional `[AS] alias`
5177    pub fn parse_table_factor(&mut self) -> ModalResult<TableFactor> {
5178        if self.parse_keyword(Keyword::LATERAL) {
5179            // LATERAL must always be followed by a subquery.
5180            if !self.consume_token(&Token::LParen) {
5181                self.expected("subquery after LATERAL")?;
5182            }
5183            self.parse_derived_table_factor(Lateral)
5184        } else if self.consume_token(&Token::LParen) {
5185            // A left paren introduces either a derived table (i.e., a subquery)
5186            // or a nested join. It's nearly impossible to determine ahead of
5187            // time which it is... so we just try to parse both.
5188            //
5189            // Here's an example that demonstrates the complexity:
5190            //                     /-------------------------------------------------------\
5191            //                     | /-----------------------------------\                 |
5192            //     SELECT * FROM ( ( ( (SELECT 1) UNION (SELECT 2) ) AS t1 NATURAL JOIN t2 ) )
5193            //                   ^ ^ ^ ^
5194            //                   | | | |
5195            //                   | | | |
5196            //                   | | | (4) belongs to a SetExpr::Query inside the subquery
5197            //                   | | (3) starts a derived table (subquery)
5198            //                   | (2) starts a nested join
5199            //                   (1) an additional set of parens around a nested join
5200            //
5201
5202            // It can only be a subquery. We don't use `maybe_parse` so that a meaningful error can
5203            // be returned.
5204            match self.peek_token().token {
5205                Token::Word(w)
5206                    if [Keyword::SELECT, Keyword::WITH, Keyword::VALUES].contains(&w.keyword) =>
5207                {
5208                    return self.parse_derived_table_factor(NotLateral);
5209                }
5210                _ => {}
5211            };
5212            // It can still be a subquery, e.g., the case (3) in the example above:
5213            // (SELECT 1) UNION (SELECT 2)
5214            // TODO: how to produce a good error message here?
5215            if self.peek_token() == Token::LParen {
5216                return_ok_if_some!(
5217                    self.maybe_parse(|parser| parser.parse_derived_table_factor(NotLateral))
5218                );
5219            }
5220
5221            // A parsing error from `parse_derived_table_factor` indicates that the '(' we've
5222            // recently consumed does not start a derived table (cases 1, 2, or 4).
5223            // `maybe_parse` will ignore such an error and rewind to be after the opening '('.
5224
5225            // Inside the parentheses we expect to find an (A) table factor
5226            // followed by some joins or (B) another level of nesting.
5227            let table_and_joins = self.parse_table_and_joins()?;
5228
5229            #[allow(clippy::if_same_then_else)]
5230            if !table_and_joins.joins.is_empty() {
5231                self.expect_token(&Token::RParen)?;
5232                Ok(TableFactor::NestedJoin(Box::new(table_and_joins))) // (A)
5233            } else if let TableFactor::NestedJoin(_) = &table_and_joins.relation {
5234                // (B): `table_and_joins` (what we found inside the parentheses)
5235                // is a nested join `(foo JOIN bar)`, not followed by other joins.
5236                self.expect_token(&Token::RParen)?;
5237                Ok(TableFactor::NestedJoin(Box::new(table_and_joins)))
5238            } else {
5239                // The SQL spec prohibits derived tables and bare tables from
5240                // appearing alone in parentheses (e.g. `FROM (mytable)`)
5241                parser_err!(
5242                    "Expected joined table, found: {table_and_joins}, next_token: {}",
5243                    self.peek_token()
5244                );
5245            }
5246        } else {
5247            let name = self.parse_object_name()?;
5248            if self.peek_token() == Token::LParen {
5249                // table-valued function
5250
5251                let arg_list = self.parse_argument_list()?;
5252                if arg_list.distinct {
5253                    parser_err!("DISTINCT is not supported in table-valued function calls");
5254                }
5255                if !arg_list.order_by.is_empty() {
5256                    parser_err!("ORDER BY is not supported in table-valued function calls");
5257                }
5258                if arg_list.ignore_nulls {
5259                    parser_err!("IGNORE NULLS is not supported in table-valued function calls");
5260                }
5261
5262                let args = arg_list.args;
5263                let with_ordinality = self.parse_keywords(&[Keyword::WITH, Keyword::ORDINALITY]);
5264                let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
5265
5266                Ok(TableFactor::TableFunction {
5267                    name,
5268                    alias,
5269                    args,
5270                    with_ordinality,
5271                })
5272            } else {
5273                let as_of = opt(Self::parse_as_of).parse_next(self)?;
5274                let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
5275                Ok(TableFactor::Table { name, alias, as_of })
5276            }
5277        }
5278    }
5279
5280    pub fn parse_derived_table_factor(&mut self, lateral: IsLateral) -> ModalResult<TableFactor> {
5281        let subquery = Box::new(self.parse_query()?);
5282        self.expect_token(&Token::RParen)?;
5283        let alias = self.parse_optional_table_alias(keywords::RESERVED_FOR_TABLE_ALIAS)?;
5284        Ok(TableFactor::Derived {
5285            lateral: match lateral {
5286                Lateral => true,
5287                NotLateral => false,
5288            },
5289            subquery,
5290            alias,
5291        })
5292    }
5293
5294    fn parse_join_constraint(&mut self, natural: bool) -> ModalResult<JoinConstraint> {
5295        if natural {
5296            Ok(JoinConstraint::Natural)
5297        } else if self.parse_keyword(Keyword::ON) {
5298            let constraint = self.parse_expr()?;
5299            Ok(JoinConstraint::On(constraint))
5300        } else if self.parse_keyword(Keyword::USING) {
5301            let columns = self.parse_parenthesized_column_list(Mandatory)?;
5302            Ok(JoinConstraint::Using(columns))
5303        } else {
5304            Ok(JoinConstraint::None)
5305            // self.expected("ON, or USING after JOIN")
5306        }
5307    }
5308
5309    /// Parse a GRANT statement.
5310    pub fn parse_grant(&mut self) -> ModalResult<Statement> {
5311        let (privileges, objects) = self.parse_grant_revoke_privileges_objects()?;
5312
5313        self.expect_keyword(Keyword::TO)?;
5314        let grantees = self.parse_comma_separated(Parser::parse_identifier)?;
5315
5316        let with_grant_option =
5317            self.parse_keywords(&[Keyword::WITH, Keyword::GRANT, Keyword::OPTION]);
5318
5319        let granted_by = self
5320            .parse_keywords(&[Keyword::GRANTED, Keyword::BY])
5321            .then(|| self.parse_identifier().unwrap());
5322
5323        Ok(Statement::Grant {
5324            privileges,
5325            objects,
5326            grantees,
5327            with_grant_option,
5328            granted_by,
5329        })
5330    }
5331
5332    fn parse_privileges(&mut self) -> ModalResult<Privileges> {
5333        let privileges = if self.parse_keyword(Keyword::ALL) {
5334            Privileges::All {
5335                with_privileges_keyword: self.parse_keyword(Keyword::PRIVILEGES),
5336            }
5337        } else {
5338            Privileges::Actions(
5339                self.parse_comma_separated(Parser::parse_grant_permission)?
5340                    .into_iter()
5341                    .map(|(kw, columns)| match kw {
5342                        Keyword::CONNECT => Action::Connect,
5343                        Keyword::CREATE => Action::Create,
5344                        Keyword::DELETE => Action::Delete,
5345                        Keyword::EXECUTE => Action::Execute,
5346                        Keyword::INSERT => Action::Insert { columns },
5347                        Keyword::REFERENCES => Action::References { columns },
5348                        Keyword::SELECT => Action::Select { columns },
5349                        Keyword::TEMPORARY => Action::Temporary,
5350                        Keyword::TRIGGER => Action::Trigger,
5351                        Keyword::TRUNCATE => Action::Truncate,
5352                        Keyword::UPDATE => Action::Update { columns },
5353                        Keyword::USAGE => Action::Usage,
5354                        _ => unreachable!(),
5355                    })
5356                    .collect(),
5357            )
5358        };
5359
5360        Ok(privileges)
5361    }
5362
5363    fn parse_grant_revoke_privileges_objects(&mut self) -> ModalResult<(Privileges, GrantObjects)> {
5364        let privileges = self.parse_privileges()?;
5365
5366        self.expect_keyword(Keyword::ON)?;
5367
5368        let objects = if self.parse_keywords(&[
5369            Keyword::ALL,
5370            Keyword::TABLES,
5371            Keyword::IN,
5372            Keyword::SCHEMA,
5373        ]) {
5374            GrantObjects::AllTablesInSchema {
5375                schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5376            }
5377        } else if self.parse_keywords(&[
5378            Keyword::ALL,
5379            Keyword::SEQUENCES,
5380            Keyword::IN,
5381            Keyword::SCHEMA,
5382        ]) {
5383            GrantObjects::AllSequencesInSchema {
5384                schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5385            }
5386        } else if self.parse_keywords(&[
5387            Keyword::ALL,
5388            Keyword::SOURCES,
5389            Keyword::IN,
5390            Keyword::SCHEMA,
5391        ]) {
5392            GrantObjects::AllSourcesInSchema {
5393                schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5394            }
5395        } else if self.parse_keywords(&[Keyword::ALL, Keyword::SINKS, Keyword::IN, Keyword::SCHEMA])
5396        {
5397            GrantObjects::AllSinksInSchema {
5398                schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5399            }
5400        } else if self.parse_keywords(&[
5401            Keyword::ALL,
5402            Keyword::MATERIALIZED,
5403            Keyword::VIEWS,
5404            Keyword::IN,
5405            Keyword::SCHEMA,
5406        ]) {
5407            GrantObjects::AllMviewsInSchema {
5408                schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5409            }
5410        } else if self.parse_keywords(&[Keyword::ALL, Keyword::VIEWS, Keyword::IN, Keyword::SCHEMA])
5411        {
5412            GrantObjects::AllViewsInSchema {
5413                schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5414            }
5415        } else if self.parse_keywords(&[
5416            Keyword::ALL,
5417            Keyword::FUNCTIONS,
5418            Keyword::IN,
5419            Keyword::SCHEMA,
5420        ]) {
5421            GrantObjects::AllFunctionsInSchema {
5422                schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5423            }
5424        } else if self.parse_keywords(&[
5425            Keyword::ALL,
5426            Keyword::SECRETS,
5427            Keyword::IN,
5428            Keyword::SCHEMA,
5429        ]) {
5430            GrantObjects::AllSecretsInSchema {
5431                schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5432            }
5433        } else if self.parse_keywords(&[
5434            Keyword::ALL,
5435            Keyword::CONNECTIONS,
5436            Keyword::IN,
5437            Keyword::SCHEMA,
5438        ]) {
5439            GrantObjects::AllConnectionsInSchema {
5440                schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5441            }
5442        } else if self.parse_keywords(&[
5443            Keyword::ALL,
5444            Keyword::SUBSCRIPTIONS,
5445            Keyword::IN,
5446            Keyword::SCHEMA,
5447        ]) {
5448            GrantObjects::AllSubscriptionsInSchema {
5449                schemas: self.parse_comma_separated(Parser::parse_object_name)?,
5450            }
5451        } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEW]) {
5452            GrantObjects::Mviews(self.parse_comma_separated(Parser::parse_object_name)?)
5453        } else {
5454            let object_type = self.parse_one_of_keywords(&[
5455                Keyword::SEQUENCE,
5456                Keyword::DATABASE,
5457                Keyword::SCHEMA,
5458                Keyword::TABLE,
5459                Keyword::SOURCE,
5460                Keyword::SINK,
5461                Keyword::VIEW,
5462                Keyword::SUBSCRIPTION,
5463                Keyword::FUNCTION,
5464                Keyword::CONNECTION,
5465                Keyword::SECRET,
5466            ]);
5467            if let Some(Keyword::FUNCTION) = object_type {
5468                let func_descs = self.parse_comma_separated(Parser::parse_function_desc)?;
5469                GrantObjects::Functions(func_descs)
5470            } else {
5471                let objects = self.parse_comma_separated(Parser::parse_object_name);
5472                match object_type {
5473                    Some(Keyword::DATABASE) => GrantObjects::Databases(objects?),
5474                    Some(Keyword::SCHEMA) => GrantObjects::Schemas(objects?),
5475                    Some(Keyword::SEQUENCE) => GrantObjects::Sequences(objects?),
5476                    Some(Keyword::SOURCE) => GrantObjects::Sources(objects?),
5477                    Some(Keyword::SINK) => GrantObjects::Sinks(objects?),
5478                    Some(Keyword::VIEW) => GrantObjects::Views(objects?),
5479                    Some(Keyword::SUBSCRIPTION) => GrantObjects::Subscriptions(objects?),
5480                    Some(Keyword::CONNECTION) => GrantObjects::Connections(objects?),
5481                    Some(Keyword::SECRET) => GrantObjects::Secrets(objects?),
5482                    Some(Keyword::TABLE) | None => GrantObjects::Tables(objects?),
5483                    _ => unreachable!(),
5484                }
5485            }
5486        };
5487
5488        Ok((privileges, objects))
5489    }
5490
5491    fn parse_grant_permission(&mut self) -> ModalResult<(Keyword, Option<Vec<Ident>>)> {
5492        let kw = self.expect_one_of_keywords(&[
5493            Keyword::CONNECT,
5494            Keyword::CREATE,
5495            Keyword::DELETE,
5496            Keyword::EXECUTE,
5497            Keyword::INSERT,
5498            Keyword::REFERENCES,
5499            Keyword::SELECT,
5500            Keyword::TEMPORARY,
5501            Keyword::TRIGGER,
5502            Keyword::TRUNCATE,
5503            Keyword::UPDATE,
5504            Keyword::USAGE,
5505        ])?;
5506        let columns = match kw {
5507            Keyword::INSERT | Keyword::REFERENCES | Keyword::SELECT | Keyword::UPDATE => {
5508                let columns = self.parse_parenthesized_column_list(Optional)?;
5509                if columns.is_empty() {
5510                    None
5511                } else {
5512                    Some(columns)
5513                }
5514            }
5515            _ => None,
5516        };
5517        Ok((kw, columns))
5518    }
5519
5520    /// Parse a REVOKE statement
5521    pub fn parse_revoke(&mut self) -> ModalResult<Statement> {
5522        let revoke_grant_option =
5523            self.parse_keywords(&[Keyword::GRANT, Keyword::OPTION, Keyword::FOR]);
5524        let (privileges, objects) = self.parse_grant_revoke_privileges_objects()?;
5525
5526        self.expect_keyword(Keyword::FROM)?;
5527        let grantees = self.parse_comma_separated(Parser::parse_identifier)?;
5528
5529        let granted_by = self
5530            .parse_keywords(&[Keyword::GRANTED, Keyword::BY])
5531            .then(|| self.parse_identifier().unwrap());
5532
5533        let cascade = self.parse_keyword(Keyword::CASCADE);
5534        let restrict = self.parse_keyword(Keyword::RESTRICT);
5535        if cascade && restrict {
5536            parser_err!("Cannot specify both CASCADE and RESTRICT in REVOKE");
5537        }
5538
5539        Ok(Statement::Revoke {
5540            privileges,
5541            objects,
5542            grantees,
5543            granted_by,
5544            revoke_grant_option,
5545            cascade,
5546        })
5547    }
5548
5549    fn parse_privilege_object_types(&mut self) -> ModalResult<PrivilegeObjectType> {
5550        let object_type = if self.parse_keyword(Keyword::TABLES) {
5551            PrivilegeObjectType::Tables
5552        } else if self.parse_keyword(Keyword::SOURCES) {
5553            PrivilegeObjectType::Sources
5554        } else if self.parse_keyword(Keyword::SINKS) {
5555            PrivilegeObjectType::Sinks
5556        } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEWS]) {
5557            PrivilegeObjectType::Mviews
5558        } else if self.parse_keyword(Keyword::VIEWS) {
5559            PrivilegeObjectType::Views
5560        } else if self.parse_keyword(Keyword::FUNCTIONS) {
5561            PrivilegeObjectType::Functions
5562        } else if self.parse_keyword(Keyword::SECRETS) {
5563            PrivilegeObjectType::Secrets
5564        } else if self.parse_keyword(Keyword::CONNECTIONS) {
5565            PrivilegeObjectType::Connections
5566        } else if self.parse_keyword(Keyword::SUBSCRIPTIONS) {
5567            PrivilegeObjectType::Subscriptions
5568        } else if self.parse_keyword(Keyword::SCHEMAS) {
5569            PrivilegeObjectType::Schemas
5570        } else {
5571            return self.expected("TABLES, SOURCES, SINKS, MATERIALIZED VIEWS, VIEWS, FUNCTIONS, SECRETS, CONNECTIONS, SUBSCRIPTIONS or SCHEMAS");
5572        };
5573
5574        Ok(object_type)
5575    }
5576
5577    pub fn parse_alter_default_privileges(&mut self) -> ModalResult<Statement> {
5578        // [ FOR USER target_user [, ...] ]
5579        let target_users = if self.parse_keyword(Keyword::FOR) {
5580            self.expect_keyword(Keyword::USER)?;
5581            Some(self.parse_comma_separated(Parser::parse_identifier)?)
5582        } else {
5583            None
5584        };
5585
5586        // [ IN SCHEMA schema_name [, ...] ]
5587        let schema_names = if self.parse_keywords(&[Keyword::IN, Keyword::SCHEMA]) {
5588            Some(self.parse_comma_separated(Parser::parse_object_name)?)
5589        } else {
5590            None
5591        };
5592        let keyword = self.expect_one_of_keywords(&[Keyword::GRANT, Keyword::REVOKE])?;
5593        let for_grant = keyword == Keyword::GRANT;
5594        if for_grant {
5595            let privileges = self.parse_privileges()?;
5596            self.expect_keyword(Keyword::ON)?;
5597            let object_type = self.parse_privilege_object_types()?;
5598            if schema_names.is_some() && object_type == PrivilegeObjectType::Schemas {
5599                parser_err!("cannot use IN SCHEMA clause when using GRANT/REVOKE ON SCHEMAS");
5600            }
5601            self.expect_keyword(Keyword::TO)?;
5602            let grantees = self.parse_comma_separated(Parser::parse_identifier)?;
5603
5604            let with_grant_option =
5605                self.parse_keywords(&[Keyword::WITH, Keyword::GRANT, Keyword::OPTION]);
5606
5607            Ok(Statement::AlterDefaultPrivileges {
5608                target_users,
5609                schema_names,
5610                operation: DefaultPrivilegeOperation::Grant {
5611                    privileges,
5612                    object_type,
5613                    grantees,
5614                    with_grant_option,
5615                },
5616            })
5617        } else {
5618            let revoke_grant_option =
5619                self.parse_keywords(&[Keyword::GRANT, Keyword::OPTION, Keyword::FOR]);
5620            let privileges = self.parse_privileges()?;
5621            self.expect_keyword(Keyword::ON)?;
5622            let object_type = self.parse_privilege_object_types()?;
5623            if schema_names.is_some() && object_type == PrivilegeObjectType::Schemas {
5624                parser_err!("cannot use IN SCHEMA clause when using GRANT/REVOKE ON SCHEMAS");
5625            }
5626            self.expect_keyword(Keyword::FROM)?;
5627            let grantees = self.parse_comma_separated(Parser::parse_identifier)?;
5628            let cascade = self.parse_keyword(Keyword::CASCADE);
5629            let restrict = self.parse_keyword(Keyword::RESTRICT);
5630            if cascade && restrict {
5631                parser_err!("Cannot specify both CASCADE and RESTRICT in REVOKE");
5632            }
5633
5634            Ok(Statement::AlterDefaultPrivileges {
5635                target_users,
5636                schema_names,
5637                operation: DefaultPrivilegeOperation::Revoke {
5638                    privileges,
5639                    object_type,
5640                    grantees,
5641                    revoke_grant_option,
5642                    cascade,
5643                },
5644            })
5645        }
5646    }
5647
5648    /// Parse an INSERT statement
5649    pub fn parse_insert(&mut self) -> ModalResult<Statement> {
5650        self.expect_keyword(Keyword::INTO)?;
5651
5652        let table_name = self.parse_object_name()?;
5653        let columns = self.parse_parenthesized_column_list(Optional)?;
5654
5655        let source = Box::new(self.parse_query()?);
5656        let returning = self.parse_returning(Optional)?;
5657        Ok(Statement::Insert {
5658            table_name,
5659            columns,
5660            source,
5661            returning,
5662        })
5663    }
5664
5665    pub fn parse_update(&mut self) -> ModalResult<Statement> {
5666        let table_name = self.parse_object_name()?;
5667
5668        self.expect_keyword(Keyword::SET)?;
5669        let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
5670        let selection = if self.parse_keyword(Keyword::WHERE) {
5671            Some(self.parse_expr()?)
5672        } else {
5673            None
5674        };
5675        let returning = self.parse_returning(Optional)?;
5676        Ok(Statement::Update {
5677            table_name,
5678            assignments,
5679            selection,
5680            returning,
5681        })
5682    }
5683
5684    /// Parse a `var = expr` assignment, used in an UPDATE statement
5685    pub fn parse_assignment(&mut self) -> ModalResult<Assignment> {
5686        let id = self.parse_identifiers_non_keywords()?;
5687        self.expect_token(&Token::Eq)?;
5688
5689        let value = if self.parse_keyword(Keyword::DEFAULT) {
5690            AssignmentValue::Default
5691        } else {
5692            AssignmentValue::Expr(self.parse_expr()?)
5693        };
5694
5695        Ok(Assignment { id, value })
5696    }
5697
5698    /// Parse a `[VARIADIC] name => expr`.
5699    fn parse_function_args(&mut self) -> ModalResult<(bool, FunctionArg)> {
5700        let variadic = self.parse_keyword(Keyword::VARIADIC);
5701        let arg = if self.peek_nth_token(1) == Token::RArrow {
5702            let name = self.parse_identifier()?;
5703
5704            self.expect_token(&Token::RArrow)?;
5705            let arg = self.parse_wildcard_or_expr()?.into();
5706
5707            FunctionArg::Named { name, arg }
5708        } else {
5709            FunctionArg::Unnamed(self.parse_wildcard_or_expr()?.into())
5710        };
5711        Ok((variadic, arg))
5712    }
5713
5714    pub fn parse_argument_list(&mut self) -> ModalResult<FunctionArgList> {
5715        self.expect_token(&Token::LParen)?;
5716        if self.consume_token(&Token::RParen) {
5717            Ok(FunctionArgList::empty())
5718        } else {
5719            let distinct = self.parse_all_or_distinct()?;
5720            let args = self.parse_comma_separated(Parser::parse_function_args)?;
5721            if args
5722                .iter()
5723                .take(args.len() - 1)
5724                .any(|(variadic, _)| *variadic)
5725            {
5726                parser_err!("VARIADIC argument must be the last");
5727            }
5728            let variadic = args.last().map(|(variadic, _)| *variadic).unwrap_or(false);
5729            let args = args.into_iter().map(|(_, arg)| arg).collect();
5730
5731            let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
5732                self.parse_comma_separated(Parser::parse_order_by_expr)?
5733            } else {
5734                vec![]
5735            };
5736
5737            let ignore_nulls = self.parse_keywords(&[Keyword::IGNORE, Keyword::NULLS]);
5738
5739            let arg_list = FunctionArgList {
5740                distinct,
5741                args,
5742                variadic,
5743                order_by,
5744                ignore_nulls,
5745            };
5746
5747            self.expect_token(&Token::RParen)?;
5748            Ok(arg_list)
5749        }
5750    }
5751
5752    /// Parse a comma-delimited list of projections after SELECT
5753    pub fn parse_select_item(&mut self) -> ModalResult<SelectItem> {
5754        match self.parse_wildcard_or_expr()? {
5755            WildcardOrExpr::Expr(expr) => self
5756                .parse_optional_alias(keywords::RESERVED_FOR_COLUMN_ALIAS)
5757                .map(|alias| match alias {
5758                    Some(alias) => SelectItem::ExprWithAlias { expr, alias },
5759                    None => SelectItem::UnnamedExpr(expr),
5760                }),
5761            WildcardOrExpr::QualifiedWildcard(prefix, except) => {
5762                Ok(SelectItem::QualifiedWildcard(prefix, except))
5763            }
5764            WildcardOrExpr::ExprQualifiedWildcard(expr, prefix) => {
5765                Ok(SelectItem::ExprQualifiedWildcard(expr, prefix))
5766            }
5767            WildcardOrExpr::Wildcard(except) => Ok(SelectItem::Wildcard(except)),
5768        }
5769    }
5770
5771    /// Parse an expression, optionally followed by ASC or DESC (used in ORDER BY)
5772    pub fn parse_order_by_expr(&mut self) -> ModalResult<OrderByExpr> {
5773        let expr = self.parse_expr()?;
5774
5775        let asc = if self.parse_keyword(Keyword::ASC) {
5776            Some(true)
5777        } else if self.parse_keyword(Keyword::DESC) {
5778            Some(false)
5779        } else {
5780            None
5781        };
5782
5783        let nulls_first = if self.parse_keywords(&[Keyword::NULLS, Keyword::FIRST]) {
5784            Some(true)
5785        } else if self.parse_keywords(&[Keyword::NULLS, Keyword::LAST]) {
5786            Some(false)
5787        } else {
5788            None
5789        };
5790
5791        Ok(OrderByExpr {
5792            expr,
5793            asc,
5794            nulls_first,
5795        })
5796    }
5797
5798    /// Parse a LIMIT clause
5799    pub fn parse_limit(&mut self) -> ModalResult<Option<Expr>> {
5800        if self.parse_keyword(Keyword::ALL) {
5801            Ok(None)
5802        } else {
5803            let expr = self.parse_expr()?;
5804            Ok(Some(expr))
5805        }
5806    }
5807
5808    /// Parse an OFFSET clause
5809    pub fn parse_offset(&mut self) -> ModalResult<String> {
5810        let value = self.parse_number_value()?;
5811        // TODO(Kexiang): support LIMIT expr
5812        if self.consume_token(&Token::DoubleColon) {
5813            self.expect_keyword(Keyword::BIGINT)?;
5814        }
5815        _ = self.parse_one_of_keywords(&[Keyword::ROW, Keyword::ROWS]);
5816        Ok(value)
5817    }
5818
5819    /// Parse a FETCH clause
5820    pub fn parse_fetch(&mut self) -> ModalResult<Fetch> {
5821        self.expect_one_of_keywords(&[Keyword::FIRST, Keyword::NEXT])?;
5822        let quantity = if self
5823            .parse_one_of_keywords(&[Keyword::ROW, Keyword::ROWS])
5824            .is_some()
5825        {
5826            None
5827        } else {
5828            let quantity = self.parse_number_value()?;
5829            self.expect_one_of_keywords(&[Keyword::ROW, Keyword::ROWS])?;
5830            Some(quantity)
5831        };
5832        let with_ties = if self.parse_keyword(Keyword::ONLY) {
5833            false
5834        } else if self.parse_keywords(&[Keyword::WITH, Keyword::TIES]) {
5835            true
5836        } else {
5837            return self.expected("one of ONLY or WITH TIES");
5838        };
5839        Ok(Fetch {
5840            with_ties,
5841            quantity,
5842        })
5843    }
5844
5845    pub fn parse_values(&mut self) -> ModalResult<Values> {
5846        let values = self.parse_comma_separated(|parser| {
5847            parser.expect_token(&Token::LParen)?;
5848            let exprs = parser.parse_comma_separated(Parser::parse_expr)?;
5849            parser.expect_token(&Token::RParen)?;
5850            Ok(exprs)
5851        })?;
5852        Ok(Values(values))
5853    }
5854
5855    pub fn parse_start_transaction(&mut self) -> ModalResult<Statement> {
5856        self.expect_keyword(Keyword::TRANSACTION)?;
5857        Ok(Statement::StartTransaction {
5858            modes: self.parse_transaction_modes()?,
5859        })
5860    }
5861
5862    pub fn parse_begin(&mut self) -> ModalResult<Statement> {
5863        let _ = self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK]);
5864        Ok(Statement::Begin {
5865            modes: self.parse_transaction_modes()?,
5866        })
5867    }
5868
5869    pub fn parse_transaction_modes(&mut self) -> ModalResult<Vec<TransactionMode>> {
5870        let mut modes = vec![];
5871        let mut required = false;
5872        loop {
5873            let mode = if self.parse_keywords(&[Keyword::ISOLATION, Keyword::LEVEL]) {
5874                let iso_level = if self.parse_keywords(&[Keyword::READ, Keyword::UNCOMMITTED]) {
5875                    TransactionIsolationLevel::ReadUncommitted
5876                } else if self.parse_keywords(&[Keyword::READ, Keyword::COMMITTED]) {
5877                    TransactionIsolationLevel::ReadCommitted
5878                } else if self.parse_keywords(&[Keyword::REPEATABLE, Keyword::READ]) {
5879                    TransactionIsolationLevel::RepeatableRead
5880                } else if self.parse_keyword(Keyword::SERIALIZABLE) {
5881                    TransactionIsolationLevel::Serializable
5882                } else {
5883                    self.expected("isolation level")?
5884                };
5885                TransactionMode::IsolationLevel(iso_level)
5886            } else if self.parse_keywords(&[Keyword::READ, Keyword::ONLY]) {
5887                TransactionMode::AccessMode(TransactionAccessMode::ReadOnly)
5888            } else if self.parse_keywords(&[Keyword::READ, Keyword::WRITE]) {
5889                TransactionMode::AccessMode(TransactionAccessMode::ReadWrite)
5890            } else if required {
5891                self.expected("transaction mode")?
5892            } else {
5893                break;
5894            };
5895            modes.push(mode);
5896            // ANSI requires a comma after each transaction mode, but
5897            // PostgreSQL, for historical reasons, does not. We follow
5898            // PostgreSQL in making the comma optional, since that is strictly
5899            // more general.
5900            required = self.consume_token(&Token::Comma);
5901        }
5902        Ok(modes)
5903    }
5904
5905    pub fn parse_commit(&mut self) -> ModalResult<Statement> {
5906        Ok(Statement::Commit {
5907            chain: self.parse_commit_rollback_chain()?,
5908        })
5909    }
5910
5911    pub fn parse_rollback(&mut self) -> ModalResult<Statement> {
5912        Ok(Statement::Rollback {
5913            chain: self.parse_commit_rollback_chain()?,
5914        })
5915    }
5916
5917    pub fn parse_commit_rollback_chain(&mut self) -> ModalResult<bool> {
5918        let _ = self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK]);
5919        if self.parse_keyword(Keyword::AND) {
5920            let chain = !self.parse_keyword(Keyword::NO);
5921            self.expect_keyword(Keyword::CHAIN)?;
5922            Ok(chain)
5923        } else {
5924            Ok(false)
5925        }
5926    }
5927
5928    fn parse_deallocate(&mut self) -> ModalResult<Statement> {
5929        let prepare = self.parse_keyword(Keyword::PREPARE);
5930        let name = if self.parse_keyword(Keyword::ALL) {
5931            None
5932        } else {
5933            Some(self.parse_identifier()?)
5934        };
5935        Ok(Statement::Deallocate { name, prepare })
5936    }
5937
5938    fn parse_execute(&mut self) -> ModalResult<Statement> {
5939        let name = self.parse_identifier()?;
5940
5941        let mut parameters = vec![];
5942        if self.consume_token(&Token::LParen) {
5943            parameters = self.parse_comma_separated(Parser::parse_expr)?;
5944            self.expect_token(&Token::RParen)?;
5945        }
5946
5947        Ok(Statement::Execute { name, parameters })
5948    }
5949
5950    fn parse_prepare(&mut self) -> ModalResult<Statement> {
5951        let name = self.parse_identifier()?;
5952
5953        let mut data_types = vec![];
5954        if self.consume_token(&Token::LParen) {
5955            data_types = self.parse_comma_separated(Parser::parse_data_type)?;
5956            self.expect_token(&Token::RParen)?;
5957        }
5958
5959        self.expect_keyword(Keyword::AS)?;
5960        let statement = Box::new(self.parse_statement()?);
5961        Ok(Statement::Prepare {
5962            name,
5963            data_types,
5964            statement,
5965        })
5966    }
5967
5968    fn parse_comment(&mut self) -> ModalResult<Statement> {
5969        self.expect_keyword(Keyword::ON)?;
5970        let checkpoint = *self;
5971        let token = self.next_token();
5972
5973        let (object_type, object_name) = match token.token {
5974            Token::Word(w) if w.keyword == Keyword::COLUMN => {
5975                let object_name = self.parse_object_name()?;
5976                (CommentObject::Column, object_name)
5977            }
5978            Token::Word(w) if w.keyword == Keyword::TABLE => {
5979                let object_name = self.parse_object_name()?;
5980                (CommentObject::Table, object_name)
5981            }
5982            _ => self.expected_at(checkpoint, "comment object_type")?,
5983        };
5984
5985        self.expect_keyword(Keyword::IS)?;
5986        let comment = if self.parse_keyword(Keyword::NULL) {
5987            None
5988        } else {
5989            Some(self.parse_literal_string()?)
5990        };
5991        Ok(Statement::Comment {
5992            object_type,
5993            object_name,
5994            comment,
5995        })
5996    }
5997
5998    fn parse_use(&mut self) -> ModalResult<Statement> {
5999        let db_name = self.parse_object_name()?;
6000        Ok(Statement::Use { db_name })
6001    }
6002
6003    /// Parse a named window definition for the WINDOW clause
6004    pub fn parse_named_window(&mut self) -> ModalResult<NamedWindow> {
6005        let name = self.parse_identifier()?;
6006        self.expect_keywords(&[Keyword::AS])?;
6007        self.expect_token(&Token::LParen)?;
6008        let window_spec = self.parse_window_spec()?;
6009        self.expect_token(&Token::RParen)?;
6010        Ok(NamedWindow { name, window_spec })
6011    }
6012
6013    /// Parse a window specification (contents of OVER clause or WINDOW clause)
6014    pub fn parse_window_spec(&mut self) -> ModalResult<WindowSpec> {
6015        let partition_by = if self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
6016            self.parse_comma_separated(Parser::parse_expr)?
6017        } else {
6018            vec![]
6019        };
6020        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
6021            self.parse_comma_separated(Parser::parse_order_by_expr)?
6022        } else {
6023            vec![]
6024        };
6025        let window_frame = if !self.peek_token().eq(&Token::RParen) {
6026            Some(self.parse_window_frame()?)
6027        } else {
6028            None
6029        };
6030        Ok(WindowSpec {
6031            partition_by,
6032            order_by,
6033            window_frame,
6034        })
6035    }
6036}
6037
6038impl Word {
6039    /// Convert a Word to a Identifier, return ParserError when the Word's value is a empty string.
6040    pub fn to_ident(&self) -> ModalResult<Ident> {
6041        if self.value.is_empty() {
6042            parser_err!("zero-length delimited identifier at or near \"{self}\"")
6043        } else {
6044            Ok(Ident {
6045                value: self.value.clone(),
6046                quote_style: self.quote_style,
6047            })
6048        }
6049    }
6050}
6051
6052#[cfg(test)]
6053mod tests {
6054    use super::*;
6055    use crate::test_utils::run_parser_method;
6056
6057    #[test]
6058    fn test_parse_integer_min() {
6059        let min_bigint = "-9223372036854775808";
6060        run_parser_method(min_bigint, |parser| {
6061            assert_eq!(
6062                parser.parse_expr().unwrap(),
6063                Expr::Value(Value::Number("-9223372036854775808".to_owned()))
6064            )
6065        });
6066    }
6067}