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