Skip to main content

sqlparser/parser/
mod.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    collections::{BTreeMap, BTreeSet},
19    format,
20    string::{String, ToString},
21    vec,
22    vec::Vec,
23};
24use core::{
25    fmt::{self, Display},
26    str::FromStr,
27};
28#[cfg(feature = "std")]
29use std::collections::{BTreeMap, BTreeSet};
30
31use helpers::attached_token::AttachedToken;
32
33use log::debug;
34
35use recursion::RecursionCounter;
36use IsLateral::*;
37use IsOptional::*;
38
39use crate::ast::*;
40use crate::ast::{
41    comments,
42    helpers::{
43        key_value_options::{
44            KeyValueOption, KeyValueOptionKind, KeyValueOptions, KeyValueOptionsDelimiter,
45        },
46        stmt_create_table::{CreateTableBuilder, CreateTableConfiguration},
47    },
48};
49use crate::dialect::*;
50use crate::keywords::{Keyword, ALL_KEYWORDS};
51use crate::tokenizer::*;
52use sqlparser::parser::ParserState::ColumnDefinition;
53
54/// Errors produced by the SQL parser.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum ParserError {
57    /// Error originating from the tokenizer with a message.
58    TokenizerError(String),
59    /// Generic parser error with a message.
60    ParserError(String),
61    /// Raised when a recursion depth limit is exceeded.
62    RecursionLimitExceeded,
63}
64
65// Use `Parser::expected` instead, if possible
66macro_rules! parser_err {
67    ($MSG:expr, $loc:expr) => {
68        Err(ParserError::ParserError(format!("{}{}", $MSG, $loc)))
69    };
70}
71
72mod alter;
73mod merge;
74mod procedural;
75
76/// Implementation of [`RecursionCounter`].
77///
78/// Explicitly requires only `alloc` and `core`, so recursion is limited even
79/// when the "std" feature is disabled.
80mod recursion {
81    use alloc::rc::Rc;
82    use core::cell::Cell;
83
84    use super::ParserError;
85
86    /// Tracks remaining recursion depth. This value is decremented on
87    /// each call to [`RecursionCounter::try_decrease()`], when it reaches 0 an error will
88    /// be returned.
89    ///
90    /// Note: Uses an [`alloc::rc::Rc`] and [`core::cell::Cell`] in order to satisfy the Rust
91    /// borrow checker so the automatic [`DepthGuard`] decrement a
92    /// reference to the counter.
93    ///
94    /// Note: when "recursive-protection" feature is enabled, this crate uses additional stack overflow protection
95    /// for some of its recursive methods. See [`recursive::recursive`] for more information.
96    pub(crate) struct RecursionCounter {
97        remaining_depth: Rc<Cell<usize>>,
98    }
99
100    impl RecursionCounter {
101        /// Creates a [`RecursionCounter`] with the specified maximum
102        /// depth
103        pub fn new(remaining_depth: usize) -> Self {
104            Self {
105                remaining_depth: Rc::new(remaining_depth.into()),
106            }
107        }
108
109        /// Decreases the remaining depth by 1.
110        ///
111        /// Returns [`Err`] if the remaining depth falls to 0.
112        ///
113        /// Returns a [`DepthGuard`] which will adds 1 to the
114        /// remaining depth upon drop;
115        pub fn try_decrease(&self) -> Result<DepthGuard, ParserError> {
116            let old_value = self.remaining_depth.get();
117            // ran out of space
118            if old_value == 0 {
119                Err(ParserError::RecursionLimitExceeded)
120            } else {
121                self.remaining_depth.set(old_value - 1);
122                Ok(DepthGuard::new(Rc::clone(&self.remaining_depth)))
123            }
124        }
125    }
126
127    /// Guard that increases the remaining depth by 1 on drop
128    pub struct DepthGuard {
129        remaining_depth: Rc<Cell<usize>>,
130    }
131
132    impl DepthGuard {
133        fn new(remaining_depth: Rc<Cell<usize>>) -> Self {
134            Self { remaining_depth }
135        }
136    }
137
138    impl Drop for DepthGuard {
139        fn drop(&mut self) {
140            let old_value = self.remaining_depth.get();
141            self.remaining_depth.set(old_value.saturating_add(1));
142        }
143    }
144}
145
146#[derive(PartialEq, Eq)]
147/// Indicates whether a parser element is optional or mandatory.
148pub enum IsOptional {
149    /// The element is optional.
150    Optional,
151    /// The element is mandatory.
152    Mandatory,
153}
154
155/// Indicates if a table expression is lateral.
156pub enum IsLateral {
157    /// The expression is lateral.
158    Lateral,
159    /// The expression is not lateral.
160    NotLateral,
161}
162
163/// Represents a wildcard expression used in SELECT lists.
164pub enum WildcardExpr {
165    /// A specific expression used instead of a wildcard.
166    Expr(Expr),
167    /// A qualified wildcard like `table.*`.
168    QualifiedWildcard(ObjectName),
169    /// An unqualified `*` wildcard.
170    Wildcard,
171}
172
173impl From<TokenizerError> for ParserError {
174    fn from(e: TokenizerError) -> Self {
175        ParserError::TokenizerError(e.to_string())
176    }
177}
178
179impl fmt::Display for ParserError {
180    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
181        write!(
182            f,
183            "sql parser error: {}",
184            match self {
185                ParserError::TokenizerError(s) => s,
186                ParserError::ParserError(s) => s,
187                ParserError::RecursionLimitExceeded => "recursion limit exceeded",
188            }
189        )
190    }
191}
192
193impl core::error::Error for ParserError {}
194
195// By default, allow expressions up to this deep before erroring
196const DEFAULT_REMAINING_DEPTH: usize = 50;
197
198// A constant EOF token that can be referenced.
199const EOF_TOKEN: TokenWithSpan = TokenWithSpan {
200    token: Token::EOF,
201    span: Span {
202        start: Location { line: 0, column: 0 },
203        end: Location { line: 0, column: 0 },
204    },
205};
206
207/// Composite types declarations using angle brackets syntax can be arbitrary
208/// nested such that the following declaration is possible:
209///      `ARRAY<ARRAY<INT>>`
210/// But the tokenizer recognizes the `>>` as a ShiftRight token.
211/// We work around that limitation when parsing a data type by accepting
212/// either a `>` or `>>` token in such cases, remembering which variant we
213/// matched.
214/// In the latter case having matched a `>>`, the parent type will not look to
215/// match its closing `>` as a result since that will have taken place at the
216/// child type.
217///
218/// See [Parser::parse_data_type] for details
219struct MatchedTrailingBracket(bool);
220
221impl From<bool> for MatchedTrailingBracket {
222    fn from(value: bool) -> Self {
223        Self(value)
224    }
225}
226
227/// Options that control how the [`Parser`] parses SQL text
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct ParserOptions {
230    /// Allow trailing commas in lists (e.g. `a, b,`).
231    pub trailing_commas: bool,
232    /// Controls how literal values are unescaped. See
233    /// [`Tokenizer::with_unescape`] for more details.
234    pub unescape: bool,
235    /// Controls if the parser expects a semi-colon token
236    /// between statements. Default is `true`.
237    pub require_semicolon_stmt_delimiter: bool,
238}
239
240impl Default for ParserOptions {
241    fn default() -> Self {
242        Self {
243            trailing_commas: false,
244            unescape: true,
245            require_semicolon_stmt_delimiter: true,
246        }
247    }
248}
249
250impl ParserOptions {
251    /// Create a new [`ParserOptions`]
252    pub fn new() -> Self {
253        Default::default()
254    }
255
256    /// Set if trailing commas are allowed.
257    ///
258    /// If this option is `false` (the default), the following SQL will
259    /// not parse. If the option is `true`, the SQL will parse.
260    ///
261    /// ```sql
262    ///  SELECT
263    ///   foo,
264    ///   bar,
265    ///  FROM baz
266    /// ```
267    pub fn with_trailing_commas(mut self, trailing_commas: bool) -> Self {
268        self.trailing_commas = trailing_commas;
269        self
270    }
271
272    /// Set if literal values are unescaped. Defaults to true. See
273    /// [`Tokenizer::with_unescape`] for more details.
274    pub fn with_unescape(mut self, unescape: bool) -> Self {
275        self.unescape = unescape;
276        self
277    }
278}
279
280#[derive(Copy, Clone)]
281enum ParserState {
282    /// The default state of the parser.
283    Normal,
284    /// The state when parsing a CONNECT BY expression. This allows parsing
285    /// PRIOR expressions while still allowing prior as an identifier name
286    /// in other contexts.
287    ConnectBy,
288    /// The state when parsing column definitions.  This state prohibits
289    /// NOT NULL as an alias for IS NOT NULL.  For example:
290    /// ```sql
291    /// CREATE TABLE foo (abc BIGINT NOT NULL);
292    /// ```
293    ColumnDefinition,
294}
295
296/// A SQL Parser
297///
298/// This struct is the main entry point for parsing SQL queries.
299///
300/// # Functionality:
301/// * Parsing SQL: see examples on [`Parser::new`] and [`Parser::parse_sql`]
302/// * Controlling recursion: See [`Parser::with_recursion_limit`]
303/// * Controlling parser options: See [`Parser::with_options`]
304/// * Providing your own tokens: See [`Parser::with_tokens`]
305///
306/// # Internals
307///
308/// The parser uses a [`Tokenizer`] to tokenize the input SQL string into a
309/// `Vec` of [`TokenWithSpan`]s and maintains an `index` to the current token
310/// being processed. The token vec may contain multiple SQL statements.
311///
312/// * The "current" token is the token at `index - 1`
313/// * The "next" token is the token at `index`
314/// * The "previous" token is the token at `index - 2`
315///
316/// If `index` is equal to the length of the token stream, the 'next' token is
317/// [`Token::EOF`].
318///
319/// For example, the SQL string "SELECT * FROM foo" will be tokenized into
320/// following tokens:
321/// ```text
322///  [
323///    "SELECT", // token index 0
324///    " ",      // whitespace
325///    "*",
326///    " ",
327///    "FROM",
328///    " ",
329///    "foo"
330///   ]
331/// ```
332///
333///
334pub struct Parser<'a> {
335    /// The tokens
336    tokens: Vec<TokenWithSpan>,
337    /// The index of the first unprocessed token in [`Parser::tokens`].
338    index: usize,
339    /// The current state of the parser.
340    state: ParserState,
341    /// The SQL dialect to use.
342    dialect: &'a dyn Dialect,
343    /// Additional options that allow you to mix & match behavior
344    /// otherwise constrained to certain dialects (e.g. trailing
345    /// commas) and/or format of parse (e.g. unescaping).
346    options: ParserOptions,
347    /// Ensures the stack does not overflow by limiting recursion depth.
348    recursion_counter: RecursionCounter,
349    /// Cached failures from `parse_prefix` calls that returned `Err`. See
350    /// [`Parser::parse_prefix`] for the 2^N patterns this guards.
351    failed_prefix_positions: BTreeMap<usize, ExprPrefixError>,
352    /// Cached failures from the speculative reserved-word prefix arm. See
353    /// [`Parser::parse_prefix`] for the 2^N patterns this guards.
354    failed_reserved_word_prefix_positions: BTreeMap<usize, ExprPrefixError>,
355    /// Cached failures from the speculative derived-table arm of
356    /// `parse_table_factor`. See [`Parser::parse_table_factor`] for the 2^N
357    /// pattern this guards.
358    failed_derived_table_factor_positions: BTreeSet<usize>,
359    /// Cached failures from the speculative subquery arm of [`Parser::parse_in`],
360    /// which `IN` lists nested in a leading subquery would otherwise retry at
361    /// every level, taking 2^N time. Maps the arm's start to where a parsed
362    /// query lacked its `)`.
363    failed_in_subquery_positions: BTreeMap<usize, Option<usize>>,
364}
365
366/// Copy marker for a [`ParserError`] cached by the `parse_prefix` failure
367/// memoization, so the caches hold no strings.
368#[derive(Debug, Clone, Copy)]
369enum ExprPrefixError {
370    RecursionLimitExceeded,
371    Err,
372}
373
374impl From<&ParserError> for ExprPrefixError {
375    fn from(e: &ParserError) -> Self {
376        match e {
377            ParserError::RecursionLimitExceeded => Self::RecursionLimitExceeded,
378            _ => Self::Err,
379        }
380    }
381}
382
383impl<'a> Parser<'a> {
384    /// Create a parser for a [`Dialect`]
385    ///
386    /// See also [`Parser::parse_sql`]
387    ///
388    /// Example:
389    /// ```
390    /// # use sqlparser::{parser::{Parser, ParserError}, dialect::GenericDialect};
391    /// # fn main() -> Result<(), ParserError> {
392    /// let dialect = GenericDialect{};
393    /// let statements = Parser::new(&dialect)
394    ///   .try_with_sql("SELECT * FROM foo")?
395    ///   .parse_statements()?;
396    /// # Ok(())
397    /// # }
398    /// ```
399    pub fn new(dialect: &'a dyn Dialect) -> Self {
400        Self {
401            tokens: vec![],
402            index: 0,
403            state: ParserState::Normal,
404            dialect,
405            recursion_counter: RecursionCounter::new(DEFAULT_REMAINING_DEPTH),
406            options: ParserOptions::new().with_trailing_commas(dialect.supports_trailing_commas()),
407            failed_prefix_positions: BTreeMap::new(),
408            failed_reserved_word_prefix_positions: BTreeMap::new(),
409            failed_derived_table_factor_positions: BTreeSet::new(),
410            failed_in_subquery_positions: BTreeMap::new(),
411        }
412    }
413
414    /// Specify the maximum recursion limit while parsing.
415    ///
416    /// [`Parser`] prevents stack overflows by returning
417    /// [`ParserError::RecursionLimitExceeded`] if the parser exceeds
418    /// this depth while processing the query.
419    ///
420    /// Example:
421    /// ```
422    /// # use sqlparser::{parser::{Parser, ParserError}, dialect::GenericDialect};
423    /// # fn main() -> Result<(), ParserError> {
424    /// let dialect = GenericDialect{};
425    /// let result = Parser::new(&dialect)
426    ///   .with_recursion_limit(1)
427    ///   .try_with_sql("SELECT * FROM foo WHERE (a OR (b OR (c OR d)))")?
428    ///   .parse_statements();
429    ///   assert_eq!(result, Err(ParserError::RecursionLimitExceeded));
430    /// # Ok(())
431    /// # }
432    /// ```
433    ///
434    /// Note: Versions prior to `0.63.0` did not enforce any limit in builds
435    /// without the "std" feature.
436    ///
437    /// Note: when "recursive-protection" feature is enabled, this crate uses
438    /// additional stack overflow protection for some of its recursive methods.
439    /// See [`recursive::recursive`] for more information.
440    pub fn with_recursion_limit(mut self, recursion_limit: usize) -> Self {
441        self.recursion_counter = RecursionCounter::new(recursion_limit);
442        self
443    }
444
445    /// Specify additional parser options
446    ///
447    /// [`Parser`] supports additional options ([`ParserOptions`])
448    /// that allow you to mix & match behavior otherwise constrained
449    /// to certain dialects (e.g. trailing commas).
450    ///
451    /// Example:
452    /// ```
453    /// # use sqlparser::{parser::{Parser, ParserError, ParserOptions}, dialect::GenericDialect};
454    /// # fn main() -> Result<(), ParserError> {
455    /// let dialect = GenericDialect{};
456    /// let options = ParserOptions::new()
457    ///    .with_trailing_commas(true)
458    ///    .with_unescape(false);
459    /// let result = Parser::new(&dialect)
460    ///   .with_options(options)
461    ///   .try_with_sql("SELECT a, b, COUNT(*), FROM foo GROUP BY a, b,")?
462    ///   .parse_statements();
463    ///   assert!(matches!(result, Ok(_)));
464    /// # Ok(())
465    /// # }
466    /// ```
467    pub fn with_options(mut self, options: ParserOptions) -> Self {
468        self.options = options;
469        self
470    }
471
472    /// Reset this parser to parse the specified token stream
473    pub fn with_tokens_with_locations(mut self, tokens: Vec<TokenWithSpan>) -> Self {
474        self.tokens = tokens;
475        self.index = 0;
476        self.failed_prefix_positions.clear();
477        self.failed_reserved_word_prefix_positions.clear();
478        self.failed_derived_table_factor_positions.clear();
479        self.failed_in_subquery_positions.clear();
480        self
481    }
482
483    /// Reset this parser state to parse the specified tokens
484    pub fn with_tokens(self, tokens: Vec<Token>) -> Self {
485        // Put in dummy locations
486        let tokens_with_locations: Vec<TokenWithSpan> = tokens
487            .into_iter()
488            .map(|token| TokenWithSpan {
489                token,
490                span: Span::empty(),
491            })
492            .collect();
493        self.with_tokens_with_locations(tokens_with_locations)
494    }
495
496    /// Tokenize the sql string and sets this [`Parser`]'s state to
497    /// parse the resulting tokens
498    ///
499    /// Returns an error if there was an error tokenizing the SQL string.
500    ///
501    /// See example on [`Parser::new()`] for an example
502    pub fn try_with_sql(self, sql: &str) -> Result<Self, ParserError> {
503        debug!("Parsing sql '{sql}'...");
504        let tokens = Tokenizer::new(self.dialect, sql)
505            .with_unescape(self.options.unescape)
506            .tokenize_with_location()?;
507        Ok(self.with_tokens_with_locations(tokens))
508    }
509
510    /// Parse potentially multiple statements
511    ///
512    /// Example
513    /// ```
514    /// # use sqlparser::{parser::{Parser, ParserError}, dialect::GenericDialect};
515    /// # fn main() -> Result<(), ParserError> {
516    /// let dialect = GenericDialect{};
517    /// let statements = Parser::new(&dialect)
518    ///   // Parse a SQL string with 2 separate statements
519    ///   .try_with_sql("SELECT * FROM foo; SELECT * FROM bar;")?
520    ///   .parse_statements()?;
521    /// assert_eq!(statements.len(), 2);
522    /// # Ok(())
523    /// # }
524    /// ```
525    pub fn parse_statements(&mut self) -> Result<Vec<Statement>, ParserError> {
526        let mut stmts = Vec::new();
527        let mut expecting_statement_delimiter = false;
528        loop {
529            // ignore empty statements (between successive statement delimiters)
530            while self.consume_token(&Token::SemiColon) {
531                expecting_statement_delimiter = false;
532            }
533
534            if !self.options.require_semicolon_stmt_delimiter {
535                expecting_statement_delimiter = false;
536            }
537
538            match &self.peek_token_ref().token {
539                Token::EOF => break,
540                // end of statement
541                Token::Word(word)
542                    if expecting_statement_delimiter && word.keyword == Keyword::END =>
543                {
544                    break;
545                }
546                _ => {}
547            }
548
549            if expecting_statement_delimiter {
550                return self.expected_ref("end of statement", self.peek_token_ref());
551            }
552
553            let statement = self.parse_statement()?;
554            stmts.push(statement);
555            expecting_statement_delimiter = true;
556        }
557        Ok(stmts)
558    }
559
560    /// Convenience method to parse a string with one or more SQL
561    /// statements into produce an Abstract Syntax Tree (AST).
562    ///
563    /// Example
564    /// ```
565    /// # use sqlparser::{parser::{Parser, ParserError}, dialect::GenericDialect};
566    /// # fn main() -> Result<(), ParserError> {
567    /// let dialect = GenericDialect{};
568    /// let statements = Parser::parse_sql(
569    ///   &dialect, "SELECT * FROM foo"
570    /// )?;
571    /// assert_eq!(statements.len(), 1);
572    /// # Ok(())
573    /// # }
574    /// ```
575    pub fn parse_sql(dialect: &dyn Dialect, sql: &str) -> Result<Vec<Statement>, ParserError> {
576        Parser::new(dialect).try_with_sql(sql)?.parse_statements()
577    }
578
579    /// Parses the given `sql` into an Abstract Syntax Tree (AST), returning
580    /// also encountered source code comments.
581    ///
582    /// See [Parser::parse_sql].
583    pub fn parse_sql_with_comments(
584        dialect: &'a dyn Dialect,
585        sql: &str,
586    ) -> Result<(Vec<Statement>, comments::Comments), ParserError> {
587        let mut p = Parser::new(dialect).try_with_sql(sql)?;
588        p.parse_statements().map(|stmts| (stmts, p.into_comments()))
589    }
590
591    /// Consumes this parser returning comments from the parsed token stream.
592    pub fn into_comments(self) -> comments::Comments {
593        let mut comments = comments::Comments::default();
594        for t in self.tokens.into_iter() {
595            match t.token {
596                Token::Whitespace(Whitespace::SingleLineComment { comment, prefix }) => {
597                    comments.offer(comments::CommentWithSpan {
598                        comment: comments::Comment::SingleLine {
599                            content: comment,
600                            prefix,
601                        },
602                        span: t.span,
603                    });
604                }
605                Token::Whitespace(Whitespace::MultiLineComment(comment)) => {
606                    comments.offer(comments::CommentWithSpan {
607                        comment: comments::Comment::MultiLine(comment),
608                        span: t.span,
609                    });
610                }
611                _ => {}
612            }
613        }
614        comments
615    }
616
617    /// Parse a single top-level statement (such as SELECT, INSERT, CREATE, etc.),
618    /// stopping before the statement separator, if any.
619    pub fn parse_statement(&mut self) -> Result<Statement, ParserError> {
620        let _guard = self.recursion_counter.try_decrease()?;
621
622        // allow the dialect to override statement parsing
623        if let Some(statement) = self.dialect.parse_statement(self) {
624            return statement;
625        }
626
627        let next_token = self.next_token();
628        match &next_token.token {
629            Token::Word(w) => match w.keyword {
630                Keyword::KILL => self.parse_kill(),
631                Keyword::FLUSH => self.parse_flush(),
632                Keyword::DESC => self.parse_explain(DescribeAlias::Desc),
633                Keyword::DESCRIBE => self.parse_explain(DescribeAlias::Describe),
634                Keyword::DO if self.dialect.supports_do_statement() => {
635                    self.parse_do_statement().map(Into::into)
636                }
637                Keyword::EXPLAIN => self.parse_explain(DescribeAlias::Explain),
638                Keyword::ANALYZE => self.parse_analyze().map(Into::into),
639                Keyword::CASE => {
640                    self.prev_token();
641                    self.parse_case_stmt().map(Into::into)
642                }
643                Keyword::IF => {
644                    self.prev_token();
645                    self.parse_if_stmt().map(Into::into)
646                }
647                Keyword::WHILE => {
648                    self.prev_token();
649                    self.parse_while().map(Into::into)
650                }
651                Keyword::RAISE => {
652                    self.prev_token();
653                    self.parse_raise_stmt().map(Into::into)
654                }
655                Keyword::SELECT | Keyword::WITH | Keyword::VALUES | Keyword::FROM => {
656                    self.prev_token();
657                    self.parse_query().map(Into::into)
658                }
659                Keyword::TRUNCATE => self.parse_truncate().map(Into::into),
660                Keyword::ATTACH => {
661                    if dialect_of!(self is DuckDbDialect) {
662                        self.parse_attach_duckdb_database()
663                    } else {
664                        self.parse_attach_database()
665                    }
666                }
667                Keyword::DETACH if self.dialect.supports_detach() => {
668                    self.parse_detach_duckdb_database()
669                }
670                Keyword::MSCK => self.parse_msck().map(Into::into),
671                Keyword::CREATE => self.parse_create(),
672                Keyword::CACHE => self.parse_cache_table(),
673                Keyword::DROP => self.parse_drop(),
674                Keyword::DISCARD => self.parse_discard(),
675                Keyword::DECLARE => self.parse_declare(),
676                Keyword::FETCH => self.parse_fetch_statement(),
677                Keyword::DELETE => self.parse_delete(next_token),
678                Keyword::INSERT => self.parse_insert(next_token),
679                Keyword::REPLACE => self.parse_replace(next_token),
680                Keyword::UNCACHE => self.parse_uncache_table(),
681                Keyword::UPDATE => self.parse_update(next_token),
682                Keyword::ALTER => self.parse_alter(),
683                Keyword::CALL => self.parse_call(),
684                Keyword::COPY => self.parse_copy(),
685                Keyword::OPEN => {
686                    self.prev_token();
687                    self.parse_open()
688                }
689                Keyword::CLOSE => self.parse_close(),
690                Keyword::SET => self.parse_set(),
691                Keyword::SHOW => self.parse_show(),
692                Keyword::USE => self.parse_use(),
693                Keyword::GRANT => self.parse_grant().map(Into::into),
694                Keyword::DENY => {
695                    self.prev_token();
696                    self.parse_deny()
697                }
698                Keyword::REVOKE => self.parse_revoke().map(Into::into),
699                Keyword::START => self.parse_start_transaction(),
700                Keyword::BEGIN => self.parse_begin(),
701                Keyword::END => self.parse_end(),
702                Keyword::SAVEPOINT => self.parse_savepoint(),
703                Keyword::RELEASE => self.parse_release(),
704                Keyword::COMMIT => self.parse_commit(),
705                Keyword::RAISERROR => Ok(self.parse_raiserror()?),
706                Keyword::THROW => {
707                    self.prev_token();
708                    self.parse_throw().map(Into::into)
709                }
710                Keyword::ROLLBACK => self.parse_rollback(),
711                Keyword::ABORT => self.parse_abort(),
712                Keyword::ASSERT => self.parse_assert(),
713                // `PREPARE`, `EXECUTE` and `DEALLOCATE` are Postgres-specific
714                // syntaxes. They are used for Postgres prepared statement.
715                Keyword::DEALLOCATE => self.parse_deallocate(),
716                Keyword::EXECUTE | Keyword::EXEC => self.parse_execute(),
717                Keyword::PREPARE => self.parse_prepare(),
718                Keyword::MERGE => self.parse_merge(next_token).map(Into::into),
719                // `LISTEN`, `UNLISTEN` and `NOTIFY` are Postgres-specific
720                // syntaxes. They are used for Postgres statement.
721                Keyword::LISTEN if self.dialect.supports_listen_notify() => self.parse_listen(),
722                Keyword::UNLISTEN if self.dialect.supports_listen_notify() => self.parse_unlisten(),
723                Keyword::NOTIFY if self.dialect.supports_listen_notify() => self.parse_notify(),
724                // `PRAGMA` is sqlite specific https://www.sqlite.org/pragma.html
725                Keyword::PRAGMA => self.parse_pragma(),
726                Keyword::UNLOAD => {
727                    self.prev_token();
728                    self.parse_unload()
729                }
730                Keyword::RENAME => self.parse_rename(),
731                // `INSTALL` is duckdb specific https://duckdb.org/docs/extensions/overview
732                Keyword::INSTALL if self.dialect.supports_install() => self.parse_install(),
733                Keyword::LOAD => self.parse_load(),
734                Keyword::LOCK => {
735                    self.prev_token();
736                    self.parse_lock_statement().map(Into::into)
737                }
738                Keyword::OPTIMIZE if self.dialect.supports_optimize_table() => {
739                    self.parse_optimize_table()
740                }
741                // `COMMENT` is snowflake specific https://docs.snowflake.com/en/sql-reference/sql/comment
742                Keyword::COMMENT if self.dialect.supports_comment_on() => self.parse_comment(),
743                Keyword::PRINT => self.parse_print(),
744                // `WAITFOR` is MSSQL specific https://learn.microsoft.com/en-us/sql/t-sql/language-elements/waitfor-transact-sql
745                Keyword::WAITFOR => self.parse_waitfor(),
746                Keyword::RETURN => self.parse_return(),
747                Keyword::EXPORT => {
748                    self.prev_token();
749                    self.parse_export_data()
750                }
751                Keyword::VACUUM => {
752                    self.prev_token();
753                    self.parse_vacuum()
754                }
755                Keyword::RESET => self.parse_reset().map(Into::into),
756                _ => self.expected("an SQL statement", next_token),
757            },
758            Token::LParen => {
759                self.prev_token();
760                self.parse_query().map(Into::into)
761            }
762            _ => self.expected("an SQL statement", next_token),
763        }
764    }
765
766    /// Parse a `CASE` statement.
767    ///
768    /// See [Statement::Case]
769    pub fn parse_case_stmt(&mut self) -> Result<CaseStatement, ParserError> {
770        let case_token = self.expect_keyword(Keyword::CASE)?;
771
772        let match_expr = if self.peek_keyword(Keyword::WHEN) {
773            None
774        } else {
775            Some(self.parse_expr()?)
776        };
777
778        self.expect_keyword_is(Keyword::WHEN)?;
779        let when_blocks = self.parse_keyword_separated(Keyword::WHEN, |parser| {
780            parser.parse_conditional_statement_block(&[Keyword::WHEN, Keyword::ELSE, Keyword::END])
781        })?;
782
783        let else_block = if self.parse_keyword(Keyword::ELSE) {
784            Some(self.parse_conditional_statement_block(&[Keyword::END])?)
785        } else {
786            None
787        };
788
789        let mut end_case_token = self.expect_keyword(Keyword::END)?;
790        if self.peek_keyword(Keyword::CASE) {
791            end_case_token = self.expect_keyword(Keyword::CASE)?;
792        }
793
794        Ok(CaseStatement {
795            case_token: AttachedToken(case_token),
796            match_expr,
797            when_blocks,
798            else_block,
799            end_case_token: AttachedToken(end_case_token),
800        })
801    }
802
803    /// Parse an `IF` statement.
804    ///
805    /// See [Statement::If]
806    pub fn parse_if_stmt(&mut self) -> Result<IfStatement, ParserError> {
807        self.expect_keyword_is(Keyword::IF)?;
808        let if_block = self.parse_conditional_statement_block(&[
809            Keyword::ELSE,
810            Keyword::ELSEIF,
811            Keyword::END,
812        ])?;
813
814        let elseif_blocks = if self.parse_keyword(Keyword::ELSEIF) {
815            self.parse_keyword_separated(Keyword::ELSEIF, |parser| {
816                parser.parse_conditional_statement_block(&[
817                    Keyword::ELSEIF,
818                    Keyword::ELSE,
819                    Keyword::END,
820                ])
821            })?
822        } else {
823            vec![]
824        };
825
826        let else_block = if self.parse_keyword(Keyword::ELSE) {
827            Some(self.parse_conditional_statement_block(&[Keyword::END])?)
828        } else {
829            None
830        };
831
832        self.expect_keyword_is(Keyword::END)?;
833        let end_token = self.expect_keyword(Keyword::IF)?;
834
835        Ok(IfStatement {
836            if_block,
837            elseif_blocks,
838            else_block,
839            end_token: Some(AttachedToken(end_token)),
840        })
841    }
842
843    /// Parse a `WHILE` statement.
844    ///
845    /// See [Statement::While]
846    fn parse_while(&mut self) -> Result<WhileStatement, ParserError> {
847        self.expect_keyword_is(Keyword::WHILE)?;
848        let while_block = self.parse_conditional_statement_block(&[Keyword::END])?;
849
850        Ok(WhileStatement { while_block })
851    }
852
853    /// Parses an expression and associated list of statements
854    /// belonging to a conditional statement like `IF` or `WHEN` or `WHILE`.
855    ///
856    /// Example:
857    /// ```sql
858    /// IF condition THEN statement1; statement2;
859    /// ```
860    fn parse_conditional_statement_block(
861        &mut self,
862        terminal_keywords: &[Keyword],
863    ) -> Result<ConditionalStatementBlock, ParserError> {
864        let start_token = self.get_current_token().clone(); // self.expect_keyword(keyword)?;
865        let mut then_token = None;
866
867        let condition = match &start_token.token {
868            Token::Word(w) if w.keyword == Keyword::ELSE => None,
869            Token::Word(w) if w.keyword == Keyword::WHILE => {
870                let expr = self.parse_expr()?;
871                Some(expr)
872            }
873            _ => {
874                let expr = self.parse_expr()?;
875                then_token = Some(AttachedToken(self.expect_keyword(Keyword::THEN)?));
876                Some(expr)
877            }
878        };
879
880        let conditional_statements = self.parse_conditional_statements(terminal_keywords)?;
881
882        Ok(ConditionalStatementBlock {
883            start_token: AttachedToken(start_token),
884            condition,
885            then_token,
886            conditional_statements,
887        })
888    }
889
890    /// Parse a BEGIN/END block or a sequence of statements
891    /// This could be inside of a conditional (IF, CASE, WHILE etc.) or an object body defined optionally BEGIN/END and one or more statements.
892    pub(crate) fn parse_conditional_statements(
893        &mut self,
894        terminal_keywords: &[Keyword],
895    ) -> Result<ConditionalStatements, ParserError> {
896        let conditional_statements = if self.peek_keyword(Keyword::BEGIN) {
897            let begin_token = self.expect_keyword(Keyword::BEGIN)?;
898            let statements = self.parse_statement_list(terminal_keywords)?;
899            let end_token = self.expect_keyword(Keyword::END)?;
900
901            ConditionalStatements::BeginEnd(BeginEndStatements {
902                begin_token: AttachedToken(begin_token),
903                statements,
904                end_token: AttachedToken(end_token),
905            })
906        } else {
907            ConditionalStatements::Sequence {
908                statements: self.parse_statement_list(terminal_keywords)?,
909            }
910        };
911        Ok(conditional_statements)
912    }
913
914    /// Parse a `RAISE` statement.
915    ///
916    /// See [Statement::Raise]
917    pub fn parse_raise_stmt(&mut self) -> Result<RaiseStatement, ParserError> {
918        self.expect_keyword_is(Keyword::RAISE)?;
919
920        let value = if self.parse_keywords(&[Keyword::USING, Keyword::MESSAGE]) {
921            self.expect_token(&Token::Eq)?;
922            Some(RaiseStatementValue::UsingMessage(self.parse_expr()?))
923        } else {
924            self.maybe_parse(|parser| parser.parse_expr().map(RaiseStatementValue::Expr))?
925        };
926
927        Ok(RaiseStatement { value })
928    }
929    /// Parse a COMMENT statement.
930    ///
931    /// See [Statement::Comment]
932    pub fn parse_comment(&mut self) -> Result<Statement, ParserError> {
933        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
934
935        self.expect_keyword_is(Keyword::ON)?;
936        let token = self.next_token();
937
938        let (object_type, object_name) = match token.token {
939            Token::Word(w) if w.keyword == Keyword::COLLATION => {
940                (CommentObject::Collation, self.parse_object_name(false)?)
941            }
942            Token::Word(w) if w.keyword == Keyword::COLUMN => {
943                (CommentObject::Column, self.parse_object_name(false)?)
944            }
945            Token::Word(w) if w.keyword == Keyword::DATABASE => {
946                (CommentObject::Database, self.parse_object_name(false)?)
947            }
948            Token::Word(w) if w.keyword == Keyword::DOMAIN => {
949                (CommentObject::Domain, self.parse_object_name(false)?)
950            }
951            Token::Word(w) if w.keyword == Keyword::EXTENSION => {
952                (CommentObject::Extension, self.parse_object_name(false)?)
953            }
954            Token::Word(w) if w.keyword == Keyword::FUNCTION => {
955                (CommentObject::Function, self.parse_object_name(false)?)
956            }
957            Token::Word(w) if w.keyword == Keyword::INDEX => {
958                (CommentObject::Index, self.parse_object_name(false)?)
959            }
960            Token::Word(w) if w.keyword == Keyword::MATERIALIZED => {
961                self.expect_keyword_is(Keyword::VIEW)?;
962                (
963                    CommentObject::MaterializedView,
964                    self.parse_object_name(false)?,
965                )
966            }
967            Token::Word(w) if w.keyword == Keyword::PROCEDURE => {
968                (CommentObject::Procedure, self.parse_object_name(false)?)
969            }
970            Token::Word(w) if w.keyword == Keyword::ROLE => {
971                (CommentObject::Role, self.parse_object_name(false)?)
972            }
973            Token::Word(w) if w.keyword == Keyword::SCHEMA => {
974                (CommentObject::Schema, self.parse_object_name(false)?)
975            }
976            Token::Word(w) if w.keyword == Keyword::SEQUENCE => {
977                (CommentObject::Sequence, self.parse_object_name(false)?)
978            }
979            Token::Word(w) if w.keyword == Keyword::TABLE => {
980                (CommentObject::Table, self.parse_object_name(false)?)
981            }
982            Token::Word(w) if w.keyword == Keyword::TYPE => {
983                (CommentObject::Type, self.parse_object_name(false)?)
984            }
985            Token::Word(w) if w.keyword == Keyword::USER => {
986                (CommentObject::User, self.parse_object_name(false)?)
987            }
988            Token::Word(w) if w.keyword == Keyword::VIEW => {
989                (CommentObject::View, self.parse_object_name(false)?)
990            }
991            _ => self.expected("comment object_type", token)?,
992        };
993
994        self.expect_keyword_is(Keyword::IS)?;
995        let comment = if self.parse_keyword(Keyword::NULL) {
996            None
997        } else {
998            Some(self.parse_literal_string()?)
999        };
1000        Ok(Statement::Comment {
1001            object_type,
1002            object_name,
1003            comment,
1004            if_exists,
1005        })
1006    }
1007
1008    /// Parse `FLUSH` statement.
1009    pub fn parse_flush(&mut self) -> Result<Statement, ParserError> {
1010        let mut channel = None;
1011        let mut tables: Vec<ObjectName> = vec![];
1012        let mut read_lock = false;
1013        let mut export = false;
1014
1015        if !dialect_of!(self is MySqlDialect | GenericDialect) {
1016            return parser_err!(
1017                "Unsupported statement FLUSH",
1018                self.peek_token_ref().span.start
1019            );
1020        }
1021
1022        let location = if self.parse_keyword(Keyword::NO_WRITE_TO_BINLOG) {
1023            Some(FlushLocation::NoWriteToBinlog)
1024        } else if self.parse_keyword(Keyword::LOCAL) {
1025            Some(FlushLocation::Local)
1026        } else {
1027            None
1028        };
1029
1030        let object_type = if self.parse_keywords(&[Keyword::BINARY, Keyword::LOGS]) {
1031            FlushType::BinaryLogs
1032        } else if self.parse_keywords(&[Keyword::ENGINE, Keyword::LOGS]) {
1033            FlushType::EngineLogs
1034        } else if self.parse_keywords(&[Keyword::ERROR, Keyword::LOGS]) {
1035            FlushType::ErrorLogs
1036        } else if self.parse_keywords(&[Keyword::GENERAL, Keyword::LOGS]) {
1037            FlushType::GeneralLogs
1038        } else if self.parse_keywords(&[Keyword::HOSTS]) {
1039            FlushType::Hosts
1040        } else if self.parse_keyword(Keyword::PRIVILEGES) {
1041            FlushType::Privileges
1042        } else if self.parse_keyword(Keyword::OPTIMIZER_COSTS) {
1043            FlushType::OptimizerCosts
1044        } else if self.parse_keywords(&[Keyword::RELAY, Keyword::LOGS]) {
1045            if self.parse_keywords(&[Keyword::FOR, Keyword::CHANNEL]) {
1046                channel = Some(self.parse_object_name(false)?.to_string());
1047            }
1048            FlushType::RelayLogs
1049        } else if self.parse_keywords(&[Keyword::SLOW, Keyword::LOGS]) {
1050            FlushType::SlowLogs
1051        } else if self.parse_keyword(Keyword::STATUS) {
1052            FlushType::Status
1053        } else if self.parse_keyword(Keyword::USER_RESOURCES) {
1054            FlushType::UserResources
1055        } else if self.parse_keywords(&[Keyword::LOGS]) {
1056            FlushType::Logs
1057        } else if self.parse_keywords(&[Keyword::TABLES]) {
1058            loop {
1059                let next_token = self.next_token();
1060                match &next_token.token {
1061                    Token::Word(w) => match w.keyword {
1062                        Keyword::WITH => {
1063                            read_lock = self.parse_keywords(&[Keyword::READ, Keyword::LOCK]);
1064                        }
1065                        Keyword::FOR => {
1066                            export = self.parse_keyword(Keyword::EXPORT);
1067                        }
1068                        Keyword::NoKeyword => {
1069                            self.prev_token();
1070                            tables = self.parse_comma_separated(|p| p.parse_object_name(false))?;
1071                        }
1072                        _ => {}
1073                    },
1074                    _ => {
1075                        break;
1076                    }
1077                }
1078            }
1079
1080            FlushType::Tables
1081        } else {
1082            return self.expected_ref(
1083                "BINARY LOGS, ENGINE LOGS, ERROR LOGS, GENERAL LOGS, HOSTS, LOGS, PRIVILEGES, OPTIMIZER_COSTS,\
1084                 RELAY LOGS [FOR CHANNEL channel], SLOW LOGS, STATUS, USER_RESOURCES",
1085                self.peek_token_ref(),
1086            );
1087        };
1088
1089        Ok(Statement::Flush {
1090            object_type,
1091            location,
1092            channel,
1093            read_lock,
1094            export,
1095            tables,
1096        })
1097    }
1098
1099    /// Parse `MSCK` statement.
1100    pub fn parse_msck(&mut self) -> Result<Msck, ParserError> {
1101        let repair = self.parse_keyword(Keyword::REPAIR);
1102        self.expect_keyword_is(Keyword::TABLE)?;
1103        let table_name = self.parse_object_name(false)?;
1104        let partition_action = self
1105            .maybe_parse(|parser| {
1106                let pa = match parser.parse_one_of_keywords(&[
1107                    Keyword::ADD,
1108                    Keyword::DROP,
1109                    Keyword::SYNC,
1110                ]) {
1111                    Some(Keyword::ADD) => Some(AddDropSync::ADD),
1112                    Some(Keyword::DROP) => Some(AddDropSync::DROP),
1113                    Some(Keyword::SYNC) => Some(AddDropSync::SYNC),
1114                    _ => None,
1115                };
1116                parser.expect_keyword_is(Keyword::PARTITIONS)?;
1117                Ok(pa)
1118            })?
1119            .unwrap_or_default();
1120        Ok(Msck {
1121            repair,
1122            table_name,
1123            partition_action,
1124        })
1125    }
1126
1127    /// Parse `TRUNCATE` statement.
1128    pub fn parse_truncate(&mut self) -> Result<Truncate, ParserError> {
1129        let table = self.parse_keyword(Keyword::TABLE);
1130        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
1131
1132        let table_names = self.parse_comma_separated(|p| {
1133            let only = p.parse_keyword(Keyword::ONLY);
1134            let name = p.parse_object_name(false)?;
1135            let has_asterisk = p.consume_token(&Token::Mul);
1136            Ok(TruncateTableTarget {
1137                name,
1138                only,
1139                has_asterisk,
1140            })
1141        })?;
1142
1143        let mut partitions = None;
1144        if self.parse_keyword(Keyword::PARTITION) {
1145            self.expect_token(&Token::LParen)?;
1146            partitions = Some(self.parse_comma_separated(Parser::parse_expr)?);
1147            self.expect_token(&Token::RParen)?;
1148        }
1149
1150        let mut identity = None;
1151        let mut cascade = None;
1152
1153        if dialect_of!(self is PostgreSqlDialect | GenericDialect) {
1154            identity = if self.parse_keywords(&[Keyword::RESTART, Keyword::IDENTITY]) {
1155                Some(TruncateIdentityOption::Restart)
1156            } else if self.parse_keywords(&[Keyword::CONTINUE, Keyword::IDENTITY]) {
1157                Some(TruncateIdentityOption::Continue)
1158            } else {
1159                None
1160            };
1161
1162            cascade = self.parse_cascade_option();
1163        };
1164
1165        let on_cluster = self.parse_optional_on_cluster()?;
1166
1167        Ok(Truncate {
1168            table_names,
1169            partitions,
1170            table,
1171            if_exists,
1172            identity,
1173            cascade,
1174            on_cluster,
1175        })
1176    }
1177
1178    fn parse_cascade_option(&mut self) -> Option<CascadeOption> {
1179        if self.parse_keyword(Keyword::CASCADE) {
1180            Some(CascadeOption::Cascade)
1181        } else if self.parse_keyword(Keyword::RESTRICT) {
1182            Some(CascadeOption::Restrict)
1183        } else {
1184            None
1185        }
1186    }
1187
1188    /// Parse options for `ATTACH DUCKDB DATABASE` statement.
1189    pub fn parse_attach_duckdb_database_options(
1190        &mut self,
1191    ) -> Result<Vec<AttachDuckDBDatabaseOption>, ParserError> {
1192        if !self.consume_token(&Token::LParen) {
1193            return Ok(vec![]);
1194        }
1195
1196        let mut options = vec![];
1197        loop {
1198            if self.parse_keyword(Keyword::READ_ONLY) {
1199                let boolean = if self.parse_keyword(Keyword::TRUE) {
1200                    Some(true)
1201                } else if self.parse_keyword(Keyword::FALSE) {
1202                    Some(false)
1203                } else {
1204                    None
1205                };
1206                options.push(AttachDuckDBDatabaseOption::ReadOnly(boolean));
1207            } else if self.parse_keyword(Keyword::TYPE) {
1208                let ident = self.parse_identifier()?;
1209                options.push(AttachDuckDBDatabaseOption::Type(ident));
1210            } else {
1211                return self
1212                    .expected_ref("expected one of: ), READ_ONLY, TYPE", self.peek_token_ref());
1213            };
1214
1215            if self.consume_token(&Token::RParen) {
1216                return Ok(options);
1217            } else if self.consume_token(&Token::Comma) {
1218                continue;
1219            } else {
1220                return self.expected_ref("expected one of: ')', ','", self.peek_token_ref());
1221            }
1222        }
1223    }
1224
1225    /// Parse `ATTACH DUCKDB DATABASE` statement.
1226    pub fn parse_attach_duckdb_database(&mut self) -> Result<Statement, ParserError> {
1227        let database = self.parse_keyword(Keyword::DATABASE);
1228        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
1229        let database_path = self.parse_identifier()?;
1230        let database_alias = if self.parse_keyword(Keyword::AS) {
1231            Some(self.parse_identifier()?)
1232        } else {
1233            None
1234        };
1235
1236        let attach_options = self.parse_attach_duckdb_database_options()?;
1237        Ok(Statement::AttachDuckDBDatabase {
1238            if_not_exists,
1239            database,
1240            database_path,
1241            database_alias,
1242            attach_options,
1243        })
1244    }
1245
1246    /// Parse `DETACH DUCKDB DATABASE` statement.
1247    pub fn parse_detach_duckdb_database(&mut self) -> Result<Statement, ParserError> {
1248        let database = self.parse_keyword(Keyword::DATABASE);
1249        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
1250        let database_alias = self.parse_identifier()?;
1251        Ok(Statement::DetachDuckDBDatabase {
1252            if_exists,
1253            database,
1254            database_alias,
1255        })
1256    }
1257
1258    /// Parse `ATTACH DATABASE` statement.
1259    pub fn parse_attach_database(&mut self) -> Result<Statement, ParserError> {
1260        let database = self.parse_keyword(Keyword::DATABASE);
1261        let database_file_name = self.parse_expr()?;
1262        self.expect_keyword_is(Keyword::AS)?;
1263        let schema_name = self.parse_identifier()?;
1264        Ok(Statement::AttachDatabase {
1265            database,
1266            schema_name,
1267            database_file_name,
1268        })
1269    }
1270
1271    /// Parse `ANALYZE` statement.
1272    pub fn parse_analyze(&mut self) -> Result<Analyze, ParserError> {
1273        let has_table_keyword = self.parse_keyword(Keyword::TABLE);
1274        let table_name = self.maybe_parse(|parser| parser.parse_object_name(false))?;
1275        let mut for_columns = false;
1276        let mut cache_metadata = false;
1277        let mut noscan = false;
1278        let mut partitions = None;
1279        let mut compute_statistics = false;
1280        let mut columns = vec![];
1281
1282        // PostgreSQL syntax: ANALYZE t (col1, col2)
1283        if table_name.is_some() && self.consume_token(&Token::LParen) {
1284            columns = self.parse_comma_separated(|p| p.parse_identifier())?;
1285            self.expect_token(&Token::RParen)?;
1286        }
1287
1288        loop {
1289            match self.parse_one_of_keywords(&[
1290                Keyword::PARTITION,
1291                Keyword::FOR,
1292                Keyword::CACHE,
1293                Keyword::NOSCAN,
1294                Keyword::COMPUTE,
1295            ]) {
1296                Some(Keyword::PARTITION) => {
1297                    self.expect_token(&Token::LParen)?;
1298                    partitions = Some(self.parse_comma_separated(Parser::parse_expr)?);
1299                    self.expect_token(&Token::RParen)?;
1300                }
1301                Some(Keyword::NOSCAN) => noscan = true,
1302                Some(Keyword::FOR) => {
1303                    self.expect_keyword_is(Keyword::COLUMNS)?;
1304
1305                    columns = self
1306                        .maybe_parse(|parser| {
1307                            parser.parse_comma_separated(|p| p.parse_identifier())
1308                        })?
1309                        .unwrap_or_default();
1310                    for_columns = true
1311                }
1312                Some(Keyword::CACHE) => {
1313                    self.expect_keyword_is(Keyword::METADATA)?;
1314                    cache_metadata = true
1315                }
1316                Some(Keyword::COMPUTE) => {
1317                    self.expect_keyword_is(Keyword::STATISTICS)?;
1318                    compute_statistics = true
1319                }
1320                _ => break,
1321            }
1322        }
1323
1324        Ok(Analyze {
1325            has_table_keyword,
1326            table_name,
1327            for_columns,
1328            columns,
1329            partitions,
1330            cache_metadata,
1331            noscan,
1332            compute_statistics,
1333        })
1334    }
1335
1336    /// Parse a new expression including wildcard & qualified wildcard.
1337    pub fn parse_wildcard_expr(&mut self) -> Result<Expr, ParserError> {
1338        let index = self.index;
1339
1340        let next_token = self.next_token();
1341        match next_token.token {
1342            t @ (Token::Word(_) | Token::SingleQuotedString(_))
1343                if self.peek_token_ref().token == Token::Period =>
1344            {
1345                let mut id_parts: Vec<Ident> = vec![match t {
1346                    Token::Word(w) => w.into_ident(next_token.span),
1347                    Token::SingleQuotedString(s) => Ident::with_quote('\'', s),
1348                    _ => {
1349                        return Err(ParserError::ParserError(
1350                            "Internal parser error: unexpected token type".to_string(),
1351                        ))
1352                    }
1353                }];
1354
1355                while self.consume_token(&Token::Period) {
1356                    let next_token = self.next_token();
1357                    match next_token.token {
1358                        Token::Word(w) => id_parts.push(w.into_ident(next_token.span)),
1359                        Token::SingleQuotedString(s) => {
1360                            // SQLite has single-quoted identifiers
1361                            id_parts.push(Ident::with_quote('\'', s))
1362                        }
1363                        Token::Placeholder(s) => {
1364                            // Snowflake uses $1, $2, etc. for positional column references
1365                            // in staged data queries like: SELECT t.$1 FROM @stage t
1366                            id_parts.push(Ident::new(s))
1367                        }
1368                        Token::Mul => {
1369                            return Ok(Expr::QualifiedWildcard(
1370                                ObjectName::from(id_parts),
1371                                AttachedToken(next_token),
1372                            ));
1373                        }
1374                        // A field index such as `t.1` is parsed as an expression.
1375                        Token::Number(..) if self.dialect.supports_tuple_element_access() => break,
1376                        _ => {
1377                            return self.expected("an identifier or a '*' after '.'", next_token);
1378                        }
1379                    }
1380                }
1381            }
1382            Token::Mul => {
1383                return Ok(Expr::Wildcard(AttachedToken(next_token)));
1384            }
1385            // Handle parenthesized wildcard: (*)
1386            Token::LParen => {
1387                let [maybe_mul, maybe_rparen] = self.peek_tokens_ref();
1388                if maybe_mul.token == Token::Mul && maybe_rparen.token == Token::RParen {
1389                    let mul_token = self.next_token(); // consume Mul
1390                    self.next_token(); // consume RParen
1391                    return Ok(Expr::Wildcard(AttachedToken(mul_token)));
1392                }
1393            }
1394            _ => (),
1395        };
1396
1397        self.index = index;
1398        self.parse_expr()
1399    }
1400
1401    /// Parse a new expression.
1402    pub fn parse_expr(&mut self) -> Result<Expr, ParserError> {
1403        self.parse_subexpr(self.dialect.prec_unknown())
1404    }
1405
1406    /// Parse expression with optional alias and order by.
1407    pub fn parse_expr_with_alias_and_order_by(
1408        &mut self,
1409    ) -> Result<ExprWithAliasAndOrderBy, ParserError> {
1410        let expr = self.parse_expr()?;
1411
1412        fn validator(explicit: bool, kw: &Keyword, _parser: &mut Parser) -> bool {
1413            explicit || !&[Keyword::ASC, Keyword::DESC, Keyword::GROUP].contains(kw)
1414        }
1415        let alias = self.parse_optional_alias_inner(None, validator)?;
1416        let order_by = OrderByOptions {
1417            sort: self.parse_optional_order_by_sort(),
1418            nulls_first: None,
1419        };
1420        Ok(ExprWithAliasAndOrderBy {
1421            expr: ExprWithAlias { expr, alias },
1422            order_by,
1423        })
1424    }
1425
1426    /// Parse tokens until the precedence changes.
1427    #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
1428    pub fn parse_subexpr(&mut self, precedence: u8) -> Result<Expr, ParserError> {
1429        let _guard = self.recursion_counter.try_decrease()?;
1430        debug!("parsing expr");
1431        let mut expr = self.parse_prefix()?;
1432
1433        expr = self.parse_compound_expr(expr, vec![])?;
1434
1435        // Parse an optional collation cast operator following `expr`.
1436        //
1437        // For example (MSSQL): t1.a COLLATE Latin1_General_CI_AS
1438        if !self.in_column_definition_state() && self.parse_keyword(Keyword::COLLATE) {
1439            expr = Expr::Collate {
1440                expr: Box::new(expr),
1441                collation: self.parse_object_name(false)?,
1442            };
1443        }
1444
1445        debug!("prefix: {expr:?}");
1446        loop {
1447            let next_precedence = self.get_next_precedence()?;
1448            debug!("next precedence: {next_precedence:?}");
1449
1450            if precedence >= next_precedence {
1451                break;
1452            }
1453
1454            // The period operator is handled exclusively by the
1455            // compound field access parsing.
1456            if Token::Period == self.peek_token_ref().token {
1457                break;
1458            }
1459
1460            expr = self.parse_infix(expr, next_precedence)?;
1461        }
1462        Ok(expr)
1463    }
1464
1465    /// Parse `ASSERT` statement.
1466    pub fn parse_assert(&mut self) -> Result<Statement, ParserError> {
1467        let condition = self.parse_expr()?;
1468        let message = if self.parse_keyword(Keyword::AS) {
1469            Some(self.parse_expr()?)
1470        } else {
1471            None
1472        };
1473
1474        Ok(Statement::Assert { condition, message })
1475    }
1476
1477    /// Parse `SAVEPOINT` statement.
1478    pub fn parse_savepoint(&mut self) -> Result<Statement, ParserError> {
1479        let name = self.parse_identifier()?;
1480        Ok(Statement::Savepoint { name })
1481    }
1482
1483    /// Parse `RELEASE` statement.
1484    pub fn parse_release(&mut self) -> Result<Statement, ParserError> {
1485        let _ = self.parse_keyword(Keyword::SAVEPOINT);
1486        let name = self.parse_identifier()?;
1487
1488        Ok(Statement::ReleaseSavepoint { name })
1489    }
1490
1491    /// Parse `LISTEN` statement.
1492    pub fn parse_listen(&mut self) -> Result<Statement, ParserError> {
1493        let channel = self.parse_identifier()?;
1494        Ok(Statement::LISTEN { channel })
1495    }
1496
1497    /// Parse `UNLISTEN` statement.
1498    pub fn parse_unlisten(&mut self) -> Result<Statement, ParserError> {
1499        let channel = if self.consume_token(&Token::Mul) {
1500            Ident::new(Expr::Wildcard(AttachedToken::empty()).to_string())
1501        } else {
1502            match self.parse_identifier() {
1503                Ok(expr) => expr,
1504                _ => {
1505                    self.prev_token();
1506                    return self.expected_ref("wildcard or identifier", self.peek_token_ref());
1507                }
1508            }
1509        };
1510        Ok(Statement::UNLISTEN { channel })
1511    }
1512
1513    /// Parse `NOTIFY` statement.
1514    pub fn parse_notify(&mut self) -> Result<Statement, ParserError> {
1515        let channel = self.parse_identifier()?;
1516        let payload = if self.consume_token(&Token::Comma) {
1517            Some(self.parse_literal_string()?)
1518        } else {
1519            None
1520        };
1521        Ok(Statement::NOTIFY { channel, payload })
1522    }
1523
1524    /// Parses a `RENAME TABLE` statement. See [Statement::RenameTable]
1525    pub fn parse_rename(&mut self) -> Result<Statement, ParserError> {
1526        if self.peek_keyword(Keyword::TABLE) {
1527            self.expect_keyword(Keyword::TABLE)?;
1528            let rename_tables = self.parse_comma_separated(|parser| {
1529                let old_name = parser.parse_object_name(false)?;
1530                parser.expect_keyword(Keyword::TO)?;
1531                let new_name = parser.parse_object_name(false)?;
1532
1533                Ok(RenameTable { old_name, new_name })
1534            })?;
1535            Ok(rename_tables.into())
1536        } else {
1537            self.expected_ref("KEYWORD `TABLE` after RENAME", self.peek_token_ref())
1538        }
1539    }
1540
1541    /// Tries to parse an expression by matching the specified word to known keywords that have a special meaning in the dialect.
1542    /// Returns `None if no match is found.
1543    fn parse_expr_prefix_by_reserved_word(
1544        &mut self,
1545        w: &Word,
1546        w_span: Span,
1547    ) -> Result<Option<Expr>, ParserError> {
1548        match w.keyword {
1549            Keyword::TRUE | Keyword::FALSE if self.dialect.supports_boolean_literals() => {
1550                self.prev_token();
1551                Ok(Some(Expr::Value(self.parse_value()?)))
1552            }
1553            Keyword::NULL => {
1554                self.prev_token();
1555                Ok(Some(Expr::Value(self.parse_value()?)))
1556            }
1557            Keyword::CURRENT_CATALOG
1558            | Keyword::CURRENT_USER
1559            | Keyword::SESSION_USER
1560            | Keyword::USER
1561            if dialect_of!(self is PostgreSqlDialect | GenericDialect) =>
1562                {
1563                    Ok(Some(Expr::Function(Function {
1564                        name: ObjectName::from(vec![w.to_ident(w_span)]),
1565                        uses_odbc_syntax: false,
1566                        parameters: FunctionArguments::None,
1567                        args: FunctionArguments::None,
1568                        null_treatment: None,
1569                        filter: None,
1570                        over: None,
1571                        within_group: vec![],
1572                    })))
1573                }
1574            Keyword::CURRENT_TIMESTAMP
1575            | Keyword::CURRENT_TIME
1576            | Keyword::CURRENT_DATE
1577            | Keyword::LOCALTIME
1578            | Keyword::LOCALTIMESTAMP => {
1579                Ok(Some(self.parse_time_functions(ObjectName::from(vec![w.to_ident(w_span)]))?))
1580            }
1581            Keyword::CASE => Ok(Some(self.parse_case_expr()?)),
1582            Keyword::CONVERT => Ok(Some(self.parse_convert_expr(false)?)),
1583            Keyword::TRY_CONVERT if self.dialect.supports_try_convert() => Ok(Some(self.parse_convert_expr(true)?)),
1584            Keyword::CAST => Ok(Some(self.parse_cast_expr(CastKind::Cast)?)),
1585            Keyword::TRY_CAST => Ok(Some(self.parse_cast_expr(CastKind::TryCast)?)),
1586            Keyword::SAFE_CAST => Ok(Some(self.parse_cast_expr(CastKind::SafeCast)?)),
1587            Keyword::EXISTS
1588            // Support parsing Databricks has a function named `exists`.
1589            if !dialect_of!(self is DatabricksDialect)
1590                || matches!(
1591                        self.peek_nth_token_ref(1).token,
1592                        Token::Word(Word {
1593                            keyword: Keyword::SELECT | Keyword::WITH,
1594                            ..
1595                        })
1596                    ) =>
1597                {
1598                    Ok(Some(self.parse_exists_expr(false)?))
1599                }
1600            Keyword::EXTRACT => Ok(Some(self.parse_extract_expr()?)),
1601            Keyword::CEIL => Ok(Some(self.parse_ceil_floor_expr(true)?)),
1602            Keyword::FLOOR => Ok(Some(self.parse_ceil_floor_expr(false)?)),
1603            Keyword::POSITION if self.peek_token_ref().token == Token::LParen => {
1604                Ok(Some(self.parse_position_expr(w.to_ident(w_span))?))
1605            }
1606            Keyword::SUBSTR | Keyword::SUBSTRING => {
1607                self.prev_token();
1608                Ok(Some(self.parse_substring()?))
1609            }
1610            Keyword::OVERLAY => Ok(Some(self.parse_overlay_expr()?)),
1611            Keyword::TRIM => Ok(Some(self.parse_trim_expr()?)),
1612            Keyword::INTERVAL => Ok(Some(self.parse_interval()?)),
1613            // Treat ARRAY[1,2,3] as an array [1,2,3], otherwise try as subquery or a function call
1614            Keyword::ARRAY if *self.peek_token_ref() == Token::LBracket => {
1615                self.expect_token(&Token::LBracket)?;
1616                Ok(Some(self.parse_array_expr(true)?))
1617            }
1618            Keyword::ARRAY
1619            if self.peek_token_ref().token == Token::LParen
1620                && !dialect_of!(self is ClickHouseDialect | DatabricksDialect) =>
1621                {
1622                    self.expect_token(&Token::LParen)?;
1623                    let query = self.parse_query()?;
1624                    self.expect_token(&Token::RParen)?;
1625                    Ok(Some(Expr::Function(Function {
1626                        name: ObjectName::from(vec![w.to_ident(w_span)]),
1627                        uses_odbc_syntax: false,
1628                        parameters: FunctionArguments::None,
1629                        args: FunctionArguments::Subquery(query),
1630                        filter: None,
1631                        null_treatment: None,
1632                        over: None,
1633                        within_group: vec![],
1634                    })))
1635                }
1636            Keyword::NOT => Ok(Some(self.parse_not()?)),
1637            Keyword::MATCH if self.dialect.supports_match_against() => {
1638                Ok(Some(self.parse_match_against()?))
1639            }
1640            Keyword::STRUCT if self.dialect.supports_struct_literal() => {
1641                let struct_expr = self.parse_struct_literal()?;
1642                Ok(Some(struct_expr))
1643            }
1644            Keyword::PRIOR if matches!(self.state, ParserState::ConnectBy) => {
1645                let expr = self.parse_subexpr(self.dialect.prec_value(Precedence::PlusMinus))?;
1646                Ok(Some(Expr::Prior(Box::new(expr))))
1647            }
1648            Keyword::MAP if *self.peek_token_ref() == Token::LBrace && self.dialect.support_map_literal_syntax() => {
1649                Ok(Some(self.parse_duckdb_map_literal()?))
1650            }
1651            Keyword::APPROXIMATE
1652                if self.dialect.supports_approximate_percentile_disc()
1653                    && self.peek_keyword(Keyword::PERCENTILE_DISC) =>
1654            {
1655                self.maybe_parse(|parser| {
1656                    let function_name = parser.parse_object_name(false)?;
1657                    parser.parse_function(function_name).map(|function| Expr::Prefixed {
1658                        prefix: w.to_ident(w_span),
1659                        value: Box::new(function),
1660                    })
1661                })
1662            }
1663            Keyword::LAMBDA if self.dialect.supports_lambda_keyword_syntax() => {
1664                Ok(Some(self.parse_lambda_expr()?))
1665            }
1666            _ if self.dialect.supports_geometric_types() => match w.keyword {
1667                Keyword::CIRCLE => Ok(Some(self.parse_geometric_type(GeometricTypeKind::Circle)?)),
1668                Keyword::BOX => Ok(Some(self.parse_geometric_type(GeometricTypeKind::GeometricBox)?)),
1669                Keyword::PATH => Ok(Some(self.parse_geometric_type(GeometricTypeKind::GeometricPath)?)),
1670                Keyword::LINE => Ok(Some(self.parse_geometric_type(GeometricTypeKind::Line)?)),
1671                Keyword::LSEG => Ok(Some(self.parse_geometric_type(GeometricTypeKind::LineSegment)?)),
1672                Keyword::POINT => Ok(Some(self.parse_geometric_type(GeometricTypeKind::Point)?)),
1673                Keyword::POLYGON => Ok(Some(self.parse_geometric_type(GeometricTypeKind::Polygon)?)),
1674                _ => Ok(None),
1675            },
1676            _ => Ok(None),
1677        }
1678    }
1679
1680    /// Tries to parse an expression by a word that is not known to have a special meaning in the dialect.
1681    fn parse_expr_prefix_by_unreserved_word(
1682        &mut self,
1683        w: &Word,
1684        w_span: Span,
1685    ) -> Result<Expr, ParserError> {
1686        let is_outer_join = self.peek_outer_join_operator();
1687        match &self.peek_token_ref().token {
1688            Token::LParen if !is_outer_join => {
1689                let id_parts = vec![w.to_ident(w_span)];
1690                self.parse_function(ObjectName::from(id_parts))
1691            }
1692            // string introducer https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1693            Token::SingleQuotedString(_)
1694            | Token::DoubleQuotedString(_)
1695            | Token::HexStringLiteral(_)
1696                if w.value.starts_with('_') =>
1697            {
1698                Ok(Expr::Prefixed {
1699                    prefix: w.to_ident(w_span),
1700                    value: self.parse_introduced_string_expr()?.into(),
1701                })
1702            }
1703            // string introducer https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1704            Token::SingleQuotedString(_)
1705            | Token::DoubleQuotedString(_)
1706            | Token::HexStringLiteral(_)
1707                if w.value.starts_with('_') =>
1708            {
1709                Ok(Expr::Prefixed {
1710                    prefix: w.to_ident(w_span),
1711                    value: self.parse_introduced_string_expr()?.into(),
1712                })
1713            }
1714            // An unreserved word (likely an identifier) is followed by an arrow,
1715            // which indicates a lambda function with a single, untyped parameter.
1716            // For example: `a -> a * 2`.
1717            Token::Arrow if self.dialect.supports_lambda_functions() => {
1718                self.expect_token(&Token::Arrow)?;
1719                Ok(Expr::Lambda(LambdaFunction {
1720                    params: OneOrManyWithParens::One(LambdaFunctionParameter {
1721                        name: w.to_ident(w_span),
1722                        data_type: None,
1723                    }),
1724                    body: Box::new(self.parse_expr()?),
1725                    syntax: LambdaSyntax::Arrow,
1726                }))
1727            }
1728            // An unreserved word (likely an identifier) that is followed by another word (likley a data type)
1729            // which is then followed by an arrow, which indicates a lambda function with a single, typed parameter.
1730            // For example: `a INT -> a * 2`.
1731            Token::Word(_)
1732                if self.dialect.supports_lambda_functions()
1733                    && self.peek_nth_token_ref(1).token == Token::Arrow =>
1734            {
1735                let data_type = self.parse_data_type()?;
1736                self.expect_token(&Token::Arrow)?;
1737                Ok(Expr::Lambda(LambdaFunction {
1738                    params: OneOrManyWithParens::One(LambdaFunctionParameter {
1739                        name: w.to_ident(w_span),
1740                        data_type: Some(data_type),
1741                    }),
1742                    body: Box::new(self.parse_expr()?),
1743                    syntax: LambdaSyntax::Arrow,
1744                }))
1745            }
1746            _ => Ok(Expr::Identifier(w.to_ident(w_span))),
1747        }
1748    }
1749
1750    /// Returns true if the given [ObjectName] is a single unquoted
1751    /// identifier matching `expected` (case-insensitive).
1752    fn is_simple_unquoted_object_name(name: &ObjectName, expected: &str) -> bool {
1753        if let [ObjectNamePart::Identifier(ident)] = name.0.as_slice() {
1754            ident.quote_style.is_none() && ident.value.eq_ignore_ascii_case(expected)
1755        } else {
1756            false
1757        }
1758    }
1759
1760    /// Parse an expression prefix.
1761    pub fn parse_prefix(&mut self) -> Result<Expr, ParserError> {
1762        // allow the dialect to override prefix parsing
1763        if let Some(prefix) = self.dialect.parse_prefix(self) {
1764            return prefix;
1765        }
1766
1767        // Memoize parse_prefix failures to break 2^N speculation when both
1768        // prefix arms fail at every level (e.g. `IF(current_time(...x`).
1769        // The per-arm cache in `parse_prefix_inner` complements this for
1770        // chains where the reserved arm fails but the unreserved fallback
1771        // succeeds (e.g. `case-case-...c`).
1772        let start_index = self.index;
1773        if let Some(&cached) = self.failed_prefix_positions.get(&start_index) {
1774            return self.cached_prefix_error(cached, self.peek_token_ref());
1775        }
1776        let result = self.parse_prefix_inner();
1777        if let Err(ref e) = result {
1778            self.failed_prefix_positions.insert(start_index, e.into());
1779        }
1780        result
1781    }
1782
1783    /// Rebuild the error for a cached prefix failure at the `found` token.
1784    fn cached_prefix_error<T>(
1785        &self,
1786        cached: ExprPrefixError,
1787        found: &TokenWithSpan,
1788    ) -> Result<T, ParserError> {
1789        match cached {
1790            ExprPrefixError::RecursionLimitExceeded => Err(ParserError::RecursionLimitExceeded),
1791            ExprPrefixError::Err => self.expected_ref("an expression", found),
1792        }
1793    }
1794
1795    fn parse_prefix_inner(&mut self) -> Result<Expr, ParserError> {
1796        // PostgreSQL allows any string literal to be preceded by a type name, indicating that the
1797        // string literal represents a literal of that type. Some examples:
1798        //
1799        //      DATE '2020-05-20'
1800        //      TIMESTAMP WITH TIME ZONE '2020-05-20 7:43:54'
1801        //      BOOL 'true'
1802        //
1803        // The first two are standard SQL, while the latter is a PostgreSQL extension. Complicating
1804        // matters is the fact that INTERVAL string literals may optionally be followed by special
1805        // keywords, e.g.:
1806        //
1807        //      INTERVAL '7' DAY
1808        //
1809        // Note also that naively `SELECT date` looks like a syntax error because the `date` type
1810        // name is not followed by a string literal, but in fact in PostgreSQL it is a valid
1811        // expression that should parse as the column name "date".
1812        let loc = self.peek_token_ref().span.start;
1813        let opt_expr = self.maybe_parse(|parser| {
1814            match parser.parse_data_type()? {
1815                DataType::Interval { .. } => parser.parse_interval(),
1816                // PostgreSQL allows almost any identifier to be used as custom data type name,
1817                // and we support that in `parse_data_type()`. But unlike Postgres we don't
1818                // have a list of globally reserved keywords (since they vary across dialects),
1819                // so given `NOT 'a' LIKE 'b'`, we'd accept `NOT` as a possible custom data type
1820                // name, resulting in `NOT 'a'` being recognized as a `TypedString` instead of
1821                // an unary negation `NOT ('a' LIKE 'b')`. To solve this, we don't accept the
1822                // `type 'string'` syntax for the custom data types at all ...
1823                //
1824                // ... with the exception of `xml '...'` on dialects that support XML
1825                // expressions, which is a valid PostgreSQL typed string literal.
1826                DataType::Custom(ref name, ref modifiers)
1827                    if modifiers.is_empty()
1828                        && Self::is_simple_unquoted_object_name(name, "xml")
1829                        && parser.dialect.supports_xml_expressions() =>
1830                {
1831                    Ok(Expr::TypedString(TypedString {
1832                        data_type: DataType::Custom(name.clone(), modifiers.clone()),
1833                        value: parser.parse_value()?,
1834                        uses_odbc_syntax: false,
1835                    }))
1836                }
1837                DataType::Custom(..) => parser_err!("dummy", loc),
1838                // MySQL supports using the `BINARY` keyword as a cast to binary type.
1839                DataType::Binary(..) if self.dialect.supports_binary_kw_as_cast() => {
1840                    Ok(Expr::Cast {
1841                        kind: CastKind::Cast,
1842                        expr: Box::new(parser.parse_expr()?),
1843                        data_type: DataType::Binary(None),
1844                        format: None,
1845                    })
1846                }
1847                data_type => Ok(Expr::TypedString(TypedString {
1848                    data_type,
1849                    value: parser.parse_value()?,
1850                    uses_odbc_syntax: false,
1851                })),
1852            }
1853        })?;
1854
1855        if let Some(expr) = opt_expr {
1856            return Ok(expr);
1857        }
1858
1859        // Cache some dialect properties to avoid lifetime issues with the
1860        // next_token reference.
1861
1862        let dialect = self.dialect;
1863
1864        self.advance_token();
1865        let next_token_index = self.get_current_index();
1866        let next_token = self.get_current_token();
1867        let span = next_token.span;
1868        let expr = match &next_token.token {
1869            Token::Word(w) => {
1870                // The word we consumed may fall into one of two cases: it has a special meaning, or not.
1871                // For example, in Snowflake, the word `interval` may have two meanings depending on the context:
1872                // `SELECT CURRENT_DATE() + INTERVAL '1 DAY', MAX(interval) FROM tbl;`
1873                //                          ^^^^^^^^^^^^^^^^      ^^^^^^^^
1874                //                         interval expression   identifier
1875                //
1876                // We first try to parse the word and following tokens as a special expression, and if that fails,
1877                // we rollback and try to parse it as an identifier.
1878                let w = w.clone();
1879                // Memoize failed speculative reserved-word parses. When
1880                // the reserved arm (CASE, CURRENT_TIME, etc.) does
1881                // exponential work but the unreserved fallback ultimately
1882                // succeeds, the overall `parse_prefix` returns `Ok` and the
1883                // outer cache never fires. Chains like `case-case-...c`
1884                // need this per-arm cache to break the doubling.
1885                let try_parse_result = if let Some(&cached) = self
1886                    .failed_reserved_word_prefix_positions
1887                    .get(&next_token_index)
1888                {
1889                    self.cached_prefix_error(cached, self.get_current_token())
1890                } else {
1891                    self.try_parse(|parser| parser.parse_expr_prefix_by_reserved_word(&w, span))
1892                };
1893                match try_parse_result {
1894                    // This word indicated an expression prefix and parsing was successful
1895                    Ok(Some(expr)) => Ok(expr),
1896
1897                    // No expression prefix associated with this word
1898                    Ok(None) => Ok(self.parse_expr_prefix_by_unreserved_word(&w, span)?),
1899
1900                    // If parsing of the word as a special expression failed, we are facing two options:
1901                    // 1. The statement is malformed, e.g. `SELECT INTERVAL '1 DAI` (`DAI` instead of `DAY`)
1902                    // 2. The word is used as an identifier, e.g. `SELECT MAX(interval) FROM tbl`
1903                    // We first try to parse the word as an identifier and if that fails
1904                    // we rollback and return the parsing error we got from trying to parse a
1905                    // special expression (to maintain backwards compatibility of parsing errors).
1906                    Err(e) => {
1907                        self.failed_reserved_word_prefix_positions
1908                            .insert(next_token_index, (&e).into());
1909                        if !self.dialect.is_reserved_for_identifier(w.keyword) {
1910                            if let Ok(Some(expr)) = self.maybe_parse(|parser| {
1911                                parser.parse_expr_prefix_by_unreserved_word(&w, span)
1912                            }) {
1913                                return Ok(expr);
1914                            }
1915                        }
1916                        return Err(e);
1917                    }
1918                }
1919            } // End of Token::Word
1920            // array `[1, 2, 3]`
1921            Token::LBracket => self.parse_array_expr(false),
1922            tok @ Token::Minus | tok @ Token::Plus => {
1923                let op = if *tok == Token::Plus {
1924                    UnaryOperator::Plus
1925                } else {
1926                    UnaryOperator::Minus
1927                };
1928                Ok(Expr::UnaryOp {
1929                    op,
1930                    expr: Box::new(
1931                        self.parse_subexpr(self.dialect.prec_value(Precedence::MulDivModOp))?,
1932                    ),
1933                })
1934            }
1935            Token::ExclamationMark if dialect.supports_bang_not_operator() => Ok(Expr::UnaryOp {
1936                op: UnaryOperator::BangNot,
1937                expr: Box::new(self.parse_subexpr(self.dialect.prec_value(Precedence::UnaryNot))?),
1938            }),
1939            tok @ Token::DoubleExclamationMark
1940            | tok @ Token::PGSquareRoot
1941            | tok @ Token::PGCubeRoot
1942            | tok @ Token::AtSign
1943                if dialect_is!(dialect is PostgreSqlDialect) =>
1944            {
1945                let op = match tok {
1946                    Token::DoubleExclamationMark => UnaryOperator::PGPrefixFactorial,
1947                    Token::PGSquareRoot => UnaryOperator::PGSquareRoot,
1948                    Token::PGCubeRoot => UnaryOperator::PGCubeRoot,
1949                    Token::AtSign => UnaryOperator::PGAbs,
1950                    _ => {
1951                        return Err(ParserError::ParserError(
1952                            "Internal parser error: unexpected unary operator token".to_string(),
1953                        ))
1954                    }
1955                };
1956                Ok(Expr::UnaryOp {
1957                    op,
1958                    expr: Box::new(
1959                        self.parse_subexpr(self.dialect.prec_value(Precedence::PlusMinus))?,
1960                    ),
1961                })
1962            }
1963            Token::Tilde => Ok(Expr::UnaryOp {
1964                op: UnaryOperator::BitwiseNot,
1965                expr: Box::new(self.parse_subexpr(self.dialect.prec_value(Precedence::PlusMinus))?),
1966            }),
1967            tok @ Token::Sharp
1968            | tok @ Token::AtDashAt
1969            | tok @ Token::AtAt
1970            | tok @ Token::QuestionMarkDash
1971            | tok @ Token::QuestionPipe
1972                if self.dialect.supports_geometric_types() =>
1973            {
1974                let op = match tok {
1975                    Token::Sharp => UnaryOperator::Hash,
1976                    Token::AtDashAt => UnaryOperator::AtDashAt,
1977                    Token::AtAt => UnaryOperator::DoubleAt,
1978                    Token::QuestionMarkDash => UnaryOperator::QuestionDash,
1979                    Token::QuestionPipe => UnaryOperator::QuestionPipe,
1980                    _ => {
1981                        return Err(ParserError::ParserError(format!(
1982                            "Unexpected token in unary operator parsing: {tok:?}"
1983                        )))
1984                    }
1985                };
1986                Ok(Expr::UnaryOp {
1987                    op,
1988                    expr: Box::new(
1989                        self.parse_subexpr(self.dialect.prec_value(Precedence::PlusMinus))?,
1990                    ),
1991                })
1992            }
1993            Token::EscapedStringLiteral(_) if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) =>
1994            {
1995                self.prev_token();
1996                Ok(Expr::Value(self.parse_value()?))
1997            }
1998            Token::UnicodeStringLiteral(_) => {
1999                self.prev_token();
2000                Ok(Expr::Value(self.parse_value()?))
2001            }
2002            Token::Number(_, _)
2003            | Token::SingleQuotedString(_)
2004            | Token::DoubleQuotedString(_)
2005            | Token::TripleSingleQuotedString(_)
2006            | Token::TripleDoubleQuotedString(_)
2007            | Token::DollarQuotedString(_)
2008            | Token::SingleQuotedByteStringLiteral(_)
2009            | Token::DoubleQuotedByteStringLiteral(_)
2010            | Token::TripleSingleQuotedByteStringLiteral(_)
2011            | Token::TripleDoubleQuotedByteStringLiteral(_)
2012            | Token::SingleQuotedRawStringLiteral(_)
2013            | Token::DoubleQuotedRawStringLiteral(_)
2014            | Token::TripleSingleQuotedRawStringLiteral(_)
2015            | Token::TripleDoubleQuotedRawStringLiteral(_)
2016            | Token::NationalStringLiteral(_)
2017            | Token::QuoteDelimitedStringLiteral(_)
2018            | Token::NationalQuoteDelimitedStringLiteral(_)
2019            | Token::HexStringLiteral(_) => {
2020                self.prev_token();
2021                Ok(Expr::Value(self.parse_value()?))
2022            }
2023            Token::LParen => {
2024                let expr =
2025                    if let Some(expr) = self.try_parse_expr_sub_query()? {
2026                        expr
2027                    } else if let Some(lambda) = self.try_parse_lambda()? {
2028                        return Ok(lambda);
2029                    } else {
2030                        // Parentheses in expressions switch to "normal" parsing state.
2031                        // This matters for dialects (SQLite, DuckDB) where `NOT NULL` can
2032                        // be an alias for `IS NOT NULL`. In column definitions like:
2033                        //
2034                        //   CREATE TABLE t (c INT DEFAULT (42 NOT NULL) NOT NULL)
2035                        //
2036                        // The `(42 NOT NULL)` is an expression with parens, so it parses
2037                        // as `IsNotNull(42)`. The trailing `NOT NULL` is outside those
2038                        // expression parens (the outer parens are CREATE TABLE syntax),
2039                        // so it remains a column constraint.
2040                        let exprs = self.with_state(ParserState::Normal, |p| {
2041                            p.parse_comma_separated(Parser::parse_expr)
2042                        })?;
2043                        match exprs.len() {
2044                            0 => return Err(ParserError::ParserError(
2045                                "Internal parser error: parse_comma_separated returned empty list"
2046                                    .to_string(),
2047                            )),
2048                            1 => Expr::Nested(Box::new(exprs.into_iter().next().unwrap())),
2049                            _ => Expr::Tuple(exprs),
2050                        }
2051                    };
2052                self.expect_token(&Token::RParen)?;
2053                Ok(expr)
2054            }
2055            Token::Placeholder(_) | Token::Colon | Token::AtSign => {
2056                self.prev_token();
2057                Ok(Expr::Value(self.parse_value()?))
2058            }
2059            Token::LBrace => {
2060                self.prev_token();
2061                self.parse_lbrace_expr()
2062            }
2063            _ => self.expected_at("an expression", next_token_index),
2064        }?;
2065
2066        Ok(expr)
2067    }
2068
2069    fn parse_geometric_type(&mut self, kind: GeometricTypeKind) -> Result<Expr, ParserError> {
2070        Ok(Expr::TypedString(TypedString {
2071            data_type: DataType::GeometricType(kind),
2072            value: self.parse_value()?,
2073            uses_odbc_syntax: false,
2074        }))
2075    }
2076
2077    /// Try to parse an [Expr::CompoundFieldAccess] like `a.b.c` or `a.b[1].c`.
2078    /// If all the fields are `Expr::Identifier`s, return an [Expr::CompoundIdentifier] instead.
2079    /// If only the root exists, return the root.
2080    /// Parses compound expressions which may be delimited by period
2081    /// or bracket notation.
2082    /// For example: `a.b.c`, `a.b[1]`.
2083    pub fn parse_compound_expr(
2084        &mut self,
2085        root: Expr,
2086        mut chain: Vec<AccessExpr>,
2087    ) -> Result<Expr, ParserError> {
2088        let mut ending_wildcard: Option<TokenWithSpan> = None;
2089        loop {
2090            if self.consume_token(&Token::Period) {
2091                let next_token = self.peek_token_ref();
2092                match &next_token.token {
2093                    Token::Mul => {
2094                        // Postgres explicitly allows funcnm(tablenm.*) and the
2095                        // function array_agg traverses this control flow
2096                        if dialect_of!(self is PostgreSqlDialect) {
2097                            ending_wildcard = Some(self.next_token());
2098                        } else {
2099                            // Put back the consumed `.` tokens before exiting.
2100                            // If this expression is being parsed in the
2101                            // context of a projection, then the `.*` could imply
2102                            // a wildcard expansion. For example:
2103                            // `SELECT STRUCT('foo').* FROM T`
2104                            self.prev_token(); // .
2105                        }
2106
2107                        break;
2108                    }
2109                    Token::SingleQuotedString(s) => {
2110                        let expr =
2111                            Expr::Identifier(Ident::with_quote_and_span('\'', next_token.span, s));
2112                        chain.push(AccessExpr::Dot(expr));
2113                        self.advance_token(); // The consumed string
2114                    }
2115                    Token::Placeholder(s) => {
2116                        // Snowflake uses $1, $2, etc. for positional column references
2117                        // in staged data queries like: SELECT t.$1 FROM @stage t
2118                        let expr = Expr::Identifier(Ident::with_span(next_token.span, s));
2119                        chain.push(AccessExpr::Dot(expr));
2120                        self.advance_token(); // The consumed placeholder
2121                    }
2122                    // Parse a single field component, restricted to expression types valid
2123                    // after `.` (so e.g. `T.interval` is a compound identifier, not an
2124                    // interval expression). Using `parse_prefix` here rather than
2125                    // `parse_subexpr` avoids 2^N work on inputs like `IF a.b.c...x.#`:
2126                    // the outer loop already consumes successive `.field` segments, so a
2127                    // recursive `parse_subexpr` would re-walk the rest of the chain at
2128                    // every dot.
2129                    _ => {
2130                        // For a plain `Word` field (not followed by `(`), skip the
2131                        // speculative `parse_prefix`. The only result the validator
2132                        // below would accept is `Identifier`, which `parse_identifier`
2133                        // in the None branch produces directly. This avoids 2^N work
2134                        // on chains like `.not-b.not-b...` where `parse_prefix` would
2135                        // descend into `parse_not` and re-walk the remaining chain at
2136                        // every segment.
2137                        let word_field_no_lparen =
2138                            matches!(self.peek_token_ref().token, Token::Word(_))
2139                                && self.peek_nth_token_ref(1).token != Token::LParen;
2140
2141                        let expr = if word_field_no_lparen {
2142                            None
2143                        } else {
2144                            self.maybe_parse(|parser| {
2145                                let expr = parser.parse_prefix()?;
2146                                match &expr {
2147                                    Expr::CompoundFieldAccess { .. }
2148                                    | Expr::CompoundIdentifier(_)
2149                                    | Expr::Identifier(_)
2150                                    | Expr::Value(_)
2151                                    | Expr::Function(_) => Ok(expr),
2152                                    _ => parser.expected_ref(
2153                                        "an identifier or value",
2154                                        parser.peek_token_ref(),
2155                                    ),
2156                                }
2157                            })?
2158                        };
2159
2160                        match expr {
2161                            // If we get back a compound field access or identifier,
2162                            // we flatten the nested expression.
2163                            // For example if the current root is `foo`
2164                            // and we get back a compound identifier expression `bar.baz`
2165                            // The full expression should be `foo.bar.baz` (i.e.
2166                            // a root with an access chain with 2 entries) and not
2167                            // `foo.(bar.baz)` (i.e. a root with an access chain with
2168                            // 1 entry`).
2169                            Some(Expr::CompoundFieldAccess { root, access_chain }) => {
2170                                chain.push(AccessExpr::Dot(*root));
2171                                chain.extend(access_chain);
2172                            }
2173                            Some(Expr::CompoundIdentifier(parts)) => chain.extend(
2174                                parts.into_iter().map(Expr::Identifier).map(AccessExpr::Dot),
2175                            ),
2176                            Some(expr) => {
2177                                chain.push(AccessExpr::Dot(expr));
2178                            }
2179                            // If the expression is not a valid suffix, fall back to
2180                            // parsing as an identifier. This handles cases like `T.interval`
2181                            // where `interval` is a keyword but should be treated as an identifier.
2182                            None => {
2183                                chain.push(AccessExpr::Dot(Expr::Identifier(
2184                                    self.parse_identifier()?,
2185                                )));
2186                            }
2187                        }
2188                    }
2189                }
2190            } else if !self.dialect.supports_partiql()
2191                && self.peek_token_ref().token == Token::LBracket
2192            {
2193                self.parse_multi_dim_subscript(&mut chain)?;
2194            } else {
2195                break;
2196            }
2197        }
2198
2199        let tok_index = self.get_current_index();
2200        if let Some(wildcard_token) = ending_wildcard {
2201            if !Self::is_all_ident(&root, &chain) {
2202                return self
2203                    .expected_ref("an identifier or a '*' after '.'", self.peek_token_ref());
2204            };
2205            Ok(Expr::QualifiedWildcard(
2206                ObjectName::from(Self::exprs_to_idents(root, chain)?),
2207                AttachedToken(wildcard_token),
2208            ))
2209        } else if self.maybe_parse_outer_join_operator() {
2210            if !Self::is_all_ident(&root, &chain) {
2211                return self.expected_at("column identifier before (+)", tok_index);
2212            };
2213            let expr = if chain.is_empty() {
2214                root
2215            } else {
2216                Expr::CompoundIdentifier(Self::exprs_to_idents(root, chain)?)
2217            };
2218            Ok(Expr::OuterJoin(expr.into()))
2219        } else {
2220            Self::build_compound_expr(root, chain)
2221        }
2222    }
2223
2224    /// Combines a root expression and access chain to form
2225    /// a compound expression. Which may be a [Expr::CompoundFieldAccess]
2226    /// or other special cased expressions like [Expr::CompoundIdentifier],
2227    /// [Expr::OuterJoin].
2228    fn build_compound_expr(
2229        root: Expr,
2230        mut access_chain: Vec<AccessExpr>,
2231    ) -> Result<Expr, ParserError> {
2232        if access_chain.is_empty() {
2233            return Ok(root);
2234        }
2235
2236        if Self::is_all_ident(&root, &access_chain) {
2237            return Ok(Expr::CompoundIdentifier(Self::exprs_to_idents(
2238                root,
2239                access_chain,
2240            )?));
2241        }
2242
2243        // Flatten qualified function calls.
2244        // For example, the expression `a.b.c.foo(1,2,3)` should
2245        // represent a function called `a.b.c.foo`, rather than
2246        // a composite expression.
2247        if matches!(root, Expr::Identifier(_))
2248            && matches!(
2249                access_chain.last(),
2250                Some(AccessExpr::Dot(Expr::Function(_)))
2251            )
2252            && access_chain
2253                .iter()
2254                .rev()
2255                .skip(1) // All except the Function
2256                .all(|access| matches!(access, AccessExpr::Dot(Expr::Identifier(_))))
2257        {
2258            let Some(AccessExpr::Dot(Expr::Function(mut func))) = access_chain.pop() else {
2259                return parser_err!("expected function expression", root.span().start);
2260            };
2261
2262            let compound_func_name = [root]
2263                .into_iter()
2264                .chain(access_chain.into_iter().flat_map(|access| match access {
2265                    AccessExpr::Dot(expr) => Some(expr),
2266                    _ => None,
2267                }))
2268                .flat_map(|expr| match expr {
2269                    Expr::Identifier(ident) => Some(ident),
2270                    _ => None,
2271                })
2272                .map(ObjectNamePart::Identifier)
2273                .chain(func.name.0)
2274                .collect::<Vec<_>>();
2275            func.name = ObjectName(compound_func_name);
2276
2277            return Ok(Expr::Function(func));
2278        }
2279
2280        // Flatten qualified outer join expressions.
2281        // For example, the expression `T.foo(+)` should
2282        // represent an outer join on the column name `T.foo`
2283        // rather than a composite expression.
2284        if access_chain.len() == 1
2285            && matches!(
2286                access_chain.last(),
2287                Some(AccessExpr::Dot(Expr::OuterJoin(_)))
2288            )
2289        {
2290            let Some(AccessExpr::Dot(Expr::OuterJoin(inner_expr))) = access_chain.pop() else {
2291                return parser_err!("expected (+) expression", root.span().start);
2292            };
2293
2294            if !Self::is_all_ident(&root, &[]) {
2295                return parser_err!("column identifier before (+)", root.span().start);
2296            };
2297
2298            let token_start = root.span().start;
2299            let mut idents = Self::exprs_to_idents(root, vec![])?;
2300            match *inner_expr {
2301                Expr::CompoundIdentifier(suffix) => idents.extend(suffix),
2302                Expr::Identifier(suffix) => idents.push(suffix),
2303                _ => {
2304                    return parser_err!("column identifier before (+)", token_start);
2305                }
2306            }
2307
2308            return Ok(Expr::OuterJoin(Expr::CompoundIdentifier(idents).into()));
2309        }
2310
2311        Ok(Expr::CompoundFieldAccess {
2312            root: Box::new(root),
2313            access_chain,
2314        })
2315    }
2316
2317    fn keyword_to_modifier(k: Keyword) -> Option<ContextModifier> {
2318        match k {
2319            Keyword::LOCAL => Some(ContextModifier::Local),
2320            Keyword::GLOBAL => Some(ContextModifier::Global),
2321            Keyword::SESSION => Some(ContextModifier::Session),
2322            _ => None,
2323        }
2324    }
2325
2326    /// Check if the root is an identifier and all fields are identifiers.
2327    fn is_all_ident(root: &Expr, fields: &[AccessExpr]) -> bool {
2328        if !matches!(root, Expr::Identifier(_)) {
2329            return false;
2330        }
2331        fields
2332            .iter()
2333            .all(|x| matches!(x, AccessExpr::Dot(Expr::Identifier(_))))
2334    }
2335
2336    /// Convert a root and a list of fields to a list of identifiers.
2337    fn exprs_to_idents(root: Expr, fields: Vec<AccessExpr>) -> Result<Vec<Ident>, ParserError> {
2338        let mut idents = vec![];
2339        if let Expr::Identifier(root) = root {
2340            idents.push(root);
2341            for x in fields {
2342                if let AccessExpr::Dot(Expr::Identifier(ident)) = x {
2343                    idents.push(ident);
2344                } else {
2345                    return parser_err!(
2346                        format!("Expected identifier, found: {}", x),
2347                        x.span().start
2348                    );
2349                }
2350            }
2351            Ok(idents)
2352        } else {
2353            parser_err!(
2354                format!("Expected identifier, found: {}", root),
2355                root.span().start
2356            )
2357        }
2358    }
2359
2360    /// Returns true if the next tokens indicate the outer join operator `(+)`.
2361    fn peek_outer_join_operator(&mut self) -> bool {
2362        if !self.dialect.supports_outer_join_operator() {
2363            return false;
2364        }
2365
2366        let [maybe_lparen, maybe_plus, maybe_rparen] = self.peek_tokens_ref();
2367        Token::LParen == maybe_lparen.token
2368            && Token::Plus == maybe_plus.token
2369            && Token::RParen == maybe_rparen.token
2370    }
2371
2372    /// If the next tokens indicates the outer join operator `(+)`, consume
2373    /// the tokens and return true.
2374    fn maybe_parse_outer_join_operator(&mut self) -> bool {
2375        self.dialect.supports_outer_join_operator()
2376            && self.consume_tokens(&[Token::LParen, Token::Plus, Token::RParen])
2377    }
2378
2379    /// Parse utility options in the form of `(option1, option2 arg2, option3 arg3, ...)`
2380    pub fn parse_utility_options(&mut self) -> Result<Vec<UtilityOption>, ParserError> {
2381        self.expect_token(&Token::LParen)?;
2382        let options = self.parse_comma_separated(Self::parse_utility_option)?;
2383        self.expect_token(&Token::RParen)?;
2384
2385        Ok(options)
2386    }
2387
2388    fn parse_utility_option(&mut self) -> Result<UtilityOption, ParserError> {
2389        let name = self.parse_identifier()?;
2390
2391        let next_token = self.peek_token_ref();
2392        if next_token == &Token::Comma || next_token == &Token::RParen {
2393            return Ok(UtilityOption { name, arg: None });
2394        }
2395        let arg = self.parse_expr()?;
2396
2397        Ok(UtilityOption {
2398            name,
2399            arg: Some(arg),
2400        })
2401    }
2402
2403    fn try_parse_expr_sub_query(&mut self) -> Result<Option<Expr>, ParserError> {
2404        if !self.peek_sub_query() {
2405            return Ok(None);
2406        }
2407
2408        Ok(Some(Expr::Subquery(self.parse_query()?)))
2409    }
2410
2411    fn try_parse_lambda(&mut self) -> Result<Option<Expr>, ParserError> {
2412        if !self.dialect.supports_lambda_functions() {
2413            return Ok(None);
2414        }
2415        self.maybe_parse(|p| {
2416            let params = p.parse_comma_separated(|p| p.parse_lambda_function_parameter())?;
2417            p.expect_token(&Token::RParen)?;
2418            p.expect_token(&Token::Arrow)?;
2419            let expr = p.parse_expr()?;
2420            Ok(Expr::Lambda(LambdaFunction {
2421                params: OneOrManyWithParens::Many(params),
2422                body: Box::new(expr),
2423                syntax: LambdaSyntax::Arrow,
2424            }))
2425        })
2426    }
2427
2428    /// Parses a lambda expression following the `LAMBDA` keyword syntax.
2429    ///
2430    /// Syntax: `LAMBDA <params> : <expr>`
2431    ///
2432    /// Examples:
2433    /// - `LAMBDA x : x + 1`
2434    /// - `LAMBDA x, i : x > i`
2435    ///
2436    /// See <https://duckdb.org/docs/stable/sql/functions/lambda>
2437    fn parse_lambda_expr(&mut self) -> Result<Expr, ParserError> {
2438        // Parse the parameters: either a single identifier or comma-separated identifiers
2439        let params = self.parse_lambda_function_parameters()?;
2440        // Expect the colon separator
2441        self.expect_token(&Token::Colon)?;
2442        // Parse the body expression
2443        let body = self.parse_expr()?;
2444        Ok(Expr::Lambda(LambdaFunction {
2445            params,
2446            body: Box::new(body),
2447            syntax: LambdaSyntax::LambdaKeyword,
2448        }))
2449    }
2450
2451    /// Parses the parameters of a lambda function with optional typing.
2452    fn parse_lambda_function_parameters(
2453        &mut self,
2454    ) -> Result<OneOrManyWithParens<LambdaFunctionParameter>, ParserError> {
2455        // Parse the parameters: either a single identifier or comma-separated identifiers
2456        let params = if self.consume_token(&Token::LParen) {
2457            // Parenthesized parameters: (x, y)
2458            let params = self.parse_comma_separated(|p| p.parse_lambda_function_parameter())?;
2459            self.expect_token(&Token::RParen)?;
2460            OneOrManyWithParens::Many(params)
2461        } else {
2462            // Unparenthesized parameters: x or x, y
2463            let params = self.parse_comma_separated(|p| p.parse_lambda_function_parameter())?;
2464            if params.len() == 1 {
2465                OneOrManyWithParens::One(params.into_iter().next().unwrap())
2466            } else {
2467                OneOrManyWithParens::Many(params)
2468            }
2469        };
2470        Ok(params)
2471    }
2472
2473    /// Parses a single parameter of a lambda function, with optional typing.
2474    fn parse_lambda_function_parameter(&mut self) -> Result<LambdaFunctionParameter, ParserError> {
2475        let name = self.parse_identifier()?;
2476        let data_type = match &self.peek_token_ref().token {
2477            Token::Word(_) => self.maybe_parse(|p| p.parse_data_type())?,
2478            _ => None,
2479        };
2480        Ok(LambdaFunctionParameter { name, data_type })
2481    }
2482
2483    /// Tries to parse the body of an [ODBC escaping sequence]
2484    /// i.e. without the enclosing braces
2485    /// Currently implemented:
2486    /// Scalar Function Calls
2487    /// Date, Time, and Timestamp Literals
2488    /// See <https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/escape-sequences-in-odbc?view=sql-server-2017>
2489    fn maybe_parse_odbc_body(&mut self) -> Result<Option<Expr>, ParserError> {
2490        // Attempt 1: Try to parse it as a function.
2491        if let Some(expr) = self.maybe_parse_odbc_fn_body()? {
2492            return Ok(Some(expr));
2493        }
2494        // Attempt 2: Try to parse it as a Date, Time or Timestamp Literal
2495        self.maybe_parse_odbc_body_datetime()
2496    }
2497
2498    /// Tries to parse the body of an [ODBC Date, Time, and Timestamp Literals] call.
2499    ///
2500    /// ```sql
2501    /// {d '2025-07-17'}
2502    /// {t '14:12:01'}
2503    /// {ts '2025-07-17 14:12:01'}
2504    /// ```
2505    ///
2506    /// [ODBC Date, Time, and Timestamp Literals]:
2507    /// https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/date-time-and-timestamp-literals?view=sql-server-2017
2508    fn maybe_parse_odbc_body_datetime(&mut self) -> Result<Option<Expr>, ParserError> {
2509        self.maybe_parse(|p| {
2510            let token = p.next_token().clone();
2511            let word_string = token.token.to_string();
2512            let data_type = match word_string.as_str() {
2513                "t" => DataType::Time(None, TimezoneInfo::None),
2514                "d" => DataType::Date,
2515                "ts" => DataType::Timestamp(None, TimezoneInfo::None),
2516                _ => return p.expected("ODBC datetime keyword (t, d, or ts)", token),
2517            };
2518            let value = p.parse_value()?;
2519            Ok(Expr::TypedString(TypedString {
2520                data_type,
2521                value,
2522                uses_odbc_syntax: true,
2523            }))
2524        })
2525    }
2526
2527    /// Tries to parse the body of an [ODBC function] call.
2528    /// i.e. without the enclosing braces
2529    ///
2530    /// ```sql
2531    /// fn myfunc(1,2,3)
2532    /// ```
2533    ///
2534    /// [ODBC function]: https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/scalar-function-calls?view=sql-server-2017
2535    fn maybe_parse_odbc_fn_body(&mut self) -> Result<Option<Expr>, ParserError> {
2536        self.maybe_parse(|p| {
2537            p.expect_keyword(Keyword::FN)?;
2538            let fn_name = p.parse_object_name(false)?;
2539            let mut fn_call = p.parse_function_call(fn_name)?;
2540            fn_call.uses_odbc_syntax = true;
2541            Ok(Expr::Function(fn_call))
2542        })
2543    }
2544
2545    /// Parse the argument list of `XMLPARSE({ DOCUMENT | CONTENT } value)`,
2546    /// including the closing parenthesis. The mode word becomes the name of the
2547    /// single argument, with no operator between it and the value.
2548    fn parse_xmlparse_argument_list(&mut self) -> Result<FunctionArgumentList, ParserError> {
2549        let arg = FunctionArg::Named {
2550            name: self.parse_identifier()?,
2551            arg: FunctionArgExpr::Expr(self.parse_expr()?),
2552            operator: FunctionArgOperator::Space,
2553        };
2554        self.expect_token(&Token::RParen)?;
2555        Ok(FunctionArgumentList {
2556            duplicate_treatment: None,
2557            args: vec![arg],
2558            clauses: vec![],
2559        })
2560    }
2561
2562    /// Parse a function call expression named by `name` and return it as an `Expr`.
2563    pub fn parse_function(&mut self, name: ObjectName) -> Result<Expr, ParserError> {
2564        self.parse_function_call(name).map(Expr::Function)
2565    }
2566
2567    fn parse_function_call(&mut self, name: ObjectName) -> Result<Function, ParserError> {
2568        self.expect_token(&Token::LParen)?;
2569
2570        // Snowflake permits a subquery to be passed as an argument without
2571        // an enclosing set of parens if it's the only argument.
2572        if self.dialect.supports_subquery_as_function_arg() && self.peek_sub_query() {
2573            let subquery = self.parse_query()?;
2574            self.expect_token(&Token::RParen)?;
2575            return Ok(Function {
2576                name,
2577                uses_odbc_syntax: false,
2578                parameters: FunctionArguments::None,
2579                args: FunctionArguments::Subquery(subquery),
2580                filter: None,
2581                null_treatment: None,
2582                over: None,
2583                within_group: vec![],
2584            });
2585        }
2586
2587        let mut args = if self.dialect.supports_xml_expressions()
2588            && Self::is_simple_unquoted_object_name(&name, "xmlparse")
2589        {
2590            self.parse_xmlparse_argument_list()?
2591        } else {
2592            self.parse_function_argument_list()?
2593        };
2594        let mut parameters = FunctionArguments::None;
2595        // ClickHouse aggregations support parametric functions like `HISTOGRAM(0.5, 0.6)(x, y)`
2596        // which (0.5, 0.6) is a parameter to the function.
2597        if dialect_of!(self is ClickHouseDialect | GenericDialect)
2598            && self.consume_token(&Token::LParen)
2599        {
2600            parameters = FunctionArguments::List(args);
2601            args = self.parse_function_argument_list()?;
2602        }
2603
2604        let within_group = if self.parse_keywords(&[Keyword::WITHIN, Keyword::GROUP]) {
2605            self.expect_token(&Token::LParen)?;
2606            self.expect_keywords(&[Keyword::ORDER, Keyword::BY])?;
2607            let order_by = self.parse_comma_separated(Parser::parse_order_by_expr)?;
2608            self.expect_token(&Token::RParen)?;
2609            order_by
2610        } else {
2611            vec![]
2612        };
2613
2614        let filter = if self.dialect.supports_filter_during_aggregation()
2615            && self.parse_keyword(Keyword::FILTER)
2616            && self.consume_token(&Token::LParen)
2617            && self.parse_keyword(Keyword::WHERE)
2618        {
2619            let filter = Some(Box::new(self.parse_expr()?));
2620            self.expect_token(&Token::RParen)?;
2621            filter
2622        } else {
2623            None
2624        };
2625
2626        // Syntax for null treatment shows up either in the args list
2627        // or after the function call, but not both.
2628        let null_treatment = if args
2629            .clauses
2630            .iter()
2631            .all(|clause| !matches!(clause, FunctionArgumentClause::IgnoreOrRespectNulls(_)))
2632        {
2633            self.parse_null_treatment()?
2634        } else {
2635            None
2636        };
2637
2638        let over = if self.parse_keyword(Keyword::OVER) {
2639            if self.consume_token(&Token::LParen) {
2640                let window_spec = self.parse_window_spec()?;
2641                Some(WindowType::WindowSpec(window_spec))
2642            } else {
2643                Some(WindowType::NamedWindow(self.parse_identifier()?))
2644            }
2645        } else {
2646            None
2647        };
2648
2649        Ok(Function {
2650            name,
2651            uses_odbc_syntax: false,
2652            parameters,
2653            args: FunctionArguments::List(args),
2654            null_treatment,
2655            filter,
2656            over,
2657            within_group,
2658        })
2659    }
2660
2661    /// Optionally parses a null treatment clause.
2662    fn parse_null_treatment(&mut self) -> Result<Option<NullTreatment>, ParserError> {
2663        match self.parse_one_of_keywords(&[Keyword::RESPECT, Keyword::IGNORE]) {
2664            Some(keyword) => {
2665                self.expect_keyword_is(Keyword::NULLS)?;
2666
2667                Ok(match keyword {
2668                    Keyword::RESPECT => Some(NullTreatment::RespectNulls),
2669                    Keyword::IGNORE => Some(NullTreatment::IgnoreNulls),
2670                    _ => None,
2671                })
2672            }
2673            None => Ok(None),
2674        }
2675    }
2676
2677    /// Parse time-related function `name` possibly followed by `(...)` arguments.
2678    pub fn parse_time_functions(&mut self, name: ObjectName) -> Result<Expr, ParserError> {
2679        let args = if self.consume_token(&Token::LParen) {
2680            FunctionArguments::List(self.parse_function_argument_list()?)
2681        } else {
2682            FunctionArguments::None
2683        };
2684        Ok(Expr::Function(Function {
2685            name,
2686            uses_odbc_syntax: false,
2687            parameters: FunctionArguments::None,
2688            args,
2689            filter: None,
2690            over: None,
2691            null_treatment: None,
2692            within_group: vec![],
2693        }))
2694    }
2695
2696    /// Parse window frame `UNITS` clause: `ROWS`, `RANGE`, or `GROUPS`.
2697    pub fn parse_window_frame_units(&mut self) -> Result<WindowFrameUnits, ParserError> {
2698        let next_token = self.next_token();
2699        match &next_token.token {
2700            Token::Word(w) => match w.keyword {
2701                Keyword::ROWS => Ok(WindowFrameUnits::Rows),
2702                Keyword::RANGE => Ok(WindowFrameUnits::Range),
2703                Keyword::GROUPS => Ok(WindowFrameUnits::Groups),
2704                _ => self.expected("ROWS, RANGE, GROUPS", next_token)?,
2705            },
2706            _ => self.expected("ROWS, RANGE, GROUPS", next_token),
2707        }
2708    }
2709
2710    /// Parse a `WINDOW` frame definition (units and bounds).
2711    pub fn parse_window_frame(&mut self) -> Result<WindowFrame, ParserError> {
2712        let units = self.parse_window_frame_units()?;
2713        let (start_bound, end_bound) = if self.parse_keyword(Keyword::BETWEEN) {
2714            let start_bound = self.parse_window_frame_bound()?;
2715            self.expect_keyword_is(Keyword::AND)?;
2716            let end_bound = Some(self.parse_window_frame_bound()?);
2717            (start_bound, end_bound)
2718        } else {
2719            (self.parse_window_frame_bound()?, None)
2720        };
2721        Ok(WindowFrame {
2722            units,
2723            start_bound,
2724            end_bound,
2725        })
2726    }
2727
2728    /// Parse a window frame bound: `CURRENT ROW` or `<n> PRECEDING|FOLLOWING`.
2729    pub fn parse_window_frame_bound(&mut self) -> Result<WindowFrameBound, ParserError> {
2730        if self.parse_keywords(&[Keyword::CURRENT, Keyword::ROW]) {
2731            Ok(WindowFrameBound::CurrentRow)
2732        } else {
2733            let rows = if self.parse_keyword(Keyword::UNBOUNDED) {
2734                None
2735            } else {
2736                Some(Box::new(self.parse_expr()?))
2737            };
2738            if self.parse_keyword(Keyword::PRECEDING) {
2739                Ok(WindowFrameBound::Preceding(rows))
2740            } else if self.parse_keyword(Keyword::FOLLOWING) {
2741                Ok(WindowFrameBound::Following(rows))
2742            } else {
2743                self.expected_ref("PRECEDING or FOLLOWING", self.peek_token_ref())
2744            }
2745        }
2746    }
2747
2748    /// Parse a group by expr. Group by expr can be one of group sets, roll up, cube, or simple expr.
2749    fn parse_group_by_expr(&mut self) -> Result<Expr, ParserError> {
2750        if self.dialect.supports_group_by_expr() {
2751            if self.parse_keywords(&[Keyword::GROUPING, Keyword::SETS]) {
2752                self.expect_token(&Token::LParen)?;
2753                let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?;
2754                self.expect_token(&Token::RParen)?;
2755                Ok(Expr::GroupingSets(result))
2756            } else if self.parse_keyword(Keyword::CUBE) {
2757                self.expect_token(&Token::LParen)?;
2758                let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?;
2759                self.expect_token(&Token::RParen)?;
2760                Ok(Expr::Cube(result))
2761            } else if self.parse_keyword(Keyword::ROLLUP) {
2762                self.expect_token(&Token::LParen)?;
2763                let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?;
2764                self.expect_token(&Token::RParen)?;
2765                Ok(Expr::Rollup(result))
2766            } else if self.consume_tokens(&[Token::LParen, Token::RParen]) {
2767                // PostgreSQL allow to use empty tuple as a group by expression,
2768                // e.g. `GROUP BY (), name`. Please refer to GROUP BY Clause section in
2769                // [PostgreSQL](https://www.postgresql.org/docs/16/sql-select.html)
2770                Ok(Expr::Tuple(vec![]))
2771            } else {
2772                self.parse_expr()
2773            }
2774        } else {
2775            // TODO parse rollup for other dialects
2776            self.parse_expr()
2777        }
2778    }
2779
2780    /// Parse a tuple with `(` and `)`.
2781    /// If `lift_singleton` is true, then a singleton tuple is lifted to a tuple of length 1, otherwise it will fail.
2782    /// If `allow_empty` is true, then an empty tuple is allowed.
2783    fn parse_tuple(
2784        &mut self,
2785        lift_singleton: bool,
2786        allow_empty: bool,
2787    ) -> Result<Vec<Expr>, ParserError> {
2788        if lift_singleton {
2789            if self.consume_token(&Token::LParen) {
2790                let result = if allow_empty && self.consume_token(&Token::RParen) {
2791                    vec![]
2792                } else {
2793                    let result = self.parse_comma_separated(Parser::parse_expr)?;
2794                    self.expect_token(&Token::RParen)?;
2795                    result
2796                };
2797                Ok(result)
2798            } else {
2799                Ok(vec![self.parse_expr()?])
2800            }
2801        } else {
2802            self.expect_token(&Token::LParen)?;
2803            let result = if allow_empty && self.consume_token(&Token::RParen) {
2804                vec![]
2805            } else {
2806                let result = self.parse_comma_separated(Parser::parse_expr)?;
2807                self.expect_token(&Token::RParen)?;
2808                result
2809            };
2810            Ok(result)
2811        }
2812    }
2813
2814    /// Parse a `CASE` expression and return an [`Expr::Case`].
2815    pub fn parse_case_expr(&mut self) -> Result<Expr, ParserError> {
2816        let case_token = AttachedToken(self.get_current_token().clone());
2817        let mut operand = None;
2818        if !self.parse_keyword(Keyword::WHEN) {
2819            operand = Some(Box::new(self.parse_expr()?));
2820            self.expect_keyword_is(Keyword::WHEN)?;
2821        }
2822        let mut conditions = vec![];
2823        loop {
2824            let condition = self.parse_expr()?;
2825            self.expect_keyword_is(Keyword::THEN)?;
2826            let result = self.parse_expr()?;
2827            conditions.push(CaseWhen { condition, result });
2828            if !self.parse_keyword(Keyword::WHEN) {
2829                break;
2830            }
2831        }
2832        let else_result = if self.parse_keyword(Keyword::ELSE) {
2833            Some(Box::new(self.parse_expr()?))
2834        } else {
2835            None
2836        };
2837        let end_token = AttachedToken(self.expect_keyword(Keyword::END)?);
2838        Ok(Expr::Case {
2839            case_token,
2840            end_token,
2841            operand,
2842            conditions,
2843            else_result,
2844        })
2845    }
2846
2847    /// Parse an optional `FORMAT` clause for `CAST` expressions.
2848    pub fn parse_optional_cast_format(&mut self) -> Result<Option<CastFormat>, ParserError> {
2849        if self.parse_keyword(Keyword::FORMAT) {
2850            let value = self.parse_value()?;
2851            match self.parse_optional_time_zone()? {
2852                Some(tz) => Ok(Some(CastFormat::ValueAtTimeZone(value, tz))),
2853                None => Ok(Some(CastFormat::Value(value))),
2854            }
2855        } else {
2856            Ok(None)
2857        }
2858    }
2859
2860    /// Parse an optional `AT TIME ZONE` clause.
2861    pub fn parse_optional_time_zone(&mut self) -> Result<Option<ValueWithSpan>, ParserError> {
2862        if self.parse_keywords(&[Keyword::AT, Keyword::TIME, Keyword::ZONE]) {
2863            self.parse_value().map(Some)
2864        } else {
2865            Ok(None)
2866        }
2867    }
2868
2869    /// mssql-like convert function
2870    fn parse_mssql_convert(&mut self, is_try: bool) -> Result<Expr, ParserError> {
2871        self.expect_token(&Token::LParen)?;
2872        let data_type = self.parse_data_type()?;
2873        self.expect_token(&Token::Comma)?;
2874        let expr = self.parse_expr()?;
2875        let styles = if self.consume_token(&Token::Comma) {
2876            self.parse_comma_separated(Parser::parse_expr)?
2877        } else {
2878            Default::default()
2879        };
2880        self.expect_token(&Token::RParen)?;
2881        Ok(Expr::Convert {
2882            is_try,
2883            expr: Box::new(expr),
2884            data_type: Some(data_type),
2885            charset: None,
2886            target_before_value: true,
2887            styles,
2888        })
2889    }
2890
2891    /// Parse a SQL CONVERT function:
2892    ///  - `CONVERT('héhé' USING utf8mb4)` (MySQL)
2893    ///  - `CONVERT('héhé', CHAR CHARACTER SET utf8mb4)` (MySQL)
2894    ///  - `CONVERT(DECIMAL(10, 5), 42)` (MSSQL) - the type comes first
2895    pub fn parse_convert_expr(&mut self, is_try: bool) -> Result<Expr, ParserError> {
2896        if self.dialect.convert_type_before_value() {
2897            return self.parse_mssql_convert(is_try);
2898        }
2899        self.expect_token(&Token::LParen)?;
2900        let expr = self.parse_expr()?;
2901        if self.parse_keyword(Keyword::USING) {
2902            let charset = self.parse_object_name(false)?;
2903            self.expect_token(&Token::RParen)?;
2904            return Ok(Expr::Convert {
2905                is_try,
2906                expr: Box::new(expr),
2907                data_type: None,
2908                charset: Some(charset),
2909                target_before_value: false,
2910                styles: vec![],
2911            });
2912        }
2913        self.expect_token(&Token::Comma)?;
2914        let data_type = self.parse_data_type()?;
2915        let charset = if self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET]) {
2916            Some(self.parse_object_name(false)?)
2917        } else {
2918            None
2919        };
2920        self.expect_token(&Token::RParen)?;
2921        Ok(Expr::Convert {
2922            is_try,
2923            expr: Box::new(expr),
2924            data_type: Some(data_type),
2925            charset,
2926            target_before_value: false,
2927            styles: vec![],
2928        })
2929    }
2930
2931    /// Parse a SQL CAST function e.g. `CAST(expr AS FLOAT)`
2932    pub fn parse_cast_expr(&mut self, kind: CastKind) -> Result<Expr, ParserError> {
2933        self.expect_token(&Token::LParen)?;
2934        let expr = self.parse_expr()?;
2935        self.expect_keyword_is(Keyword::AS)?;
2936        let data_type = if self.dialect.supports_cast_empty_data_type_to_unspecified()
2937            && self.peek_token_ref().token == Token::RParen
2938        {
2939            DataType::Unspecified
2940        } else {
2941            self.parse_data_type()?
2942        };
2943        let format = self.parse_optional_cast_format()?;
2944        self.expect_token(&Token::RParen)?;
2945        Ok(Expr::Cast {
2946            kind,
2947            expr: Box::new(expr),
2948            data_type,
2949            format,
2950        })
2951    }
2952
2953    /// Parse a SQL EXISTS expression e.g. `WHERE EXISTS(SELECT ...)`.
2954    pub fn parse_exists_expr(&mut self, negated: bool) -> Result<Expr, ParserError> {
2955        self.expect_token(&Token::LParen)?;
2956        let exists_node = Expr::Exists {
2957            negated,
2958            subquery: self.parse_query()?,
2959        };
2960        self.expect_token(&Token::RParen)?;
2961        Ok(exists_node)
2962    }
2963
2964    /// Parse a SQL `EXTRACT` expression e.g. `EXTRACT(YEAR FROM date)`.
2965    pub fn parse_extract_expr(&mut self) -> Result<Expr, ParserError> {
2966        self.expect_token(&Token::LParen)?;
2967        let field = self.parse_date_time_field()?;
2968
2969        let syntax = if self.parse_keyword(Keyword::FROM) {
2970            ExtractSyntax::From
2971        } else if self.dialect.supports_extract_comma_syntax() && self.consume_token(&Token::Comma)
2972        {
2973            ExtractSyntax::Comma
2974        } else {
2975            return Err(ParserError::ParserError(
2976                "Expected 'FROM' or ','".to_string(),
2977            ));
2978        };
2979
2980        let expr = self.parse_expr()?;
2981        self.expect_token(&Token::RParen)?;
2982        Ok(Expr::Extract {
2983            field,
2984            expr: Box::new(expr),
2985            syntax,
2986        })
2987    }
2988
2989    /// Parse a `CEIL` or `FLOOR` expression.
2990    pub fn parse_ceil_floor_expr(&mut self, is_ceil: bool) -> Result<Expr, ParserError> {
2991        self.expect_token(&Token::LParen)?;
2992        let expr = self.parse_expr()?;
2993        // Parse `CEIL/FLOOR(expr)`
2994        let field = if self.parse_keyword(Keyword::TO) {
2995            // Parse `CEIL/FLOOR(expr TO DateTimeField)`
2996            CeilFloorKind::DateTimeField(self.parse_date_time_field()?)
2997        } else if self.consume_token(&Token::Comma) {
2998            // Parse `CEIL/FLOOR(expr, scale)`
2999            let v = self.parse_value()?;
3000            if matches!(v.value, Value::Number(_, _)) {
3001                CeilFloorKind::Scale(v)
3002            } else {
3003                return Err(ParserError::ParserError(
3004                    "Scale field can only be of number type".to_string(),
3005                ));
3006            }
3007        } else {
3008            CeilFloorKind::DateTimeField(DateTimeField::NoDateTime)
3009        };
3010        self.expect_token(&Token::RParen)?;
3011        if is_ceil {
3012            Ok(Expr::Ceil {
3013                expr: Box::new(expr),
3014                field,
3015            })
3016        } else {
3017            Ok(Expr::Floor {
3018                expr: Box::new(expr),
3019                field,
3020            })
3021        }
3022    }
3023
3024    /// Parse a `POSITION` expression.
3025    pub fn parse_position_expr(&mut self, ident: Ident) -> Result<Expr, ParserError> {
3026        let between_prec = self.dialect.prec_value(Precedence::Between);
3027        let position_expr = self.maybe_parse(|p| {
3028            // PARSE SELECT POSITION('@' in field)
3029            p.expect_token(&Token::LParen)?;
3030
3031            // Parse the subexpr till the IN keyword
3032            let expr = p.parse_subexpr(between_prec)?;
3033            p.expect_keyword_is(Keyword::IN)?;
3034            let from = p.parse_expr()?;
3035            p.expect_token(&Token::RParen)?;
3036            Ok(Expr::Position {
3037                expr: Box::new(expr),
3038                r#in: Box::new(from),
3039            })
3040        })?;
3041        match position_expr {
3042            Some(expr) => Ok(expr),
3043            // Snowflake supports `position` as an ordinary function call
3044            // without the special `IN` syntax.
3045            None => self.parse_function(ObjectName::from(vec![ident])),
3046        }
3047    }
3048
3049    /// Parse `SUBSTRING`/`SUBSTR` expressions: `SUBSTRING(expr FROM start FOR length)` or `SUBSTR(expr, start, length)`.
3050    pub fn parse_substring(&mut self) -> Result<Expr, ParserError> {
3051        let shorthand = match self.expect_one_of_keywords(&[Keyword::SUBSTR, Keyword::SUBSTRING])? {
3052            Keyword::SUBSTR => true,
3053            Keyword::SUBSTRING => false,
3054            _ => {
3055                self.prev_token();
3056                return self.expected_ref("SUBSTR or SUBSTRING", self.peek_token_ref());
3057            }
3058        };
3059        self.expect_token(&Token::LParen)?;
3060        let expr = self.parse_expr()?;
3061        let mut from_expr = None;
3062        let special = self.consume_token(&Token::Comma);
3063        if special || self.parse_keyword(Keyword::FROM) {
3064            from_expr = Some(self.parse_expr()?);
3065        }
3066
3067        let mut to_expr = None;
3068        if self.parse_keyword(Keyword::FOR) || self.consume_token(&Token::Comma) {
3069            to_expr = Some(self.parse_expr()?);
3070        }
3071        self.expect_token(&Token::RParen)?;
3072
3073        Ok(Expr::Substring {
3074            expr: Box::new(expr),
3075            substring_from: from_expr.map(Box::new),
3076            substring_for: to_expr.map(Box::new),
3077            special,
3078            shorthand,
3079        })
3080    }
3081
3082    /// Parse an OVERLAY expression.
3083    ///
3084    /// See [Expr::Overlay]
3085    pub fn parse_overlay_expr(&mut self) -> Result<Expr, ParserError> {
3086        // PARSE OVERLAY (EXPR PLACING EXPR FROM 1 [FOR 3])
3087        self.expect_token(&Token::LParen)?;
3088        let expr = self.parse_expr()?;
3089        self.expect_keyword_is(Keyword::PLACING)?;
3090        let what_expr = self.parse_expr()?;
3091        self.expect_keyword_is(Keyword::FROM)?;
3092        let from_expr = self.parse_expr()?;
3093        let mut for_expr = None;
3094        if self.parse_keyword(Keyword::FOR) {
3095            for_expr = Some(self.parse_expr()?);
3096        }
3097        self.expect_token(&Token::RParen)?;
3098
3099        Ok(Expr::Overlay {
3100            expr: Box::new(expr),
3101            overlay_what: Box::new(what_expr),
3102            overlay_from: Box::new(from_expr),
3103            overlay_for: for_expr.map(Box::new),
3104        })
3105    }
3106
3107    /// ```sql
3108    /// TRIM ([WHERE] ['text' FROM] 'text')
3109    /// TRIM ('text')
3110    /// TRIM(<expr>, [, characters]) -- PostgreSQL, DuckDB, Snowflake, BigQuery, Generic
3111    /// ```
3112    pub fn parse_trim_expr(&mut self) -> Result<Expr, ParserError> {
3113        self.expect_token(&Token::LParen)?;
3114        let mut trim_where = None;
3115        if let Token::Word(word) = &self.peek_token_ref().token {
3116            if [Keyword::BOTH, Keyword::LEADING, Keyword::TRAILING].contains(&word.keyword) {
3117                trim_where = Some(self.parse_trim_where()?);
3118            }
3119        }
3120        if self.dialect.supports_comma_separated_trim() && self.parse_keyword(Keyword::FROM) {
3121            let expr = self.parse_expr()?;
3122            let trim_characters = if self.consume_token(&Token::Comma) {
3123                Some(self.parse_comma_separated(Parser::parse_expr)?)
3124            } else {
3125                None
3126            };
3127            self.expect_token(&Token::RParen)?;
3128            return Ok(Expr::Trim {
3129                expr: Box::new(expr),
3130                trim_where,
3131                trim_what: None,
3132                trim_characters,
3133            });
3134        }
3135        let expr = self.parse_expr()?;
3136        if self.parse_keyword(Keyword::FROM) {
3137            let trim_what = Box::new(expr);
3138            let expr = self.parse_expr()?;
3139            self.expect_token(&Token::RParen)?;
3140            Ok(Expr::Trim {
3141                expr: Box::new(expr),
3142                trim_where,
3143                trim_what: Some(trim_what),
3144                trim_characters: None,
3145            })
3146        } else if self.dialect.supports_comma_separated_trim() && self.consume_token(&Token::Comma)
3147        {
3148            let characters = self.parse_comma_separated(Parser::parse_expr)?;
3149            self.expect_token(&Token::RParen)?;
3150            Ok(Expr::Trim {
3151                expr: Box::new(expr),
3152                trim_where,
3153                trim_what: None,
3154                trim_characters: Some(characters),
3155            })
3156        } else {
3157            self.expect_token(&Token::RParen)?;
3158            Ok(Expr::Trim {
3159                expr: Box::new(expr),
3160                trim_where,
3161                trim_what: None,
3162                trim_characters: None,
3163            })
3164        }
3165    }
3166
3167    /// Parse the `WHERE` field for a `TRIM` expression.
3168    ///
3169    /// See [TrimWhereField]
3170    pub fn parse_trim_where(&mut self) -> Result<TrimWhereField, ParserError> {
3171        let next_token = self.next_token();
3172        match &next_token.token {
3173            Token::Word(w) => match w.keyword {
3174                Keyword::BOTH => Ok(TrimWhereField::Both),
3175                Keyword::LEADING => Ok(TrimWhereField::Leading),
3176                Keyword::TRAILING => Ok(TrimWhereField::Trailing),
3177                _ => self.expected("trim_where field", next_token)?,
3178            },
3179            _ => self.expected("trim_where field", next_token),
3180        }
3181    }
3182
3183    /// Parses an array expression `[ex1, ex2, ..]`
3184    /// if `named` is `true`, came from an expression like  `ARRAY[ex1, ex2]`
3185    pub fn parse_array_expr(&mut self, named: bool) -> Result<Expr, ParserError> {
3186        let exprs = self.parse_comma_separated0(Parser::parse_expr, Token::RBracket)?;
3187        self.expect_token(&Token::RBracket)?;
3188        Ok(Expr::Array(Array { elem: exprs, named }))
3189    }
3190
3191    /// Parse the `ON OVERFLOW` clause for `LISTAGG`.
3192    ///
3193    /// See [`ListAggOnOverflow`]
3194    pub fn parse_listagg_on_overflow(&mut self) -> Result<Option<ListAggOnOverflow>, ParserError> {
3195        if self.parse_keywords(&[Keyword::ON, Keyword::OVERFLOW]) {
3196            if self.parse_keyword(Keyword::ERROR) {
3197                Ok(Some(ListAggOnOverflow::Error))
3198            } else {
3199                self.expect_keyword_is(Keyword::TRUNCATE)?;
3200                let filler = match &self.peek_token_ref().token {
3201                    Token::Word(w)
3202                        if w.keyword == Keyword::WITH || w.keyword == Keyword::WITHOUT =>
3203                    {
3204                        None
3205                    }
3206                    Token::SingleQuotedString(_)
3207                    | Token::EscapedStringLiteral(_)
3208                    | Token::UnicodeStringLiteral(_)
3209                    | Token::NationalStringLiteral(_)
3210                    | Token::QuoteDelimitedStringLiteral(_)
3211                    | Token::NationalQuoteDelimitedStringLiteral(_)
3212                    | Token::HexStringLiteral(_) => Some(Box::new(self.parse_expr()?)),
3213                    _ => self.expected_ref(
3214                        "either filler, WITH, or WITHOUT in LISTAGG",
3215                        self.peek_token_ref(),
3216                    )?,
3217                };
3218                let with_count = self.parse_keyword(Keyword::WITH);
3219                if !with_count && !self.parse_keyword(Keyword::WITHOUT) {
3220                    self.expected_ref("either WITH or WITHOUT in LISTAGG", self.peek_token_ref())?;
3221                }
3222                self.expect_keyword_is(Keyword::COUNT)?;
3223                Ok(Some(ListAggOnOverflow::Truncate { filler, with_count }))
3224            }
3225        } else {
3226            Ok(None)
3227        }
3228    }
3229
3230    /// Parse a date/time field for `EXTRACT`, interval qualifiers, and ceil/floor operations.
3231    ///
3232    /// `EXTRACT` supports a wider set of date/time fields than interval qualifiers,
3233    /// so this function may need to be split in two.
3234    ///
3235    /// See [`DateTimeField`]
3236    pub fn parse_date_time_field(&mut self) -> Result<DateTimeField, ParserError> {
3237        let next_token = self.next_token();
3238        match &next_token.token {
3239            Token::Word(w) => match w.keyword {
3240                Keyword::YEAR => Ok(DateTimeField::Year),
3241                Keyword::YEARS => Ok(DateTimeField::Years),
3242                Keyword::MONTH => Ok(DateTimeField::Month),
3243                Keyword::MONTHS => Ok(DateTimeField::Months),
3244                Keyword::WEEK => {
3245                    let week_day = if dialect_of!(self is BigQueryDialect | GenericDialect)
3246                        && self.consume_token(&Token::LParen)
3247                    {
3248                        let week_day = self.parse_identifier()?;
3249                        self.expect_token(&Token::RParen)?;
3250                        Some(week_day)
3251                    } else {
3252                        None
3253                    };
3254                    Ok(DateTimeField::Week(week_day))
3255                }
3256                Keyword::WEEKS => Ok(DateTimeField::Weeks),
3257                Keyword::DAY => Ok(DateTimeField::Day),
3258                Keyword::DAYOFWEEK => Ok(DateTimeField::DayOfWeek),
3259                Keyword::DAYOFYEAR => Ok(DateTimeField::DayOfYear),
3260                Keyword::DAYS => Ok(DateTimeField::Days),
3261                Keyword::DATE => Ok(DateTimeField::Date),
3262                Keyword::DATETIME => Ok(DateTimeField::Datetime),
3263                Keyword::HOUR => Ok(DateTimeField::Hour),
3264                Keyword::HOURS => Ok(DateTimeField::Hours),
3265                Keyword::MINUTE => Ok(DateTimeField::Minute),
3266                Keyword::MINUTES => Ok(DateTimeField::Minutes),
3267                Keyword::SECOND => Ok(DateTimeField::Second),
3268                Keyword::SECONDS => Ok(DateTimeField::Seconds),
3269                Keyword::CENTURY => Ok(DateTimeField::Century),
3270                Keyword::DECADE => Ok(DateTimeField::Decade),
3271                Keyword::DOY => Ok(DateTimeField::Doy),
3272                Keyword::DOW => Ok(DateTimeField::Dow),
3273                Keyword::EPOCH => Ok(DateTimeField::Epoch),
3274                Keyword::ISODOW => Ok(DateTimeField::Isodow),
3275                Keyword::ISOYEAR => Ok(DateTimeField::Isoyear),
3276                Keyword::ISOWEEK => Ok(DateTimeField::IsoWeek),
3277                Keyword::JULIAN => Ok(DateTimeField::Julian),
3278                Keyword::MICROSECOND => Ok(DateTimeField::Microsecond),
3279                Keyword::MICROSECONDS => Ok(DateTimeField::Microseconds),
3280                Keyword::MILLENIUM => Ok(DateTimeField::Millenium),
3281                Keyword::MILLENNIUM => Ok(DateTimeField::Millennium),
3282                Keyword::MILLISECOND => Ok(DateTimeField::Millisecond),
3283                Keyword::MILLISECONDS => Ok(DateTimeField::Milliseconds),
3284                Keyword::NANOSECOND => Ok(DateTimeField::Nanosecond),
3285                Keyword::NANOSECONDS => Ok(DateTimeField::Nanoseconds),
3286                Keyword::QUARTER => Ok(DateTimeField::Quarter),
3287                Keyword::TIME => Ok(DateTimeField::Time),
3288                Keyword::TIMEZONE => Ok(DateTimeField::Timezone),
3289                Keyword::TIMEZONE_ABBR => Ok(DateTimeField::TimezoneAbbr),
3290                Keyword::TIMEZONE_HOUR => Ok(DateTimeField::TimezoneHour),
3291                Keyword::TIMEZONE_MINUTE => Ok(DateTimeField::TimezoneMinute),
3292                Keyword::TIMEZONE_REGION => Ok(DateTimeField::TimezoneRegion),
3293                _ if self.dialect.allow_extract_custom() => {
3294                    self.prev_token();
3295                    let custom = self.parse_identifier()?;
3296                    Ok(DateTimeField::Custom(custom))
3297                }
3298                _ => self.expected("date/time field", next_token),
3299            },
3300            Token::SingleQuotedString(_) if self.dialect.allow_extract_single_quotes() => {
3301                self.prev_token();
3302                let custom = self.parse_identifier()?;
3303                Ok(DateTimeField::Custom(custom))
3304            }
3305            _ => self.expected("date/time field", next_token),
3306        }
3307    }
3308
3309    /// Parse a `NOT` expression.
3310    ///
3311    /// Represented in the AST as `Expr::UnaryOp` with `UnaryOperator::Not`.
3312    pub fn parse_not(&mut self) -> Result<Expr, ParserError> {
3313        match &self.peek_token_ref().token {
3314            Token::Word(w) => match w.keyword {
3315                Keyword::EXISTS => {
3316                    let negated = true;
3317                    let _ = self.parse_keyword(Keyword::EXISTS);
3318                    self.parse_exists_expr(negated)
3319                }
3320                _ => Ok(Expr::UnaryOp {
3321                    op: UnaryOperator::Not,
3322                    expr: Box::new(
3323                        self.parse_subexpr(self.dialect.prec_value(Precedence::UnaryNot))?,
3324                    ),
3325                }),
3326            },
3327            _ => Ok(Expr::UnaryOp {
3328                op: UnaryOperator::Not,
3329                expr: Box::new(self.parse_subexpr(self.dialect.prec_value(Precedence::UnaryNot))?),
3330            }),
3331        }
3332    }
3333
3334    /// Parse expression types that start with a left brace '{'.
3335    /// Examples:
3336    /// ```sql
3337    /// -- Dictionary expr.
3338    /// {'key1': 'value1', 'key2': 'value2'}
3339    ///
3340    /// -- Function call using the ODBC syntax.
3341    /// { fn CONCAT('foo', 'bar') }
3342    /// ```
3343    fn parse_lbrace_expr(&mut self) -> Result<Expr, ParserError> {
3344        let token = self.expect_token(&Token::LBrace)?;
3345
3346        if let Some(fn_expr) = self.maybe_parse_odbc_body()? {
3347            self.expect_token(&Token::RBrace)?;
3348            return Ok(fn_expr);
3349        }
3350
3351        if self.dialect.supports_dictionary_syntax() {
3352            self.prev_token(); // Put back the '{'
3353            return self.parse_dictionary();
3354        }
3355
3356        self.expected("an expression", token)
3357    }
3358
3359    /// Parses fulltext expressions [`sqlparser::ast::Expr::MatchAgainst`]
3360    ///
3361    /// # Errors
3362    /// This method will raise an error if the column list is empty or with invalid identifiers,
3363    /// the match expression is not a literal string, or if the search modifier is not valid.
3364    pub fn parse_match_against(&mut self) -> Result<Expr, ParserError> {
3365        let columns = self.parse_parenthesized_qualified_column_list(Mandatory, false)?;
3366
3367        self.expect_keyword_is(Keyword::AGAINST)?;
3368
3369        self.expect_token(&Token::LParen)?;
3370
3371        // MySQL is too permissive about the value, IMO we can't validate it perfectly on syntax level.
3372        let match_value = self.parse_value()?;
3373
3374        let in_natural_language_mode_keywords = &[
3375            Keyword::IN,
3376            Keyword::NATURAL,
3377            Keyword::LANGUAGE,
3378            Keyword::MODE,
3379        ];
3380
3381        let with_query_expansion_keywords = &[Keyword::WITH, Keyword::QUERY, Keyword::EXPANSION];
3382
3383        let in_boolean_mode_keywords = &[Keyword::IN, Keyword::BOOLEAN, Keyword::MODE];
3384
3385        let opt_search_modifier = if self.parse_keywords(in_natural_language_mode_keywords) {
3386            if self.parse_keywords(with_query_expansion_keywords) {
3387                Some(SearchModifier::InNaturalLanguageModeWithQueryExpansion)
3388            } else {
3389                Some(SearchModifier::InNaturalLanguageMode)
3390            }
3391        } else if self.parse_keywords(in_boolean_mode_keywords) {
3392            Some(SearchModifier::InBooleanMode)
3393        } else if self.parse_keywords(with_query_expansion_keywords) {
3394            Some(SearchModifier::WithQueryExpansion)
3395        } else {
3396            None
3397        };
3398
3399        self.expect_token(&Token::RParen)?;
3400
3401        Ok(Expr::MatchAgainst {
3402            columns,
3403            match_value,
3404            opt_search_modifier,
3405        })
3406    }
3407
3408    /// Parse an `INTERVAL` expression.
3409    ///
3410    /// Some syntactically valid intervals:
3411    ///
3412    /// ```sql
3413    ///   1. INTERVAL '1' DAY
3414    ///   2. INTERVAL '1-1' YEAR TO MONTH
3415    ///   3. INTERVAL '1' SECOND
3416    ///   4. INTERVAL '1:1:1.1' HOUR (5) TO SECOND (5)
3417    ///   5. INTERVAL '1.1' SECOND (2, 2)
3418    ///   6. INTERVAL '1:1' HOUR (5) TO MINUTE (5)
3419    ///   7. (MySql & BigQuery only): INTERVAL 1 DAY
3420    /// ```
3421    ///
3422    /// Note that we do not currently attempt to parse the quoted value.
3423    #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
3424    pub fn parse_interval(&mut self) -> Result<Expr, ParserError> {
3425        let _guard = self.recursion_counter.try_decrease()?;
3426
3427        // The SQL standard allows an optional sign before the value string, but
3428        // it is not clear if any implementations support that syntax, so we
3429        // don't currently try to parse it. (The sign can instead be included
3430        // inside the value string.)
3431
3432        // to match the different flavours of INTERVAL syntax, we only allow expressions
3433        // if the dialect requires an interval qualifier,
3434        // see https://github.com/sqlparser-rs/sqlparser-rs/pull/1398 for more details
3435        let value = if self.dialect.require_interval_qualifier() {
3436            // parse a whole expression so `INTERVAL 1 + 1 DAY` is valid
3437            self.parse_expr()?
3438        } else {
3439            // parse a prefix expression so `INTERVAL 1 DAY` is valid, but `INTERVAL 1 + 1 DAY` is not
3440            // this also means that `INTERVAL '5 days' > INTERVAL '1 day'` treated properly
3441            self.parse_prefix()?
3442        };
3443
3444        // Following the string literal is a qualifier which indicates the units
3445        // of the duration specified in the string literal.
3446        //
3447        // Note that PostgreSQL allows omitting the qualifier, so we provide
3448        // this more general implementation.
3449        let leading_field = if self.next_token_is_temporal_unit() {
3450            Some(self.parse_date_time_field()?)
3451        } else if self.dialect.require_interval_qualifier() {
3452            return parser_err!(
3453                "INTERVAL requires a unit after the literal value",
3454                self.peek_token_ref().span.start
3455            );
3456        } else {
3457            None
3458        };
3459
3460        let (leading_precision, last_field, fsec_precision) =
3461            if leading_field == Some(DateTimeField::Second) {
3462                // SQL mandates special syntax for `SECOND TO SECOND` literals.
3463                // Instead of
3464                //     `SECOND [(<leading precision>)] TO SECOND[(<fractional seconds precision>)]`
3465                // one must use the special format:
3466                //     `SECOND [( <leading precision> [ , <fractional seconds precision>] )]`
3467                let last_field = None;
3468                let (leading_precision, fsec_precision) = self.parse_optional_precision_scale()?;
3469                (leading_precision, last_field, fsec_precision)
3470            } else {
3471                let leading_precision = self.parse_optional_precision()?;
3472                if self.parse_keyword(Keyword::TO) {
3473                    let last_field = Some(self.parse_date_time_field()?);
3474                    let fsec_precision = if last_field == Some(DateTimeField::Second) {
3475                        self.parse_optional_precision()?
3476                    } else {
3477                        None
3478                    };
3479                    (leading_precision, last_field, fsec_precision)
3480                } else {
3481                    (leading_precision, None, None)
3482                }
3483            };
3484
3485        Ok(Expr::Interval(Interval {
3486            value: Box::new(value),
3487            leading_field,
3488            leading_precision,
3489            last_field,
3490            fractional_seconds_precision: fsec_precision,
3491        }))
3492    }
3493
3494    /// Peek at the next token and determine if it is a temporal unit
3495    /// like `second`.
3496    pub fn next_token_is_temporal_unit(&mut self) -> bool {
3497        if let Token::Word(word) = &self.peek_token_ref().token {
3498            matches!(
3499                word.keyword,
3500                Keyword::YEAR
3501                    | Keyword::YEARS
3502                    | Keyword::MONTH
3503                    | Keyword::MONTHS
3504                    | Keyword::WEEK
3505                    | Keyword::WEEKS
3506                    | Keyword::DAY
3507                    | Keyword::DAYS
3508                    | Keyword::HOUR
3509                    | Keyword::HOURS
3510                    | Keyword::MINUTE
3511                    | Keyword::MINUTES
3512                    | Keyword::SECOND
3513                    | Keyword::SECONDS
3514                    | Keyword::CENTURY
3515                    | Keyword::DECADE
3516                    | Keyword::DOW
3517                    | Keyword::DOY
3518                    | Keyword::EPOCH
3519                    | Keyword::ISODOW
3520                    | Keyword::ISOYEAR
3521                    | Keyword::JULIAN
3522                    | Keyword::MICROSECOND
3523                    | Keyword::MICROSECONDS
3524                    | Keyword::MILLENIUM
3525                    | Keyword::MILLENNIUM
3526                    | Keyword::MILLISECOND
3527                    | Keyword::MILLISECONDS
3528                    | Keyword::NANOSECOND
3529                    | Keyword::NANOSECONDS
3530                    | Keyword::QUARTER
3531                    | Keyword::TIMEZONE
3532                    | Keyword::TIMEZONE_HOUR
3533                    | Keyword::TIMEZONE_MINUTE
3534            )
3535        } else {
3536            false
3537        }
3538    }
3539
3540    /// Syntax
3541    /// ```sql
3542    /// -- typed
3543    /// STRUCT<[field_name] field_type, ...>( expr1 [, ... ])
3544    /// -- typeless
3545    /// STRUCT( expr1 [AS field_name] [, ... ])
3546    /// ```
3547    fn parse_struct_literal(&mut self) -> Result<Expr, ParserError> {
3548        // Parse the fields definition if exist `<[field_name] field_type, ...>`
3549        self.prev_token();
3550        let (fields, trailing_bracket) =
3551            self.parse_struct_type_def(Self::parse_struct_field_def)?;
3552        if trailing_bracket.0 {
3553            return parser_err!(
3554                "unmatched > in STRUCT literal",
3555                self.peek_token_ref().span.start
3556            );
3557        }
3558
3559        // Parse the struct values `(expr1 [, ... ])`
3560        self.expect_token(&Token::LParen)?;
3561        let values = self
3562            .parse_comma_separated(|parser| parser.parse_struct_field_expr(!fields.is_empty()))?;
3563        self.expect_token(&Token::RParen)?;
3564
3565        Ok(Expr::Struct { values, fields })
3566    }
3567
3568    /// Parse an expression value for a struct literal
3569    /// Syntax
3570    /// ```sql
3571    /// expr [AS name]
3572    /// ```
3573    ///
3574    /// For biquery [1], Parameter typed_syntax is set to true if the expression
3575    /// is to be parsed as a field expression declared using typed
3576    /// struct syntax [2], and false if using typeless struct syntax [3].
3577    ///
3578    /// [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#constructing_a_struct
3579    /// [2]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#typed_struct_syntax
3580    /// [3]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#typeless_struct_syntax
3581    fn parse_struct_field_expr(&mut self, typed_syntax: bool) -> Result<Expr, ParserError> {
3582        let expr = self.parse_expr()?;
3583        if self.parse_keyword(Keyword::AS) {
3584            if typed_syntax {
3585                return parser_err!("Typed syntax does not allow AS", {
3586                    self.prev_token();
3587                    self.peek_token_ref().span.start
3588                });
3589            }
3590            let field_name = self.parse_identifier()?;
3591            Ok(Expr::Named {
3592                expr: expr.into(),
3593                name: field_name,
3594            })
3595        } else {
3596            Ok(expr)
3597        }
3598    }
3599
3600    /// Parse a Struct type definition as a sequence of field-value pairs.
3601    /// The syntax of the Struct elem differs by dialect so it is customised
3602    /// by the `elem_parser` argument.
3603    ///
3604    /// Syntax
3605    /// ```sql
3606    /// Hive:
3607    /// STRUCT<field_name: field_type>
3608    ///
3609    /// BigQuery:
3610    /// STRUCT<[field_name] field_type>
3611    /// ```
3612    fn parse_struct_type_def<F>(
3613        &mut self,
3614        mut elem_parser: F,
3615    ) -> Result<(Vec<StructField>, MatchedTrailingBracket), ParserError>
3616    where
3617        F: FnMut(&mut Parser<'a>) -> Result<(StructField, MatchedTrailingBracket), ParserError>,
3618    {
3619        self.expect_keyword_is(Keyword::STRUCT)?;
3620
3621        // Nothing to do if we have no type information.
3622        if self.peek_token_ref().token != Token::Lt {
3623            return Ok((Default::default(), false.into()));
3624        }
3625        self.next_token();
3626
3627        let mut field_defs = vec![];
3628        let trailing_bracket = loop {
3629            let (def, trailing_bracket) = elem_parser(self)?;
3630            field_defs.push(def);
3631            // The struct field definition is finished if it occurs `>>` or comma.
3632            if trailing_bracket.0 || !self.consume_token(&Token::Comma) {
3633                break trailing_bracket;
3634            }
3635        };
3636
3637        Ok((
3638            field_defs,
3639            self.expect_closing_angle_bracket(trailing_bracket)?,
3640        ))
3641    }
3642
3643    /// Duckdb Struct Data Type <https://duckdb.org/docs/sql/data_types/struct.html#retrieving-from-structs>
3644    fn parse_duckdb_struct_type_def(&mut self) -> Result<Vec<StructField>, ParserError> {
3645        self.expect_keyword_is(Keyword::STRUCT)?;
3646        self.expect_token(&Token::LParen)?;
3647        let struct_body = self.parse_comma_separated(|parser| {
3648            let field_name = parser.parse_identifier()?;
3649            let field_type = parser.parse_data_type()?;
3650
3651            Ok(StructField {
3652                field_name: Some(field_name),
3653                field_type,
3654                options: None,
3655            })
3656        });
3657        self.expect_token(&Token::RParen)?;
3658        struct_body
3659    }
3660
3661    /// Parse a field definition in a [struct] or [tuple].
3662    /// Syntax:
3663    ///
3664    /// ```sql
3665    /// [field_name] field_type
3666    /// field_name: field_type
3667    /// ```
3668    ///
3669    /// [struct]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#declaring_a_struct_type
3670    /// [tuple]: https://clickhouse.com/docs/en/sql-reference/data-types/tuple
3671    /// [databricks]: https://docs.databricks.com/en/sql/language-manual/data-types/struct-type.html
3672    fn parse_struct_field_def(
3673        &mut self,
3674    ) -> Result<(StructField, MatchedTrailingBracket), ParserError> {
3675        // Look beyond the next item to infer whether both field name
3676        // and type are specified.
3677        let is_named_field = matches!(
3678            (self.peek_nth_token(0).token, self.peek_nth_token(1).token),
3679            (Token::Word(_), Token::Word(_)) | (Token::Word(_), Token::Colon)
3680        );
3681
3682        let field_name = if is_named_field {
3683            let name = self.parse_identifier()?;
3684            let _ = self.consume_token(&Token::Colon);
3685            Some(name)
3686        } else {
3687            None
3688        };
3689
3690        let (field_type, trailing_bracket) = self.parse_data_type_with_optional_collation()?;
3691
3692        let options = self.maybe_parse_options(Keyword::OPTIONS)?;
3693        Ok((
3694            StructField {
3695                field_name,
3696                field_type,
3697                options,
3698            },
3699            trailing_bracket,
3700        ))
3701    }
3702
3703    /// DuckDB specific: Parse a Union type definition as a sequence of field-value pairs.
3704    ///
3705    /// Syntax:
3706    ///
3707    /// ```sql
3708    /// UNION(field_name field_type[,...])
3709    /// ```
3710    ///
3711    /// [1]: https://duckdb.org/docs/sql/data_types/union.html
3712    fn parse_union_type_def(&mut self) -> Result<Vec<UnionField>, ParserError> {
3713        self.expect_keyword_is(Keyword::UNION)?;
3714
3715        self.expect_token(&Token::LParen)?;
3716
3717        let fields = self.parse_comma_separated(|p| {
3718            Ok(UnionField {
3719                field_name: p.parse_identifier()?,
3720                field_type: p.parse_data_type()?,
3721            })
3722        })?;
3723
3724        self.expect_token(&Token::RParen)?;
3725
3726        Ok(fields)
3727    }
3728
3729    /// DuckDB and ClickHouse specific: Parse a duckdb [dictionary] or a clickhouse [map] setting
3730    ///
3731    /// Syntax:
3732    ///
3733    /// ```sql
3734    /// {'field_name': expr1[, ... ]}
3735    /// ```
3736    ///
3737    /// [dictionary]: https://duckdb.org/docs/sql/data_types/struct#creating-structs
3738    /// [map]: https://clickhouse.com/docs/operations/settings/settings#additional_table_filters
3739    fn parse_dictionary(&mut self) -> Result<Expr, ParserError> {
3740        self.expect_token(&Token::LBrace)?;
3741
3742        let fields = self.parse_comma_separated0(Self::parse_dictionary_field, Token::RBrace)?;
3743
3744        self.expect_token(&Token::RBrace)?;
3745
3746        Ok(Expr::Dictionary(fields))
3747    }
3748
3749    /// Parse a field for a duckdb [dictionary] or a clickhouse [map] setting
3750    ///
3751    /// Syntax
3752    ///
3753    /// ```sql
3754    /// 'name': expr
3755    /// ```
3756    ///
3757    /// [dictionary]: https://duckdb.org/docs/sql/data_types/struct#creating-structs
3758    /// [map]: https://clickhouse.com/docs/operations/settings/settings#additional_table_filters
3759    fn parse_dictionary_field(&mut self) -> Result<DictionaryField, ParserError> {
3760        let key = self.parse_identifier()?;
3761
3762        self.expect_token(&Token::Colon)?;
3763
3764        let expr = self.parse_expr()?;
3765
3766        Ok(DictionaryField {
3767            key,
3768            value: Box::new(expr),
3769        })
3770    }
3771
3772    /// DuckDB specific: Parse a duckdb [map]
3773    ///
3774    /// Syntax:
3775    ///
3776    /// ```sql
3777    /// Map {key1: value1[, ... ]}
3778    /// ```
3779    ///
3780    /// [map]: https://duckdb.org/docs/sql/data_types/map.html#creating-maps
3781    fn parse_duckdb_map_literal(&mut self) -> Result<Expr, ParserError> {
3782        self.expect_token(&Token::LBrace)?;
3783        let fields = self.parse_comma_separated0(Self::parse_duckdb_map_field, Token::RBrace)?;
3784        self.expect_token(&Token::RBrace)?;
3785        Ok(Expr::Map(Map { entries: fields }))
3786    }
3787
3788    /// Parse a field for a duckdb [map]
3789    ///
3790    /// Syntax
3791    ///
3792    /// ```sql
3793    /// key: value
3794    /// ```
3795    ///
3796    /// [map]: https://duckdb.org/docs/sql/data_types/map.html#creating-maps
3797    fn parse_duckdb_map_field(&mut self) -> Result<MapEntry, ParserError> {
3798        // Stop before `:` so it can act as a key/value separator
3799        let key = self.parse_subexpr(self.dialect.prec_value(Precedence::Colon))?;
3800
3801        self.expect_token(&Token::Colon)?;
3802
3803        let value = self.parse_expr()?;
3804
3805        Ok(MapEntry {
3806            key: Box::new(key),
3807            value: Box::new(value),
3808        })
3809    }
3810
3811    /// Parse a parenthesized MAP type (ClickHouse or Snowflake).
3812    ///
3813    /// Syntax
3814    ///
3815    /// ```sql
3816    /// Map(key_data_type, value_data_type)
3817    /// ```
3818    ///
3819    /// [map]: https://clickhouse.com/docs/en/sql-reference/data-types/map
3820    fn parse_parenthesized_map_type_def(
3821        &mut self,
3822    ) -> Result<(DataType, DataType, bool), ParserError> {
3823        self.expect_keyword_is(Keyword::MAP)?;
3824        self.expect_token(&Token::LParen)?;
3825        let key_data_type = self.parse_data_type()?;
3826        self.expect_token(&Token::Comma)?;
3827        let value_data_type = self.parse_data_type()?;
3828        let value_not_null = self.dialect.supports_map_value_not_null()
3829            && self.parse_keywords(&[Keyword::NOT, Keyword::NULL]);
3830        self.expect_token(&Token::RParen)?;
3831
3832        Ok((key_data_type, value_data_type, value_not_null))
3833    }
3834
3835    /// Parse clickhouse [tuple]
3836    ///
3837    /// Syntax
3838    ///
3839    /// ```sql
3840    /// Tuple([field_name] field_type, ...)
3841    /// ```
3842    ///
3843    /// [tuple]: https://clickhouse.com/docs/en/sql-reference/data-types/tuple
3844    fn parse_click_house_tuple_def(&mut self) -> Result<Vec<StructField>, ParserError> {
3845        self.expect_keyword_is(Keyword::TUPLE)?;
3846        self.expect_token(&Token::LParen)?;
3847        let mut field_defs = vec![];
3848        loop {
3849            let (def, _) = self.parse_struct_field_def()?;
3850            field_defs.push(def);
3851            if !self.consume_token(&Token::Comma) {
3852                break;
3853            }
3854        }
3855        self.expect_token(&Token::RParen)?;
3856
3857        Ok(field_defs)
3858    }
3859
3860    /// For nested types that use the angle bracket syntax, this matches either
3861    /// `>`, `>>` or nothing depending on which variant is expected (specified by the previously
3862    /// matched `trailing_bracket` argument). It returns whether there is a trailing
3863    /// left to be matched - (i.e. if '>>' was matched).
3864    fn expect_closing_angle_bracket(
3865        &mut self,
3866        trailing_bracket: MatchedTrailingBracket,
3867    ) -> Result<MatchedTrailingBracket, ParserError> {
3868        let trailing_bracket = if !trailing_bracket.0 {
3869            match &self.peek_token_ref().token {
3870                Token::Gt => {
3871                    self.next_token();
3872                    false.into()
3873                }
3874                Token::ShiftRight => {
3875                    self.next_token();
3876                    true.into()
3877                }
3878                _ => return self.expected_ref(">", self.peek_token_ref()),
3879            }
3880        } else {
3881            false.into()
3882        };
3883
3884        Ok(trailing_bracket)
3885    }
3886
3887    /// Parse an operator following an expression
3888    pub fn parse_infix(&mut self, expr: Expr, precedence: u8) -> Result<Expr, ParserError> {
3889        // allow the dialect to override infix parsing
3890        if let Some(infix) = self.dialect.parse_infix(self, &expr, precedence) {
3891            return infix;
3892        }
3893
3894        let dialect = self.dialect;
3895
3896        self.advance_token();
3897        let tok = self.get_current_token();
3898        debug!("infix: {tok:?}");
3899        let tok_index = self.get_current_index();
3900        let span = tok.span;
3901        let regular_binary_operator = match &tok.token {
3902            Token::Spaceship => Some(BinaryOperator::Spaceship),
3903            Token::DoubleEq => Some(BinaryOperator::Eq),
3904            Token::Assignment => Some(BinaryOperator::Assignment),
3905            Token::Eq => Some(BinaryOperator::Eq),
3906            Token::Neq => Some(BinaryOperator::NotEq),
3907            Token::Gt => Some(BinaryOperator::Gt),
3908            Token::GtEq => Some(BinaryOperator::GtEq),
3909            Token::Lt => Some(BinaryOperator::Lt),
3910            Token::LtEq => Some(BinaryOperator::LtEq),
3911            Token::Plus => Some(BinaryOperator::Plus),
3912            Token::Minus => Some(BinaryOperator::Minus),
3913            Token::Mul => Some(BinaryOperator::Multiply),
3914            Token::Mod => Some(BinaryOperator::Modulo),
3915            Token::StringConcat => Some(BinaryOperator::StringConcat),
3916            Token::Pipe => Some(BinaryOperator::BitwiseOr),
3917            Token::Caret => {
3918                // In PostgreSQL, ^ stands for the exponentiation operation,
3919                // and # stands for XOR. See https://www.postgresql.org/docs/current/functions-math.html
3920                if dialect_is!(dialect is PostgreSqlDialect) {
3921                    Some(BinaryOperator::PGExp)
3922                } else {
3923                    Some(BinaryOperator::BitwiseXor)
3924                }
3925            }
3926            Token::Ampersand => Some(BinaryOperator::BitwiseAnd),
3927            Token::Div => Some(BinaryOperator::Divide),
3928            Token::DuckIntDiv if dialect_is!(dialect is DuckDbDialect | GenericDialect) => {
3929                Some(BinaryOperator::DuckIntegerDivide)
3930            }
3931            Token::ShiftLeft if dialect.supports_bitwise_shift_operators() => {
3932                Some(BinaryOperator::PGBitwiseShiftLeft)
3933            }
3934            Token::ShiftRight if dialect.supports_bitwise_shift_operators() => {
3935                Some(BinaryOperator::PGBitwiseShiftRight)
3936            }
3937            Token::Sharp if dialect_is!(dialect is PostgreSqlDialect | RedshiftSqlDialect) => {
3938                Some(BinaryOperator::PGBitwiseXor)
3939            }
3940            Token::Overlap if dialect_is!(dialect is PostgreSqlDialect | RedshiftSqlDialect) => {
3941                Some(BinaryOperator::PGOverlap)
3942            }
3943            Token::Overlap if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) => {
3944                Some(BinaryOperator::PGOverlap)
3945            }
3946            Token::Overlap if dialect.supports_double_ampersand_operator() => {
3947                Some(BinaryOperator::And)
3948            }
3949            Token::CaretAt if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) => {
3950                Some(BinaryOperator::PGStartsWith)
3951            }
3952            Token::Tilde => Some(BinaryOperator::PGRegexMatch),
3953            Token::TildeAsterisk => Some(BinaryOperator::PGRegexIMatch),
3954            Token::ExclamationMarkTilde => Some(BinaryOperator::PGRegexNotMatch),
3955            Token::ExclamationMarkTildeAsterisk => Some(BinaryOperator::PGRegexNotIMatch),
3956            Token::DoubleTilde => Some(BinaryOperator::PGLikeMatch),
3957            Token::DoubleTildeAsterisk => Some(BinaryOperator::PGILikeMatch),
3958            Token::ExclamationMarkDoubleTilde => Some(BinaryOperator::PGNotLikeMatch),
3959            Token::ExclamationMarkDoubleTildeAsterisk => Some(BinaryOperator::PGNotILikeMatch),
3960            Token::Arrow => Some(BinaryOperator::Arrow),
3961            Token::LongArrow => Some(BinaryOperator::LongArrow),
3962            Token::HashArrow => Some(BinaryOperator::HashArrow),
3963            Token::HashLongArrow => Some(BinaryOperator::HashLongArrow),
3964            Token::AtArrow => Some(BinaryOperator::AtArrow),
3965            Token::ArrowAt => Some(BinaryOperator::ArrowAt),
3966            Token::HashMinus => Some(BinaryOperator::HashMinus),
3967            Token::AtQuestion => Some(BinaryOperator::AtQuestion),
3968            Token::AtAt => Some(BinaryOperator::AtAt),
3969            Token::Question => Some(BinaryOperator::Question),
3970            Token::QuestionAnd => Some(BinaryOperator::QuestionAnd),
3971            Token::QuestionPipe => Some(BinaryOperator::QuestionPipe),
3972            Token::CustomBinaryOperator(s) => Some(BinaryOperator::Custom(s.clone())),
3973            Token::DoubleSharp if self.dialect.supports_geometric_types() => {
3974                Some(BinaryOperator::DoubleHash)
3975            }
3976
3977            Token::AmpersandLeftAngleBracket if self.dialect.supports_geometric_types() => {
3978                Some(BinaryOperator::AndLt)
3979            }
3980            Token::AmpersandRightAngleBracket if self.dialect.supports_geometric_types() => {
3981                Some(BinaryOperator::AndGt)
3982            }
3983            Token::QuestionMarkDash if self.dialect.supports_geometric_types() => {
3984                Some(BinaryOperator::QuestionDash)
3985            }
3986            Token::AmpersandLeftAngleBracketVerticalBar
3987                if self.dialect.supports_geometric_types() =>
3988            {
3989                Some(BinaryOperator::AndLtPipe)
3990            }
3991            Token::VerticalBarAmpersandRightAngleBracket
3992                if self.dialect.supports_geometric_types() =>
3993            {
3994                Some(BinaryOperator::PipeAndGt)
3995            }
3996            Token::TwoWayArrow if self.dialect.supports_geometric_types() => {
3997                Some(BinaryOperator::LtDashGt)
3998            }
3999            Token::LeftAngleBracketCaret if self.dialect.supports_geometric_types() => {
4000                Some(BinaryOperator::LtCaret)
4001            }
4002            Token::RightAngleBracketCaret if self.dialect.supports_geometric_types() => {
4003                Some(BinaryOperator::GtCaret)
4004            }
4005            Token::QuestionMarkSharp if self.dialect.supports_geometric_types() => {
4006                Some(BinaryOperator::QuestionHash)
4007            }
4008            Token::QuestionMarkDoubleVerticalBar if self.dialect.supports_geometric_types() => {
4009                Some(BinaryOperator::QuestionDoublePipe)
4010            }
4011            Token::QuestionMarkDashVerticalBar if self.dialect.supports_geometric_types() => {
4012                Some(BinaryOperator::QuestionDashPipe)
4013            }
4014            Token::TildeEqual if self.dialect.supports_geometric_types() => {
4015                Some(BinaryOperator::TildeEq)
4016            }
4017            Token::ShiftLeftVerticalBar if self.dialect.supports_geometric_types() => {
4018                Some(BinaryOperator::LtLtPipe)
4019            }
4020            Token::VerticalBarShiftRight if self.dialect.supports_geometric_types() => {
4021                Some(BinaryOperator::PipeGtGt)
4022            }
4023            Token::AtSign if self.dialect.supports_geometric_types() => Some(BinaryOperator::At),
4024
4025            Token::Word(w) => match w.keyword {
4026                Keyword::AND => Some(BinaryOperator::And),
4027                Keyword::OR => Some(BinaryOperator::Or),
4028                Keyword::XOR => Some(BinaryOperator::Xor),
4029                Keyword::OVERLAPS => Some(BinaryOperator::Overlaps),
4030                Keyword::OPERATOR if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) => {
4031                    // there are special rules for operator names in
4032                    // postgres so we can not use 'parse_object'
4033                    // or similar.
4034                    // See https://www.postgresql.org/docs/current/sql-createoperator.html
4035                    Some(BinaryOperator::PGCustomBinaryOperator(
4036                        self.parse_pg_operator_ident_parts()?,
4037                    ))
4038                }
4039                _ => None,
4040            },
4041            _ => None,
4042        };
4043
4044        let tok = self.token_at(tok_index);
4045        if let Some(op) = regular_binary_operator {
4046            if let Some(keyword) =
4047                self.parse_one_of_keywords(&[Keyword::ANY, Keyword::ALL, Keyword::SOME])
4048            {
4049                self.expect_token(&Token::LParen)?;
4050                let right = if self.peek_sub_query() {
4051                    // We have a subquery ahead (SELECT\WITH ...) need to rewind and
4052                    // use the parenthesis for parsing the subquery as an expression.
4053                    self.prev_token(); // LParen
4054                    self.parse_subexpr(precedence)?
4055                } else {
4056                    // Non-subquery expression
4057                    let right = self.parse_subexpr(precedence)?;
4058                    self.expect_token(&Token::RParen)?;
4059                    right
4060                };
4061
4062                if !matches!(
4063                    op,
4064                    BinaryOperator::Gt
4065                        | BinaryOperator::Lt
4066                        | BinaryOperator::GtEq
4067                        | BinaryOperator::LtEq
4068                        | BinaryOperator::Eq
4069                        | BinaryOperator::NotEq
4070                        | BinaryOperator::PGRegexMatch
4071                        | BinaryOperator::PGRegexIMatch
4072                        | BinaryOperator::PGRegexNotMatch
4073                        | BinaryOperator::PGRegexNotIMatch
4074                        | BinaryOperator::PGLikeMatch
4075                        | BinaryOperator::PGILikeMatch
4076                        | BinaryOperator::PGNotLikeMatch
4077                        | BinaryOperator::PGNotILikeMatch
4078                ) {
4079                    return parser_err!(
4080                        format!(
4081                        "Expected one of [=, >, <, =>, =<, !=, ~, ~*, !~, !~*, ~~, ~~*, !~~, !~~*] as comparison operator, found: {op}"
4082                    ),
4083                        span.start
4084                    );
4085                };
4086
4087                Ok(match keyword {
4088                    Keyword::ALL => Expr::AllOp {
4089                        left: Box::new(expr),
4090                        compare_op: op,
4091                        right: Box::new(right),
4092                    },
4093                    Keyword::ANY | Keyword::SOME => Expr::AnyOp {
4094                        left: Box::new(expr),
4095                        compare_op: op,
4096                        right: Box::new(right),
4097                        is_some: keyword == Keyword::SOME,
4098                    },
4099                    unexpected_keyword => return Err(ParserError::ParserError(
4100                        format!("Internal parser error: expected any of {{ALL, ANY, SOME}}, got {unexpected_keyword:?}"),
4101                    )),
4102                })
4103            } else {
4104                Ok(Expr::BinaryOp {
4105                    left: Box::new(expr),
4106                    op,
4107                    right: Box::new(self.parse_subexpr(precedence)?),
4108                })
4109            }
4110        } else if let Token::Word(w) = &tok.token {
4111            match w.keyword {
4112                Keyword::IS => {
4113                    if self.parse_keyword(Keyword::NULL) {
4114                        Ok(Expr::IsNull(Box::new(expr)))
4115                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) {
4116                        Ok(Expr::IsNotNull(Box::new(expr)))
4117                    } else if self.parse_keywords(&[Keyword::TRUE]) {
4118                        Ok(Expr::IsTrue(Box::new(expr)))
4119                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::TRUE]) {
4120                        Ok(Expr::IsNotTrue(Box::new(expr)))
4121                    } else if self.parse_keywords(&[Keyword::FALSE]) {
4122                        Ok(Expr::IsFalse(Box::new(expr)))
4123                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::FALSE]) {
4124                        Ok(Expr::IsNotFalse(Box::new(expr)))
4125                    } else if self.parse_keywords(&[Keyword::UNKNOWN]) {
4126                        Ok(Expr::IsUnknown(Box::new(expr)))
4127                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::UNKNOWN]) {
4128                        Ok(Expr::IsNotUnknown(Box::new(expr)))
4129                    } else if self.parse_keywords(&[Keyword::DISTINCT, Keyword::FROM]) {
4130                        // The right operand binds no more loosely than `IS`
4131                        // itself, so that e.g. `a IS DISTINCT FROM b AND c`
4132                        // parses as `(a IS DISTINCT FROM b) AND c`.
4133                        let expr2 = self.parse_subexpr(precedence)?;
4134                        Ok(Expr::IsDistinctFrom(Box::new(expr), Box::new(expr2)))
4135                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::DISTINCT, Keyword::FROM])
4136                    {
4137                        let expr2 = self.parse_subexpr(precedence)?;
4138                        Ok(Expr::IsNotDistinctFrom(Box::new(expr), Box::new(expr2)))
4139                    } else if self.parse_keyword(Keyword::JSON) {
4140                        self.parse_is_json_predicate(expr, false)
4141                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::JSON]) {
4142                        self.parse_is_json_predicate(expr, true)
4143                    } else if let Ok(is_normalized) = self.parse_unicode_is_normalized(expr) {
4144                        Ok(is_normalized)
4145                    } else {
4146                        self.expected_ref(
4147                            "[NOT] NULL | TRUE | FALSE | DISTINCT | [NOT] JSON [VALUE | SCALAR | ARRAY | OBJECT] [WITH | WITHOUT UNIQUE [KEYS]] | [form] NORMALIZED FROM after IS",
4148                            self.peek_token_ref(),
4149                        )
4150                    }
4151                }
4152                Keyword::AT => {
4153                    self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
4154                    Ok(Expr::AtTimeZone {
4155                        timestamp: Box::new(expr),
4156                        time_zone: Box::new(self.parse_subexpr(precedence)?),
4157                    })
4158                }
4159                Keyword::NOT
4160                | Keyword::IN
4161                | Keyword::BETWEEN
4162                | Keyword::LIKE
4163                | Keyword::ILIKE
4164                | Keyword::SIMILAR
4165                | Keyword::REGEXP
4166                | Keyword::RLIKE => {
4167                    self.prev_token();
4168                    let negated = self.parse_keyword(Keyword::NOT);
4169                    let regexp = self.parse_keyword(Keyword::REGEXP);
4170                    let rlike = self.parse_keyword(Keyword::RLIKE);
4171                    let null = if !self.in_column_definition_state() {
4172                        self.parse_keyword(Keyword::NULL)
4173                    } else {
4174                        false
4175                    };
4176                    if regexp || rlike {
4177                        Ok(Expr::RLike {
4178                            negated,
4179                            expr: Box::new(expr),
4180                            pattern: Box::new(
4181                                self.parse_subexpr(self.dialect.prec_value(Precedence::Like))?,
4182                            ),
4183                            regexp,
4184                        })
4185                    } else if negated && null {
4186                        Ok(Expr::IsNotNull(Box::new(expr)))
4187                    } else if self.parse_keyword(Keyword::IN) {
4188                        self.parse_in(expr, negated)
4189                    } else if self.parse_keyword(Keyword::BETWEEN) {
4190                        self.parse_between(expr, negated)
4191                    } else if self.parse_keyword(Keyword::LIKE) {
4192                        Ok(Expr::Like {
4193                            negated,
4194                            any: self.parse_keyword(Keyword::ANY),
4195                            expr: Box::new(expr),
4196                            pattern: Box::new(
4197                                self.parse_subexpr(self.dialect.prec_value(Precedence::Like))?,
4198                            ),
4199                            escape_char: self.parse_escape_char()?,
4200                        })
4201                    } else if self.parse_keyword(Keyword::ILIKE) {
4202                        Ok(Expr::ILike {
4203                            negated,
4204                            any: self.parse_keyword(Keyword::ANY),
4205                            expr: Box::new(expr),
4206                            pattern: Box::new(
4207                                self.parse_subexpr(self.dialect.prec_value(Precedence::Like))?,
4208                            ),
4209                            escape_char: self.parse_escape_char()?,
4210                        })
4211                    } else if self.parse_keywords(&[Keyword::SIMILAR, Keyword::TO]) {
4212                        Ok(Expr::SimilarTo {
4213                            negated,
4214                            expr: Box::new(expr),
4215                            pattern: Box::new(
4216                                self.parse_subexpr(self.dialect.prec_value(Precedence::Like))?,
4217                            ),
4218                            escape_char: self.parse_escape_char()?,
4219                        })
4220                    } else {
4221                        self.expected_ref("IN or BETWEEN after NOT", self.peek_token_ref())
4222                    }
4223                }
4224                Keyword::NOTNULL if dialect.supports_notnull_operator() => {
4225                    Ok(Expr::IsNotNull(Box::new(expr)))
4226                }
4227                Keyword::MEMBER => {
4228                    if self.parse_keyword(Keyword::OF) {
4229                        self.expect_token(&Token::LParen)?;
4230                        let array = self.parse_expr()?;
4231                        self.expect_token(&Token::RParen)?;
4232                        Ok(Expr::MemberOf(MemberOf {
4233                            value: Box::new(expr),
4234                            array: Box::new(array),
4235                        }))
4236                    } else {
4237                        self.expected_ref("OF after MEMBER", self.peek_token_ref())
4238                    }
4239                }
4240                // Reached when the dialect assigns `COLLATE` a lower precedence than `::`, e.g.
4241                // Postgres's `expr::type COLLATE collation`.
4242                // See <https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-PRECEDENCE>
4243                Keyword::COLLATE => Ok(Expr::Collate {
4244                    expr: Box::new(expr),
4245                    collation: self.parse_object_name(false)?,
4246                }),
4247                // Can only happen if `get_next_precedence` got out of sync with this function
4248                _ => parser_err!(
4249                    format!("No infix parser for token {:?}", tok.token),
4250                    tok.span.start
4251                ),
4252            }
4253        } else if Token::DoubleColon == *tok {
4254            Ok(Expr::Cast {
4255                kind: CastKind::DoubleColon,
4256                expr: Box::new(expr),
4257                data_type: self.parse_data_type()?,
4258                format: None,
4259            })
4260        } else if Token::ExclamationMark == *tok && self.dialect.supports_factorial_operator() {
4261            Ok(Expr::UnaryOp {
4262                op: UnaryOperator::PGPostfixFactorial,
4263                expr: Box::new(expr),
4264            })
4265        } else if Token::LBracket == *tok && self.dialect.supports_partiql()
4266            || (Token::Colon == *tok)
4267        {
4268            self.prev_token();
4269            self.parse_json_access(expr)
4270        } else {
4271            // Can only happen if `get_next_precedence` got out of sync with this function
4272            parser_err!(
4273                format!("No infix parser for token {:?}", tok.token),
4274                tok.span.start
4275            )
4276        }
4277    }
4278
4279    /// Parse the `ESCAPE CHAR` portion of `LIKE`, `ILIKE`, and `SIMILAR TO`
4280    pub fn parse_escape_char(&mut self) -> Result<Option<Box<Expr>>, ParserError> {
4281        if self.parse_keyword(Keyword::ESCAPE) {
4282            Ok(Some(Box::new(self.parse_subexpr(
4283                self.dialect.prec_value(Precedence::Like),
4284            )?)))
4285        } else {
4286            Ok(None)
4287        }
4288    }
4289
4290    /// Parses an array subscript like
4291    /// * `[:]`
4292    /// * `[l]`
4293    /// * `[l:]`
4294    /// * `[:u]`
4295    /// * `[l:u]`
4296    /// * `[l:u:s]`
4297    ///
4298    /// Parser is right after `[`
4299    fn parse_subscript_inner(&mut self) -> Result<Subscript, ParserError> {
4300        // at either `<lower>:(rest)` or `:(rest)]`
4301        let lower_bound = if self.consume_token(&Token::Colon) {
4302            None
4303        } else {
4304            // parse expr until we hit a colon (or any token with lower precedence)
4305            Some(self.parse_subexpr(self.dialect.prec_value(Precedence::Colon))?)
4306        };
4307
4308        // check for end
4309        if self.consume_token(&Token::RBracket) {
4310            if let Some(lower_bound) = lower_bound {
4311                return Ok(Subscript::Index { index: lower_bound });
4312            };
4313            return Ok(Subscript::Slice {
4314                lower_bound,
4315                upper_bound: None,
4316                stride: None,
4317            });
4318        }
4319
4320        // consume the `:`
4321        if lower_bound.is_some() {
4322            self.expect_token(&Token::Colon)?;
4323        }
4324
4325        // we are now at either `]`, `<upper>(rest)]`
4326        let upper_bound = if self.consume_token(&Token::RBracket) {
4327            return Ok(Subscript::Slice {
4328                lower_bound,
4329                upper_bound: None,
4330                stride: None,
4331            });
4332        } else {
4333            // parse expr until we hit a colon (or any token with lower precedence)
4334            Some(self.parse_subexpr(self.dialect.prec_value(Precedence::Colon))?)
4335        };
4336
4337        // check for end
4338        if self.consume_token(&Token::RBracket) {
4339            return Ok(Subscript::Slice {
4340                lower_bound,
4341                upper_bound,
4342                stride: None,
4343            });
4344        }
4345
4346        // we are now at `:]` or `:stride]`
4347        self.expect_token(&Token::Colon)?;
4348        let stride = if self.consume_token(&Token::RBracket) {
4349            None
4350        } else {
4351            Some(self.parse_expr()?)
4352        };
4353
4354        if stride.is_some() {
4355            self.expect_token(&Token::RBracket)?;
4356        }
4357
4358        Ok(Subscript::Slice {
4359            lower_bound,
4360            upper_bound,
4361            stride,
4362        })
4363    }
4364
4365    /// Parse a multi-dimension array accessing like `[1:3][1][1]`
4366    pub fn parse_multi_dim_subscript(
4367        &mut self,
4368        chain: &mut Vec<AccessExpr>,
4369    ) -> Result<(), ParserError> {
4370        while self.consume_token(&Token::LBracket) {
4371            self.parse_subscript(chain)?;
4372        }
4373        Ok(())
4374    }
4375
4376    /// Parses an array subscript like `[1:3]`
4377    ///
4378    /// Parser is right after `[`
4379    fn parse_subscript(&mut self, chain: &mut Vec<AccessExpr>) -> Result<(), ParserError> {
4380        let subscript = self.parse_subscript_inner()?;
4381        chain.push(AccessExpr::Subscript(subscript));
4382        Ok(())
4383    }
4384
4385    fn parse_json_path_object_key(&mut self) -> Result<JsonPathElem, ParserError> {
4386        let token = self.next_token();
4387        match token.token {
4388            Token::Word(Word {
4389                value,
4390                // path segments in SF dot notation can be unquoted or double-quoted;
4391                // Databricks also supports backtick-quoted identifiers
4392                quote_style: quote_style @ (Some('"') | Some('`') | None),
4393                // some experimentation suggests that snowflake permits
4394                // any keyword here unquoted.
4395                keyword: _,
4396            }) => Ok(JsonPathElem::Dot {
4397                key: value,
4398                quoted: quote_style.is_some(),
4399            }),
4400
4401            // This token should never be generated on snowflake or generic
4402            // dialects, but we handle it just in case this is used on future
4403            // dialects.
4404            Token::DoubleQuotedString(key) => Ok(JsonPathElem::Dot { key, quoted: true }),
4405
4406            _ => self.expected("variant object key name", token),
4407        }
4408    }
4409
4410    fn parse_json_access(&mut self, expr: Expr) -> Result<Expr, ParserError> {
4411        let path = self.parse_json_path()?;
4412        Ok(Expr::JsonAccess {
4413            value: Box::new(expr),
4414            path,
4415        })
4416    }
4417
4418    fn parse_json_path(&mut self) -> Result<JsonPath, ParserError> {
4419        let mut path = Vec::new();
4420        loop {
4421            match self.next_token().token {
4422                Token::Colon if path.is_empty() && self.peek_token_ref() == &Token::LBracket => {
4423                    self.next_token();
4424                    let key = self.parse_wildcard_expr()?;
4425                    self.expect_token(&Token::RBracket)?;
4426                    path.push(JsonPathElem::ColonBracket { key });
4427                }
4428                Token::Colon if path.is_empty() => {
4429                    path.push(self.parse_json_path_object_key()?);
4430                }
4431                Token::Period if !path.is_empty() => {
4432                    path.push(self.parse_json_path_object_key()?);
4433                }
4434                Token::LBracket => {
4435                    let key = self.parse_wildcard_expr()?;
4436                    self.expect_token(&Token::RBracket)?;
4437
4438                    path.push(JsonPathElem::Bracket { key });
4439                }
4440                _ => {
4441                    self.prev_token();
4442                    break;
4443                }
4444            };
4445        }
4446
4447        debug_assert!(!path.is_empty());
4448        Ok(JsonPath { path })
4449    }
4450
4451    /// Parses the parens following the `[ NOT ] IN` operator.
4452    pub fn parse_in(&mut self, expr: Expr, negated: bool) -> Result<Expr, ParserError> {
4453        // BigQuery allows `IN UNNEST(array_expression)`
4454        // https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#in_operators
4455        if self.parse_keyword(Keyword::UNNEST) {
4456            self.expect_token(&Token::LParen)?;
4457            let array_expr = self.parse_expr()?;
4458            self.expect_token(&Token::RParen)?;
4459            return Ok(Expr::InUnnest {
4460                expr: Box::new(expr),
4461                array_expr: Box::new(array_expr),
4462                negated,
4463            });
4464        }
4465        if self.dialect.supports_in_unparenthesized_expr()
4466            && self.peek_token_ref().token != Token::LParen
4467        {
4468            return Ok(Expr::InList {
4469                expr: Box::new(expr),
4470                list: vec![self.parse_expr()?],
4471                negated,
4472            });
4473        }
4474        self.expect_token(&Token::LParen)?;
4475        // A leading query is the whole subquery only when `)` follows it,
4476        // otherwise it is the first item of a list, as in `IN ((SELECT 1), 2)`.
4477        let start = self.index;
4478        // Where a parsed query lacked its `)`. Reported if the list fails no
4479        // further in, since that error would sit inside the query.
4480        let missing_rparen = match self.failed_in_subquery_positions.get(&start) {
4481            Some(&cached) => cached,
4482            None => {
4483                let mut missing_rparen = None;
4484                if let Some(subquery) = self.maybe_parse(|p| p.parse_query())? {
4485                    if self.consume_token(&Token::RParen) {
4486                        return Ok(Expr::InSubquery {
4487                            expr: Box::new(expr),
4488                            subquery,
4489                            negated,
4490                        });
4491                    }
4492                    missing_rparen = Some(self.index);
4493                    self.index = start;
4494                }
4495                self.failed_in_subquery_positions
4496                    .insert(start, missing_rparen);
4497                missing_rparen
4498            }
4499        };
4500        let list = if self.dialect.supports_in_empty_list() {
4501            self.parse_comma_separated0(Parser::parse_expr, Token::RParen)
4502        } else {
4503            self.parse_comma_separated(Parser::parse_expr)
4504        };
4505        match list.and_then(|list| self.expect_token(&Token::RParen).map(|_| list)) {
4506            Ok(list) => Ok(Expr::InList {
4507                expr: Box::new(expr),
4508                list,
4509                negated,
4510            }),
4511            Err(ParserError::RecursionLimitExceeded) => Err(ParserError::RecursionLimitExceeded),
4512            Err(e) => match missing_rparen {
4513                Some(index) if self.index <= index => {
4514                    self.index = index;
4515                    self.expected_ref(")", self.peek_token_ref())
4516                }
4517                _ => Err(e),
4518            },
4519        }
4520    }
4521
4522    /// Parses `BETWEEN <low> AND <high>`, assuming the `BETWEEN` keyword was already consumed.
4523    pub fn parse_between(&mut self, expr: Expr, negated: bool) -> Result<Expr, ParserError> {
4524        // Stop parsing subexpressions for <low> and <high> on tokens with
4525        // precedence lower than that of `BETWEEN`, such as `AND`, `IS`, etc.
4526        let low = self.parse_subexpr(self.dialect.prec_value(Precedence::Between))?;
4527        self.expect_keyword_is(Keyword::AND)?;
4528        let high = self.parse_subexpr(self.dialect.prec_value(Precedence::Between))?;
4529        Ok(Expr::Between {
4530            expr: Box::new(expr),
4531            negated,
4532            low: Box::new(low),
4533            high: Box::new(high),
4534        })
4535    }
4536
4537    /// Parse a PostgreSQL casting style which is in the form of `expr::datatype`.
4538    pub fn parse_pg_cast(&mut self, expr: Expr) -> Result<Expr, ParserError> {
4539        Ok(Expr::Cast {
4540            kind: CastKind::DoubleColon,
4541            expr: Box::new(expr),
4542            data_type: self.parse_data_type()?,
4543            format: None,
4544        })
4545    }
4546
4547    /// Get the precedence of the next token
4548    pub fn get_next_precedence(&self) -> Result<u8, ParserError> {
4549        self.dialect.get_next_precedence_default(self)
4550    }
4551
4552    /// Return the token at the given location, or EOF if the index is beyond
4553    /// the length of the current set of tokens.
4554    pub fn token_at(&self, index: usize) -> &TokenWithSpan {
4555        self.tokens.get(index).unwrap_or(&EOF_TOKEN)
4556    }
4557
4558    /// Return the first non-whitespace token that has not yet been processed
4559    /// or Token::EOF
4560    ///
4561    /// See [`Self::peek_token_ref`] to avoid the copy.
4562    pub fn peek_token(&self) -> TokenWithSpan {
4563        self.peek_nth_token(0)
4564    }
4565
4566    /// Return a reference to the first non-whitespace token that has not yet
4567    /// been processed or Token::EOF
4568    pub fn peek_token_ref(&self) -> &TokenWithSpan {
4569        self.peek_nth_token_ref(0)
4570    }
4571
4572    /// Returns the `N` next non-whitespace tokens that have not yet been
4573    /// processed.
4574    ///
4575    /// Example:
4576    /// ```rust
4577    /// # use sqlparser::dialect::GenericDialect;
4578    /// # use sqlparser::parser::Parser;
4579    /// # use sqlparser::keywords::Keyword;
4580    /// # use sqlparser::tokenizer::{Token, Word};
4581    /// let dialect = GenericDialect {};
4582    /// let mut parser = Parser::new(&dialect).try_with_sql("ORDER BY foo, bar").unwrap();
4583    ///
4584    /// // Note that Rust infers the number of tokens to peek based on the
4585    /// // length of the slice pattern!
4586    /// assert!(matches!(
4587    ///     parser.peek_tokens(),
4588    ///     [
4589    ///         Token::Word(Word { keyword: Keyword::ORDER, .. }),
4590    ///         Token::Word(Word { keyword: Keyword::BY, .. }),
4591    ///     ]
4592    /// ));
4593    /// ```
4594    pub fn peek_tokens<const N: usize>(&self) -> [Token; N] {
4595        self.peek_tokens_with_location()
4596            .map(|with_loc| with_loc.token)
4597    }
4598
4599    /// Returns the `N` next non-whitespace tokens with locations that have not
4600    /// yet been processed.
4601    ///
4602    /// See [`Self::peek_token`] for an example.
4603    pub fn peek_tokens_with_location<const N: usize>(&self) -> [TokenWithSpan; N] {
4604        let mut index = self.index;
4605        core::array::from_fn(|_| loop {
4606            let token = self.tokens.get(index);
4607            index += 1;
4608            if let Some(TokenWithSpan {
4609                token: Token::Whitespace(_),
4610                span: _,
4611            }) = token
4612            {
4613                continue;
4614            }
4615            break token.cloned().unwrap_or(TokenWithSpan {
4616                token: Token::EOF,
4617                span: Span::empty(),
4618            });
4619        })
4620    }
4621
4622    /// Returns references to the `N` next non-whitespace tokens
4623    /// that have not yet been processed.
4624    ///
4625    /// See [`Self::peek_tokens`] for an example.
4626    pub fn peek_tokens_ref<const N: usize>(&self) -> [&TokenWithSpan; N] {
4627        let mut index = self.index;
4628        core::array::from_fn(|_| loop {
4629            let token = self.tokens.get(index);
4630            index += 1;
4631            if let Some(TokenWithSpan {
4632                token: Token::Whitespace(_),
4633                span: _,
4634            }) = token
4635            {
4636                continue;
4637            }
4638            break token.unwrap_or(&EOF_TOKEN);
4639        })
4640    }
4641
4642    /// Return nth non-whitespace token that has not yet been processed
4643    pub fn peek_nth_token(&self, n: usize) -> TokenWithSpan {
4644        self.peek_nth_token_ref(n).clone()
4645    }
4646
4647    /// Return nth non-whitespace token that has not yet been processed
4648    pub fn peek_nth_token_ref(&self, mut n: usize) -> &TokenWithSpan {
4649        let mut index = self.index;
4650        loop {
4651            index += 1;
4652            match self.tokens.get(index - 1) {
4653                Some(TokenWithSpan {
4654                    token: Token::Whitespace(_),
4655                    span: _,
4656                }) => continue,
4657                non_whitespace => {
4658                    if n == 0 {
4659                        return non_whitespace.unwrap_or(&EOF_TOKEN);
4660                    }
4661                    n -= 1;
4662                }
4663            }
4664        }
4665    }
4666
4667    /// Return the first token, possibly whitespace, that has not yet been processed
4668    /// (or None if reached end-of-file).
4669    pub fn peek_token_no_skip(&self) -> TokenWithSpan {
4670        self.peek_nth_token_no_skip(0)
4671    }
4672
4673    /// Return nth token, possibly whitespace, that has not yet been processed.
4674    pub fn peek_nth_token_no_skip(&self, n: usize) -> TokenWithSpan {
4675        self.tokens
4676            .get(self.index + n)
4677            .cloned()
4678            .unwrap_or(TokenWithSpan {
4679                token: Token::EOF,
4680                span: Span::empty(),
4681            })
4682    }
4683
4684    /// Return nth token, possibly whitespace, that has not yet been processed.
4685    fn peek_nth_token_no_skip_ref(&self, n: usize) -> &TokenWithSpan {
4686        self.tokens.get(self.index + n).unwrap_or(&EOF_TOKEN)
4687    }
4688
4689    /// Return true if the next tokens exactly `expected`
4690    ///
4691    /// Does not advance the current token.
4692    fn peek_keywords(&mut self, expected: &[Keyword]) -> bool {
4693        let index = self.index;
4694        let matched = self.parse_keywords(expected);
4695        self.index = index;
4696        matched
4697    }
4698
4699    /// Advances to the next non-whitespace token and returns a copy.
4700    ///
4701    /// Please use [`Self::advance_token`] and [`Self::get_current_token`] to
4702    /// avoid the copy.
4703    pub fn next_token(&mut self) -> TokenWithSpan {
4704        self.advance_token();
4705        self.get_current_token().clone()
4706    }
4707
4708    /// Returns the index of the current token
4709    ///
4710    /// This can be used with APIs that expect an index, such as
4711    /// [`Self::token_at`]
4712    pub fn get_current_index(&self) -> usize {
4713        self.index.saturating_sub(1)
4714    }
4715
4716    /// Return the next unprocessed token, possibly whitespace.
4717    pub fn next_token_no_skip(&mut self) -> Option<&TokenWithSpan> {
4718        self.index += 1;
4719        self.tokens.get(self.index - 1)
4720    }
4721
4722    /// Advances the current token to the next non-whitespace token
4723    ///
4724    /// See [`Self::get_current_token`] to get the current token after advancing
4725    pub fn advance_token(&mut self) {
4726        loop {
4727            self.index += 1;
4728            match self.tokens.get(self.index - 1) {
4729                Some(TokenWithSpan {
4730                    token: Token::Whitespace(_),
4731                    span: _,
4732                }) => continue,
4733                _ => break,
4734            }
4735        }
4736    }
4737
4738    /// Returns a reference to the current token
4739    ///
4740    /// Does not advance the current token.
4741    pub fn get_current_token(&self) -> &TokenWithSpan {
4742        self.token_at(self.index.saturating_sub(1))
4743    }
4744
4745    /// Returns a reference to the previous token
4746    ///
4747    /// Does not advance the current token.
4748    pub fn get_previous_token(&self) -> &TokenWithSpan {
4749        self.token_at(self.index.saturating_sub(2))
4750    }
4751
4752    /// Returns a reference to the next token
4753    ///
4754    /// Does not advance the current token.
4755    pub fn get_next_token(&self) -> &TokenWithSpan {
4756        self.token_at(self.index)
4757    }
4758
4759    /// Seek back the last one non-whitespace token.
4760    ///
4761    /// Must be called after `next_token()`, otherwise might panic. OK to call
4762    /// after `next_token()` indicates an EOF.
4763    ///
4764    // TODO rename to backup_token and deprecate prev_token?
4765    pub fn prev_token(&mut self) {
4766        loop {
4767            assert!(self.index > 0);
4768            self.index -= 1;
4769            if let Some(TokenWithSpan {
4770                token: Token::Whitespace(_),
4771                span: _,
4772            }) = self.tokens.get(self.index)
4773            {
4774                continue;
4775            }
4776            return;
4777        }
4778    }
4779
4780    /// Report `found` was encountered instead of `expected`
4781    pub fn expected<T>(&self, expected: &str, found: TokenWithSpan) -> Result<T, ParserError> {
4782        parser_err!(
4783            format!("Expected: {expected}, found: {found}"),
4784            found.span.start
4785        )
4786    }
4787
4788    /// report `found` was encountered instead of `expected`
4789    pub fn expected_ref<T>(&self, expected: &str, found: &TokenWithSpan) -> Result<T, ParserError> {
4790        parser_err!(
4791            format!("Expected: {expected}, found: {found}"),
4792            found.span.start
4793        )
4794    }
4795
4796    /// Report that the token at `index` was found instead of `expected`.
4797    pub fn expected_at<T>(&self, expected: &str, index: usize) -> Result<T, ParserError> {
4798        let found = self.tokens.get(index).unwrap_or(&EOF_TOKEN);
4799        parser_err!(
4800            format!("Expected: {expected}, found: {found}"),
4801            found.span.start
4802        )
4803    }
4804
4805    /// If the current token is the `expected` keyword, consume it and returns
4806    /// true. Otherwise, no tokens are consumed and returns false.
4807    #[must_use]
4808    pub fn parse_keyword(&mut self, expected: Keyword) -> bool {
4809        if self.peek_keyword(expected) {
4810            self.advance_token();
4811            true
4812        } else {
4813            false
4814        }
4815    }
4816
4817    #[must_use]
4818    /// Check if the current token is the expected keyword without consuming it.
4819    ///
4820    /// Returns true if the current token matches the expected keyword.
4821    pub fn peek_keyword(&self, expected: Keyword) -> bool {
4822        matches!(&self.peek_token_ref().token, Token::Word(w) if expected == w.keyword)
4823    }
4824
4825    /// If the current token is the `expected` keyword followed by
4826    /// specified tokens, consume them and returns true.
4827    /// Otherwise, no tokens are consumed and returns false.
4828    ///
4829    /// Note that if the length of `tokens` is too long, this function will
4830    /// not be efficient as it does a loop on the tokens with `peek_nth_token`
4831    /// each time.
4832    pub fn parse_keyword_with_tokens(&mut self, expected: Keyword, tokens: &[Token]) -> bool {
4833        self.keyword_with_tokens(expected, tokens, true)
4834    }
4835
4836    /// Peeks to see if the current token is the `expected` keyword followed by specified tokens
4837    /// without consuming them.
4838    ///
4839    /// See [Self::parse_keyword_with_tokens] for details.
4840    pub(crate) fn peek_keyword_with_tokens(&mut self, expected: Keyword, tokens: &[Token]) -> bool {
4841        self.keyword_with_tokens(expected, tokens, false)
4842    }
4843
4844    fn keyword_with_tokens(&mut self, expected: Keyword, tokens: &[Token], consume: bool) -> bool {
4845        match &self.peek_token_ref().token {
4846            Token::Word(w) if expected == w.keyword => {
4847                for (idx, token) in tokens.iter().enumerate() {
4848                    if self.peek_nth_token_ref(idx + 1).token != *token {
4849                        return false;
4850                    }
4851                }
4852
4853                if consume {
4854                    for _ in 0..(tokens.len() + 1) {
4855                        self.advance_token();
4856                    }
4857                }
4858
4859                true
4860            }
4861            _ => false,
4862        }
4863    }
4864
4865    /// If the current and subsequent tokens exactly match the `keywords`
4866    /// sequence, consume them and returns true. Otherwise, no tokens are
4867    /// consumed and returns false
4868    #[must_use]
4869    pub fn parse_keywords(&mut self, keywords: &[Keyword]) -> bool {
4870        self.parse_keywords_indexed(keywords).is_some()
4871    }
4872
4873    /// Just like [Self::parse_keywords], but - upon success - returns the
4874    /// token index of the first keyword.
4875    #[must_use]
4876    fn parse_keywords_indexed(&mut self, keywords: &[Keyword]) -> Option<usize> {
4877        let start_index = self.index;
4878        let mut first_keyword_index = None;
4879        for &keyword in keywords {
4880            if !self.parse_keyword(keyword) {
4881                self.index = start_index;
4882                return None;
4883            }
4884            if first_keyword_index.is_none() {
4885                first_keyword_index = Some(self.index.saturating_sub(1));
4886            }
4887        }
4888        first_keyword_index
4889    }
4890
4891    /// If the current token is one of the given `keywords`, returns the keyword
4892    /// that matches, without consuming the token. Otherwise, returns [`None`].
4893    #[must_use]
4894    pub fn peek_one_of_keywords(&self, keywords: &[Keyword]) -> Option<Keyword> {
4895        for keyword in keywords {
4896            if self.peek_keyword(*keyword) {
4897                return Some(*keyword);
4898            }
4899        }
4900        None
4901    }
4902
4903    /// If the current token is one of the given `keywords`, consume the token
4904    /// and return the keyword that matches. Otherwise, no tokens are consumed
4905    /// and returns [`None`].
4906    #[must_use]
4907    pub fn parse_one_of_keywords(&mut self, keywords: &[Keyword]) -> Option<Keyword> {
4908        match &self.peek_token_ref().token {
4909            Token::Word(w) => {
4910                keywords
4911                    .iter()
4912                    .find(|keyword| **keyword == w.keyword)
4913                    .map(|keyword| {
4914                        self.advance_token();
4915                        *keyword
4916                    })
4917            }
4918            _ => None,
4919        }
4920    }
4921
4922    /// If the current token is one of the expected keywords, consume the token
4923    /// and return the keyword that matches. Otherwise, return an error.
4924    pub fn expect_one_of_keywords(&mut self, keywords: &[Keyword]) -> Result<Keyword, ParserError> {
4925        if let Some(keyword) = self.parse_one_of_keywords(keywords) {
4926            Ok(keyword)
4927        } else {
4928            let keywords: Vec<String> = keywords.iter().map(|x| format!("{x:?}")).collect();
4929            self.expected_ref(
4930                &format!("one of {}", keywords.join(" or ")),
4931                self.peek_token_ref(),
4932            )
4933        }
4934    }
4935
4936    /// If the current token is the `expected` keyword, consume the token.
4937    /// Otherwise, return an error.
4938    ///
4939    // todo deprecate in favor of expected_keyword_is
4940    pub fn expect_keyword(&mut self, expected: Keyword) -> Result<TokenWithSpan, ParserError> {
4941        if self.parse_keyword(expected) {
4942            Ok(self.get_current_token().clone())
4943        } else {
4944            self.expected_ref(format!("{:?}", expected).as_str(), self.peek_token_ref())
4945        }
4946    }
4947
4948    /// If the current token is the `expected` keyword, consume the token.
4949    /// Otherwise, return an error.
4950    ///
4951    /// This differs from expect_keyword only in that the matched keyword
4952    /// token is not returned.
4953    pub fn expect_keyword_is(&mut self, expected: Keyword) -> Result<(), ParserError> {
4954        if self.parse_keyword(expected) {
4955            Ok(())
4956        } else {
4957            self.expected_ref(format!("{:?}", expected).as_str(), self.peek_token_ref())
4958        }
4959    }
4960
4961    /// If the current and subsequent tokens exactly match the `keywords`
4962    /// sequence, consume them and returns Ok. Otherwise, return an Error.
4963    pub fn expect_keywords(&mut self, expected: &[Keyword]) -> Result<(), ParserError> {
4964        for &kw in expected {
4965            self.expect_keyword_is(kw)?;
4966        }
4967        Ok(())
4968    }
4969
4970    /// Consume the next token if it matches the expected token, otherwise return false
4971    ///
4972    /// See [Self::advance_token] to consume the token unconditionally
4973    #[must_use]
4974    pub fn consume_token(&mut self, expected: &Token) -> bool {
4975        if self.peek_token_ref() == expected {
4976            self.advance_token();
4977            true
4978        } else {
4979            false
4980        }
4981    }
4982
4983    /// If the current and subsequent tokens exactly match the `tokens`
4984    /// sequence, consume them and returns true. Otherwise, no tokens are
4985    /// consumed and returns false
4986    #[must_use]
4987    pub fn consume_tokens(&mut self, tokens: &[Token]) -> bool {
4988        let index = self.index;
4989        for token in tokens {
4990            if !self.consume_token(token) {
4991                self.index = index;
4992                return false;
4993            }
4994        }
4995        true
4996    }
4997
4998    /// Bail out if the current token is not an expected keyword, or consume it if it is
4999    pub fn expect_token(&mut self, expected: &Token) -> Result<TokenWithSpan, ParserError> {
5000        if self.peek_token_ref() == expected {
5001            Ok(self.next_token())
5002        } else {
5003            self.expected_ref(&expected.to_string(), self.peek_token_ref())
5004        }
5005    }
5006
5007    fn parse<T: FromStr>(s: String, loc: Location) -> Result<T, ParserError>
5008    where
5009        <T as FromStr>::Err: Display,
5010    {
5011        s.parse::<T>().map_err(|e| {
5012            ParserError::ParserError(format!(
5013                "Could not parse '{s}' as {}: {e}{loc}",
5014                core::any::type_name::<T>()
5015            ))
5016        })
5017    }
5018
5019    /// Parse a comma-separated list of 1+ SelectItem
5020    pub fn parse_projection(&mut self) -> Result<Vec<SelectItem>, ParserError> {
5021        // BigQuery and Snowflake allow trailing commas, but only in project lists
5022        // e.g. `SELECT 1, 2, FROM t`
5023        // https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#trailing_commas
5024        // https://docs.snowflake.com/en/release-notes/2024/8_11#select-supports-trailing-commas
5025
5026        let trailing_commas =
5027            self.options.trailing_commas | self.dialect.supports_projection_trailing_commas();
5028
5029        self.parse_comma_separated_with_trailing_commas(
5030            |p| p.parse_select_item(),
5031            trailing_commas,
5032            Self::is_reserved_for_column_alias,
5033        )
5034    }
5035
5036    /// Parse a list of actions for `GRANT` statements.
5037    pub fn parse_actions_list(&mut self) -> Result<Vec<Action>, ParserError> {
5038        let mut values = vec![];
5039        loop {
5040            values.push(self.parse_grant_permission()?);
5041            if !self.consume_token(&Token::Comma) {
5042                break;
5043            } else if self.options.trailing_commas {
5044                match &self.peek_token_ref().token {
5045                    Token::Word(kw) if kw.keyword == Keyword::ON => {
5046                        break;
5047                    }
5048                    Token::RParen
5049                    | Token::SemiColon
5050                    | Token::EOF
5051                    | Token::RBracket
5052                    | Token::RBrace => break,
5053                    _ => continue,
5054                }
5055            }
5056        }
5057        Ok(values)
5058    }
5059
5060    /// Parse a list of [TableWithJoins]
5061    fn parse_table_with_joins(&mut self) -> Result<Vec<TableWithJoins>, ParserError> {
5062        let trailing_commas = self.dialect.supports_from_trailing_commas();
5063
5064        self.parse_comma_separated_with_trailing_commas(
5065            Parser::parse_table_and_joins,
5066            trailing_commas,
5067            |kw, parser| !self.dialect.is_table_factor(kw, parser),
5068        )
5069    }
5070
5071    /// Parse the comma of a comma-separated syntax element.
5072    /// `R` is a predicate that should return true if the next
5073    /// keyword is a reserved keyword.
5074    /// Allows for control over trailing commas
5075    ///
5076    /// Returns true if there is a next element
5077    fn is_parse_comma_separated_end_with_trailing_commas<R>(
5078        &mut self,
5079        trailing_commas: bool,
5080        is_reserved_keyword: &R,
5081    ) -> bool
5082    where
5083        R: Fn(&Keyword, &mut Parser) -> bool,
5084    {
5085        if !self.consume_token(&Token::Comma) {
5086            true
5087        } else if trailing_commas {
5088            let token = self.next_token().token;
5089            let is_end = match token {
5090                Token::Word(ref kw) if is_reserved_keyword(&kw.keyword, self) => true,
5091                Token::RParen | Token::SemiColon | Token::EOF | Token::RBracket | Token::RBrace => {
5092                    true
5093                }
5094                _ => false,
5095            };
5096            self.prev_token();
5097
5098            is_end
5099        } else {
5100            false
5101        }
5102    }
5103
5104    /// Parse the comma of a comma-separated syntax element.
5105    /// Returns true if there is a next element
5106    fn is_parse_comma_separated_end(&mut self) -> bool {
5107        self.is_parse_comma_separated_end_with_trailing_commas(
5108            self.options.trailing_commas,
5109            &Self::is_reserved_for_column_alias,
5110        )
5111    }
5112
5113    /// Parse a comma-separated list of 1+ items accepted by `F`
5114    pub fn parse_comma_separated<T, F>(&mut self, f: F) -> Result<Vec<T>, ParserError>
5115    where
5116        F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
5117    {
5118        self.parse_comma_separated_with_trailing_commas(
5119            f,
5120            self.options.trailing_commas,
5121            Self::is_reserved_for_column_alias,
5122        )
5123    }
5124
5125    /// Parse a comma-separated list of 1+ items accepted by `F`.
5126    /// `R` is a predicate that should return true if the next
5127    /// keyword is a reserved keyword.
5128    /// Allows for control over trailing commas.
5129    fn parse_comma_separated_with_trailing_commas<T, F, R>(
5130        &mut self,
5131        mut f: F,
5132        trailing_commas: bool,
5133        is_reserved_keyword: R,
5134    ) -> Result<Vec<T>, ParserError>
5135    where
5136        F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
5137        R: Fn(&Keyword, &mut Parser) -> bool,
5138    {
5139        let mut values = vec![];
5140        loop {
5141            values.push(f(self)?);
5142            if self.is_parse_comma_separated_end_with_trailing_commas(
5143                trailing_commas,
5144                &is_reserved_keyword,
5145            ) {
5146                break;
5147            }
5148        }
5149        Ok(values)
5150    }
5151
5152    /// Parse a period-separated list of 1+ items accepted by `F`
5153    fn parse_period_separated<T, F>(&mut self, mut f: F) -> Result<Vec<T>, ParserError>
5154    where
5155        F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
5156    {
5157        let mut values = vec![];
5158        loop {
5159            values.push(f(self)?);
5160            if !self.consume_token(&Token::Period) {
5161                break;
5162            }
5163        }
5164        Ok(values)
5165    }
5166
5167    /// Parse a keyword-separated list of 1+ items accepted by `F`
5168    pub fn parse_keyword_separated<T, F>(
5169        &mut self,
5170        keyword: Keyword,
5171        mut f: F,
5172    ) -> Result<Vec<T>, ParserError>
5173    where
5174        F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
5175    {
5176        let mut values = vec![];
5177        loop {
5178            values.push(f(self)?);
5179            if !self.parse_keyword(keyword) {
5180                break;
5181            }
5182        }
5183        Ok(values)
5184    }
5185
5186    /// Parse an expression enclosed in parentheses.
5187    pub fn parse_parenthesized<T, F>(&mut self, mut f: F) -> Result<T, ParserError>
5188    where
5189        F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
5190    {
5191        self.expect_token(&Token::LParen)?;
5192        let res = f(self)?;
5193        self.expect_token(&Token::RParen)?;
5194        Ok(res)
5195    }
5196
5197    /// Parse a comma-separated list of 0+ items accepted by `F`
5198    /// * `end_token` - expected end token for the closure (e.g. [Token::RParen], [Token::RBrace] ...)
5199    pub fn parse_comma_separated0<T, F>(
5200        &mut self,
5201        f: F,
5202        end_token: Token,
5203    ) -> Result<Vec<T>, ParserError>
5204    where
5205        F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
5206    {
5207        if self.peek_token_ref().token == end_token {
5208            return Ok(vec![]);
5209        }
5210
5211        if self.options.trailing_commas && self.peek_tokens() == [Token::Comma, end_token] {
5212            let _ = self.consume_token(&Token::Comma);
5213            return Ok(vec![]);
5214        }
5215
5216        self.parse_comma_separated(f)
5217    }
5218
5219    /// Parses 0 or more statements, each followed by a semicolon.
5220    /// If the next token is any of `terminal_keywords` then no more
5221    /// statements will be parsed.
5222    pub(crate) fn parse_statement_list(
5223        &mut self,
5224        terminal_keywords: &[Keyword],
5225    ) -> Result<Vec<Statement>, ParserError> {
5226        let mut values = vec![];
5227        loop {
5228            match &self.peek_nth_token_ref(0).token {
5229                Token::EOF => break,
5230                Token::Word(w)
5231                    if w.quote_style.is_none() && terminal_keywords.contains(&w.keyword) =>
5232                {
5233                    break;
5234                }
5235                _ => {}
5236            }
5237
5238            values.push(self.parse_statement()?);
5239            self.expect_token(&Token::SemiColon)?;
5240        }
5241        Ok(values)
5242    }
5243
5244    /// Default implementation of a predicate that returns true if
5245    /// the specified keyword is reserved for column alias.
5246    /// See [Dialect::is_column_alias]
5247    fn is_reserved_for_column_alias(kw: &Keyword, parser: &mut Parser) -> bool {
5248        !parser.dialect.is_column_alias(kw, parser)
5249    }
5250
5251    /// Run a parser method `f`, reverting back to the current position if unsuccessful.
5252    /// Returns `ParserError::RecursionLimitExceeded` if `f` returns a `RecursionLimitExceeded`.
5253    /// Returns `Ok(None)` if `f` returns any other error.
5254    pub fn maybe_parse<T, F>(&mut self, f: F) -> Result<Option<T>, ParserError>
5255    where
5256        F: FnMut(&mut Parser) -> Result<T, ParserError>,
5257    {
5258        match self.try_parse(f) {
5259            Ok(t) => Ok(Some(t)),
5260            Err(ParserError::RecursionLimitExceeded) => Err(ParserError::RecursionLimitExceeded),
5261            _ => Ok(None),
5262        }
5263    }
5264
5265    /// Run a parser method `f`, reverting back to the current position if unsuccessful.
5266    pub fn try_parse<T, F>(&mut self, mut f: F) -> Result<T, ParserError>
5267    where
5268        F: FnMut(&mut Parser) -> Result<T, ParserError>,
5269    {
5270        let index = self.index;
5271        match f(self) {
5272            Ok(t) => Ok(t),
5273            Err(e) => {
5274                // Unwind stack if limit exceeded
5275                self.index = index;
5276                Err(e)
5277            }
5278        }
5279    }
5280
5281    /// Parse either `ALL`, `DISTINCT` or `DISTINCT ON (...)`. Returns [`None`] if `ALL` is parsed
5282    /// and results in a [`ParserError`] if both `ALL` and `DISTINCT` are found.
5283    pub fn parse_all_or_distinct(&mut self) -> Result<Option<Distinct>, ParserError> {
5284        let loc = self.peek_token_ref().span.start;
5285        let distinct = match self.parse_one_of_keywords(&[Keyword::ALL, Keyword::DISTINCT]) {
5286            Some(Keyword::ALL) => {
5287                if self.peek_keyword(Keyword::DISTINCT) {
5288                    return parser_err!("Cannot specify ALL then DISTINCT".to_string(), loc);
5289                }
5290                Some(Distinct::All)
5291            }
5292            Some(Keyword::DISTINCT) => {
5293                if self.peek_keyword(Keyword::ALL) {
5294                    return parser_err!("Cannot specify DISTINCT then ALL".to_string(), loc);
5295                }
5296                Some(Distinct::Distinct)
5297            }
5298            None => return Ok(None),
5299            _ => return parser_err!("ALL or DISTINCT", loc),
5300        };
5301
5302        let Some(Distinct::Distinct) = distinct else {
5303            return Ok(distinct);
5304        };
5305        if !self.parse_keyword(Keyword::ON) {
5306            return Ok(Some(Distinct::Distinct));
5307        }
5308
5309        self.expect_token(&Token::LParen)?;
5310        let col_names = if self.consume_token(&Token::RParen) {
5311            self.prev_token();
5312            Vec::new()
5313        } else {
5314            self.parse_comma_separated(Parser::parse_expr)?
5315        };
5316        self.expect_token(&Token::RParen)?;
5317        Ok(Some(Distinct::On(col_names)))
5318    }
5319
5320    /// Parse a SQL CREATE statement
5321    pub fn parse_create(&mut self) -> Result<Statement, ParserError> {
5322        let modifier_loc = self.peek_token_ref().span.start;
5323        let or_replace = self.parse_keywords(&[Keyword::OR, Keyword::REPLACE]);
5324        let or_alter = self.parse_keywords(&[Keyword::OR, Keyword::ALTER]);
5325        let multiset = self.maybe_parse_multiset();
5326        let local = self.parse_one_of_keywords(&[Keyword::LOCAL]).is_some();
5327        let global = self.parse_one_of_keywords(&[Keyword::GLOBAL]).is_some();
5328        let transient = self.parse_one_of_keywords(&[Keyword::TRANSIENT]).is_some();
5329        let global: Option<bool> = if global {
5330            Some(true)
5331        } else if local {
5332            Some(false)
5333        } else {
5334            None
5335        };
5336        let temporary = self
5337            .parse_one_of_keywords(&[Keyword::TEMP, Keyword::TEMPORARY])
5338            .is_some();
5339        let volatile = self.parse_keyword(Keyword::VOLATILE);
5340        let unlogged = self.peek_keywords(&[Keyword::UNLOGGED, Keyword::TABLE]);
5341        if unlogged {
5342            self.expect_keyword(Keyword::UNLOGGED)?;
5343        }
5344        let persistent = dialect_of!(self is DuckDbDialect)
5345            && self.parse_one_of_keywords(&[Keyword::PERSISTENT]).is_some();
5346        let create_view_params = self.parse_create_view_params()?;
5347        if self.peek_keywords(&[Keyword::SNAPSHOT, Keyword::TABLE]) {
5348            self.parse_create_snapshot_table().map(Into::into)
5349        } else if self.peek_keywords(&[Keyword::TEXT, Keyword::SEARCH]) {
5350            self.parse_create_text_search().map(Into::into)
5351        } else if self.parse_keyword(Keyword::TABLE) {
5352            self.parse_create_table(
5353                or_replace, temporary, unlogged, global, transient, volatile, multiset,
5354            )
5355            .map(Into::into)
5356        } else if self.peek_keyword(Keyword::MATERIALIZED)
5357            || self.peek_keyword(Keyword::VIEW)
5358            || self.peek_keywords(&[Keyword::SECURE, Keyword::MATERIALIZED, Keyword::VIEW])
5359            || self.peek_keywords(&[Keyword::SECURE, Keyword::VIEW])
5360        {
5361            self.parse_create_view(or_alter, or_replace, temporary, create_view_params)
5362                .map(Into::into)
5363        } else if self.parse_keyword(Keyword::POLICY) {
5364            self.parse_create_policy().map(Into::into)
5365        } else if self.parse_keyword(Keyword::EXTERNAL) {
5366            self.parse_create_external_table(or_replace).map(Into::into)
5367        } else if self.parse_keyword(Keyword::FUNCTION) {
5368            self.parse_create_function(or_alter, or_replace, temporary)
5369        } else if self.parse_keyword(Keyword::DOMAIN) {
5370            self.parse_create_domain().map(Into::into)
5371        } else if self.parse_keyword(Keyword::TRIGGER) {
5372            self.parse_create_trigger(temporary, or_alter, or_replace, false)
5373                .map(Into::into)
5374        } else if self.parse_keywords(&[Keyword::CONSTRAINT, Keyword::TRIGGER]) {
5375            self.parse_create_trigger(temporary, or_alter, or_replace, true)
5376                .map(Into::into)
5377        } else if self.parse_keyword(Keyword::MACRO) {
5378            self.parse_create_macro(or_replace, temporary)
5379        } else if self.parse_keyword(Keyword::SECRET) {
5380            self.parse_create_secret(or_replace, temporary, persistent)
5381        } else if self.parse_keyword(Keyword::USER) {
5382            self.parse_create_user(or_replace).map(Into::into)
5383        } else if self.parse_keyword(Keyword::SCHEMA) {
5384            self.parse_create_schema(or_replace)
5385        } else if self.parse_keyword(Keyword::WAREHOUSE) {
5386            self.parse_create_warehouse(or_replace).map(Into::into)
5387        } else if or_replace {
5388            self.expected_ref(
5389                "[EXTERNAL] TABLE or [MATERIALIZED] VIEW or FUNCTION or SCHEMA or WAREHOUSE after CREATE OR REPLACE",
5390                self.peek_token_ref(),
5391            )
5392        } else if self.parse_keyword(Keyword::EXTENSION) {
5393            self.parse_create_extension().map(Into::into)
5394        } else if self.parse_keyword(Keyword::INDEX) {
5395            self.parse_create_index(false).map(Into::into)
5396        } else if self.parse_keywords(&[Keyword::UNIQUE, Keyword::INDEX]) {
5397            self.parse_create_index(true).map(Into::into)
5398        } else if self.parse_keyword(Keyword::VIRTUAL) {
5399            self.parse_create_virtual_table()
5400        } else if self.parse_keyword(Keyword::DATABASE) {
5401            self.parse_create_database()
5402        } else if self.parse_keyword(Keyword::ROLE) {
5403            self.parse_create_role().map(Into::into)
5404        } else if self.parse_keyword(Keyword::SEQUENCE) {
5405            self.parse_create_sequence(temporary)
5406        } else if self.parse_keyword(Keyword::COLLATION) {
5407            self.parse_create_collation().map(Into::into)
5408        } else if self.parse_keyword(Keyword::TYPE) {
5409            self.parse_create_type()
5410        } else if self.parse_keyword(Keyword::PROCEDURE)
5411            || self.dialect.supports_create_proc_syntax() && self.parse_keyword(Keyword::PROC)
5412        {
5413            self.parse_create_procedure(or_alter)
5414        } else if self.parse_keyword(Keyword::CONNECTOR) {
5415            self.parse_create_connector().map(Into::into)
5416        } else if self.parse_keyword(Keyword::OPERATOR) {
5417            // Check if this is CREATE OPERATOR FAMILY or CREATE OPERATOR CLASS
5418            if self.parse_keyword(Keyword::FAMILY) {
5419                self.parse_create_operator_family().map(Into::into)
5420            } else if self.parse_keyword(Keyword::CLASS) {
5421                self.parse_create_operator_class().map(Into::into)
5422            } else {
5423                self.parse_create_operator().map(Into::into)
5424            }
5425        } else if self.parse_keyword(Keyword::SERVER) {
5426            self.parse_pg_create_server()
5427        } else if self.parse_keywords(&[Keyword::FOREIGN, Keyword::TABLE]) {
5428            // `or_replace` cannot reach here today, since the arm above catches it.
5429            // It stays so that reordering the arms cannot make it fall through.
5430            if or_replace
5431                || or_alter
5432                || temporary
5433                || global.is_some()
5434                || transient
5435                || volatile
5436                || multiset.is_some()
5437                || persistent
5438                || create_view_params.is_some()
5439            {
5440                return parser_err!(
5441                    "CREATE FOREIGN TABLE does not accept this modifier",
5442                    modifier_loc
5443                );
5444            }
5445            self.parse_create_foreign_table().map(Into::into)
5446        } else {
5447            self.expected_ref("an object type after CREATE", self.peek_token_ref())
5448        }
5449    }
5450
5451    fn parse_text_search_object_type(&mut self) -> Result<TextSearchObjectType, ParserError> {
5452        match self.expect_one_of_keywords(&[
5453            Keyword::DICTIONARY,
5454            Keyword::CONFIGURATION,
5455            Keyword::TEMPLATE,
5456            Keyword::PARSER,
5457        ])? {
5458            Keyword::DICTIONARY => Ok(TextSearchObjectType::Dictionary),
5459            Keyword::CONFIGURATION => Ok(TextSearchObjectType::Configuration),
5460            Keyword::TEMPLATE => Ok(TextSearchObjectType::Template),
5461            Keyword::PARSER => Ok(TextSearchObjectType::Parser),
5462            unexpected_keyword => Err(ParserError::ParserError(format!(
5463                "Internal parser error: expected any of {{DICTIONARY, CONFIGURATION, TEMPLATE, PARSER}}, got {unexpected_keyword:?}"
5464            ))),
5465        }
5466    }
5467
5468    /// Parse a `CREATE TEXT SEARCH ...` statement.
5469    pub fn parse_create_text_search(&mut self) -> Result<CreateTextSearch, ParserError> {
5470        self.expect_keywords(&[Keyword::TEXT, Keyword::SEARCH])?;
5471        let object_type = self.parse_text_search_object_type()?;
5472        let name = self.parse_object_name(false)?;
5473        self.expect_token(&Token::LParen)?;
5474        let options = self.parse_comma_separated(Parser::parse_sql_option)?;
5475        self.expect_token(&Token::RParen)?;
5476        Ok(CreateTextSearch {
5477            object_type,
5478            name,
5479            options,
5480        })
5481    }
5482
5483    fn parse_alter_text_search_option(&mut self) -> Result<AlterTextSearchOption, ParserError> {
5484        let key = self.parse_identifier()?;
5485        let value = if self.consume_token(&Token::Eq) {
5486            Some(self.parse_expr()?)
5487        } else {
5488            None
5489        };
5490        Ok(AlterTextSearchOption { key, value })
5491    }
5492
5493    /// Parse an `ALTER TEXT SEARCH ...` statement.
5494    pub fn parse_alter_text_search(&mut self) -> Result<AlterTextSearch, ParserError> {
5495        self.expect_keywords(&[Keyword::TEXT, Keyword::SEARCH])?;
5496        let object_type = self.parse_text_search_object_type()?;
5497        let name = self.parse_object_name(false)?;
5498
5499        let operation = if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
5500            AlterTextSearchOperation::RenameTo {
5501                new_name: self.parse_identifier()?,
5502            }
5503        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
5504            AlterTextSearchOperation::OwnerTo(self.parse_owner()?)
5505        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
5506            AlterTextSearchOperation::SetSchema {
5507                schema_name: self.parse_object_name(false)?,
5508            }
5509        } else if self.consume_token(&Token::LParen) {
5510            let options = self.parse_comma_separated(Parser::parse_alter_text_search_option)?;
5511            self.expect_token(&Token::RParen)?;
5512            AlterTextSearchOperation::SetOptions { options }
5513        } else {
5514            let expected = "RENAME TO, OWNER TO, SET SCHEMA, or (...) after ALTER TEXT SEARCH";
5515            return self.expected_ref(expected, self.peek_token_ref());
5516        };
5517
5518        Ok(AlterTextSearch {
5519            object_type,
5520            name,
5521            operation,
5522        })
5523    }
5524
5525    fn parse_create_user(&mut self, or_replace: bool) -> Result<CreateUser, ParserError> {
5526        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
5527        let name = self.parse_identifier()?;
5528        let options = self
5529            .parse_key_value_options(false, &[Keyword::WITH, Keyword::TAG])?
5530            .options;
5531        let with_tags = self.parse_keyword(Keyword::WITH);
5532        let tags = if self.parse_keyword(Keyword::TAG) {
5533            self.parse_key_value_options(true, &[])?.options
5534        } else {
5535            vec![]
5536        };
5537        Ok(CreateUser {
5538            or_replace,
5539            if_not_exists,
5540            name,
5541            options: KeyValueOptions {
5542                options,
5543                delimiter: KeyValueOptionsDelimiter::Space,
5544            },
5545            with_tags,
5546            tags: KeyValueOptions {
5547                options: tags,
5548                delimiter: KeyValueOptionsDelimiter::Comma,
5549            },
5550        })
5551    }
5552
5553    /// Parse a `CREATE WAREHOUSE` statement.
5554    ///
5555    /// See <https://docs.snowflake.com/en/sql-reference/sql/create-warehouse>
5556    fn parse_create_warehouse(&mut self, or_replace: bool) -> Result<CreateWarehouse, ParserError> {
5557        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
5558        let name = self.parse_object_name(false)?;
5559        let _ = self.parse_keyword(Keyword::WITH);
5560        let options = self.parse_key_value_options(false, &[])?;
5561        Ok(CreateWarehouse {
5562            or_replace,
5563            if_not_exists,
5564            name,
5565            options,
5566        })
5567    }
5568
5569    /// See [DuckDB Docs](https://duckdb.org/docs/sql/statements/create_secret.html) for more details.
5570    pub fn parse_create_secret(
5571        &mut self,
5572        or_replace: bool,
5573        temporary: bool,
5574        persistent: bool,
5575    ) -> Result<Statement, ParserError> {
5576        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
5577
5578        let mut storage_specifier = None;
5579        let mut name = None;
5580        if self.peek_token_ref().token != Token::LParen {
5581            if self.parse_keyword(Keyword::IN) {
5582                storage_specifier = self.parse_identifier().ok()
5583            } else {
5584                name = self.parse_identifier().ok();
5585            }
5586
5587            // Storage specifier may follow the name
5588            if storage_specifier.is_none()
5589                && self.peek_token_ref().token != Token::LParen
5590                && self.parse_keyword(Keyword::IN)
5591            {
5592                storage_specifier = self.parse_identifier().ok();
5593            }
5594        }
5595
5596        self.expect_token(&Token::LParen)?;
5597        self.expect_keyword_is(Keyword::TYPE)?;
5598        let secret_type = self.parse_identifier()?;
5599
5600        let mut options = Vec::new();
5601        if self.consume_token(&Token::Comma) {
5602            options.append(&mut self.parse_comma_separated(|p| {
5603                let key = p.parse_identifier()?;
5604                let value = p.parse_identifier()?;
5605                Ok(SecretOption { key, value })
5606            })?);
5607        }
5608        self.expect_token(&Token::RParen)?;
5609
5610        let temp = match (temporary, persistent) {
5611            (true, false) => Some(true),
5612            (false, true) => Some(false),
5613            (false, false) => None,
5614            _ => self.expected_ref("TEMPORARY or PERSISTENT", self.peek_token_ref())?,
5615        };
5616
5617        Ok(Statement::CreateSecret {
5618            or_replace,
5619            temporary: temp,
5620            if_not_exists,
5621            name,
5622            storage_specifier,
5623            secret_type,
5624            options,
5625        })
5626    }
5627
5628    /// Parse a CACHE TABLE statement
5629    pub fn parse_cache_table(&mut self) -> Result<Statement, ParserError> {
5630        let (mut table_flag, mut options, mut has_as, mut query) = (None, vec![], false, None);
5631        if self.parse_keyword(Keyword::TABLE) {
5632            let table_name = self.parse_object_name(false)?;
5633            if self.peek_token_ref().token != Token::EOF {
5634                if let Token::Word(word) = &self.peek_token_ref().token {
5635                    if word.keyword == Keyword::OPTIONS {
5636                        options = self.parse_options(Keyword::OPTIONS)?
5637                    }
5638                };
5639
5640                if self.peek_token_ref().token != Token::EOF {
5641                    let (a, q) = self.parse_as_query()?;
5642                    has_as = a;
5643                    query = Some(q);
5644                }
5645
5646                Ok(Statement::Cache {
5647                    table_flag,
5648                    table_name,
5649                    has_as,
5650                    options,
5651                    query,
5652                })
5653            } else {
5654                Ok(Statement::Cache {
5655                    table_flag,
5656                    table_name,
5657                    has_as,
5658                    options,
5659                    query,
5660                })
5661            }
5662        } else {
5663            table_flag = Some(self.parse_object_name(false)?);
5664            if self.parse_keyword(Keyword::TABLE) {
5665                let table_name = self.parse_object_name(false)?;
5666                if self.peek_token_ref().token != Token::EOF {
5667                    if let Token::Word(word) = &self.peek_token_ref().token {
5668                        if word.keyword == Keyword::OPTIONS {
5669                            options = self.parse_options(Keyword::OPTIONS)?
5670                        }
5671                    };
5672
5673                    if self.peek_token_ref().token != Token::EOF {
5674                        let (a, q) = self.parse_as_query()?;
5675                        has_as = a;
5676                        query = Some(q);
5677                    }
5678
5679                    Ok(Statement::Cache {
5680                        table_flag,
5681                        table_name,
5682                        has_as,
5683                        options,
5684                        query,
5685                    })
5686                } else {
5687                    Ok(Statement::Cache {
5688                        table_flag,
5689                        table_name,
5690                        has_as,
5691                        options,
5692                        query,
5693                    })
5694                }
5695            } else {
5696                if self.peek_token_ref().token == Token::EOF {
5697                    self.prev_token();
5698                }
5699                self.expected_ref("a `TABLE` keyword", self.peek_token_ref())
5700            }
5701        }
5702    }
5703
5704    /// Parse 'AS' before as query,such as `WITH XXX AS SELECT XXX` oer `CACHE TABLE AS SELECT XXX`
5705    pub fn parse_as_query(&mut self) -> Result<(bool, Box<Query>), ParserError> {
5706        match &self.peek_token_ref().token {
5707            Token::Word(word) => match word.keyword {
5708                Keyword::AS => {
5709                    self.next_token();
5710                    Ok((true, self.parse_query()?))
5711                }
5712                _ => Ok((false, self.parse_query()?)),
5713            },
5714            _ => self.expected_ref("a QUERY statement", self.peek_token_ref()),
5715        }
5716    }
5717
5718    /// Parse a UNCACHE TABLE statement
5719    pub fn parse_uncache_table(&mut self) -> Result<Statement, ParserError> {
5720        self.expect_keyword_is(Keyword::TABLE)?;
5721        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
5722        let table_name = self.parse_object_name(false)?;
5723        Ok(Statement::UNCache {
5724            table_name,
5725            if_exists,
5726        })
5727    }
5728
5729    /// SQLite-specific `CREATE VIRTUAL TABLE`
5730    pub fn parse_create_virtual_table(&mut self) -> Result<Statement, ParserError> {
5731        self.expect_keyword_is(Keyword::TABLE)?;
5732        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
5733        let table_name = self.parse_object_name(false)?;
5734        self.expect_keyword_is(Keyword::USING)?;
5735        let module_name = self.parse_identifier()?;
5736        // SQLite docs note that module "arguments syntax is sufficiently
5737        // general that the arguments can be made to appear as column
5738        // definitions in a traditional CREATE TABLE statement", but
5739        // we don't implement that.
5740        let module_args = self.parse_parenthesized_column_list(Optional, false)?;
5741        Ok(Statement::CreateVirtualTable {
5742            name: table_name,
5743            if_not_exists,
5744            module_name,
5745            module_args,
5746        })
5747    }
5748
5749    /// Parse a `CREATE SCHEMA` statement.
5750    pub fn parse_create_schema(&mut self, or_replace: bool) -> Result<Statement, ParserError> {
5751        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
5752
5753        let schema_name = self.parse_schema_name()?;
5754
5755        let default_collate_spec = if self.parse_keywords(&[Keyword::DEFAULT, Keyword::COLLATE]) {
5756            Some(self.parse_expr()?)
5757        } else {
5758            None
5759        };
5760
5761        let with = if self.peek_keyword(Keyword::WITH) {
5762            Some(self.parse_options(Keyword::WITH)?)
5763        } else {
5764            None
5765        };
5766
5767        let options = if self.peek_keyword(Keyword::OPTIONS) {
5768            Some(self.parse_options(Keyword::OPTIONS)?)
5769        } else {
5770            None
5771        };
5772
5773        let clone = if self.parse_keyword(Keyword::CLONE) {
5774            Some(self.parse_object_name(false)?)
5775        } else {
5776            None
5777        };
5778
5779        Ok(Statement::CreateSchema {
5780            schema_name,
5781            or_replace,
5782            if_not_exists,
5783            with,
5784            options,
5785            default_collate_spec,
5786            clone,
5787        })
5788    }
5789
5790    fn parse_schema_name(&mut self) -> Result<SchemaName, ParserError> {
5791        if self.parse_keyword(Keyword::AUTHORIZATION) {
5792            Ok(SchemaName::UnnamedAuthorization(self.parse_identifier()?))
5793        } else {
5794            let name = self.parse_object_name(false)?;
5795
5796            if self.parse_keyword(Keyword::AUTHORIZATION) {
5797                Ok(SchemaName::NamedAuthorization(
5798                    name,
5799                    self.parse_identifier()?,
5800                ))
5801            } else {
5802                Ok(SchemaName::Simple(name))
5803            }
5804        }
5805    }
5806
5807    /// Parse a `CREATE DATABASE` statement.
5808    pub fn parse_create_database(&mut self) -> Result<Statement, ParserError> {
5809        let ine = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
5810        let db_name = self.parse_object_name(false)?;
5811        let mut location = None;
5812        let mut managed_location = None;
5813        loop {
5814            match self.parse_one_of_keywords(&[Keyword::LOCATION, Keyword::MANAGEDLOCATION]) {
5815                Some(Keyword::LOCATION) => location = Some(self.parse_literal_string()?),
5816                Some(Keyword::MANAGEDLOCATION) => {
5817                    managed_location = Some(self.parse_literal_string()?)
5818                }
5819                _ => break,
5820            }
5821        }
5822        let clone = if self.parse_keyword(Keyword::CLONE) {
5823            Some(self.parse_object_name(false)?)
5824        } else {
5825            None
5826        };
5827
5828        // Parse MySQL-style [DEFAULT] CHARACTER SET and [DEFAULT] COLLATE options
5829        //
5830        // Note: The docs only mention `CHARACTER SET`, but `CHARSET` is also supported.
5831        // Furthermore, MySQL will only accept one character set, raising an error if there is more
5832        // than one, but will accept multiple collations and use the last one.
5833        //
5834        // <https://dev.mysql.com/doc/refman/8.4/en/create-database.html>
5835        let mut default_charset = None;
5836        let mut default_collation = None;
5837        loop {
5838            let has_default = self.parse_keyword(Keyword::DEFAULT);
5839            if default_charset.is_none() && self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET])
5840                || self.parse_keyword(Keyword::CHARSET)
5841            {
5842                let _ = self.consume_token(&Token::Eq);
5843                default_charset = Some(self.parse_identifier()?.value);
5844            } else if self.parse_keyword(Keyword::COLLATE) {
5845                let _ = self.consume_token(&Token::Eq);
5846                default_collation = Some(self.parse_identifier()?.value);
5847            } else if has_default {
5848                // DEFAULT keyword not followed by CHARACTER SET, CHARSET, or COLLATE
5849                self.prev_token();
5850                break;
5851            } else {
5852                break;
5853            }
5854        }
5855
5856        Ok(Statement::CreateDatabase {
5857            db_name,
5858            if_not_exists: ine,
5859            location,
5860            managed_location,
5861            or_replace: false,
5862            transient: false,
5863            clone,
5864            data_retention_time_in_days: None,
5865            max_data_extension_time_in_days: None,
5866            external_volume: None,
5867            catalog: None,
5868            replace_invalid_characters: None,
5869            default_ddl_collation: None,
5870            storage_serialization_policy: None,
5871            comment: None,
5872            default_charset,
5873            default_collation,
5874            catalog_sync: None,
5875            catalog_sync_namespace_mode: None,
5876            catalog_sync_namespace_flatten_delimiter: None,
5877            with_tags: None,
5878            with_contacts: None,
5879        })
5880    }
5881
5882    /// Parse an optional `USING` clause for `CREATE FUNCTION`.
5883    pub fn parse_optional_create_function_using(
5884        &mut self,
5885    ) -> Result<Option<CreateFunctionUsing>, ParserError> {
5886        if !self.parse_keyword(Keyword::USING) {
5887            return Ok(None);
5888        };
5889        let keyword =
5890            self.expect_one_of_keywords(&[Keyword::JAR, Keyword::FILE, Keyword::ARCHIVE])?;
5891
5892        let uri = self.parse_literal_string()?;
5893
5894        match keyword {
5895            Keyword::JAR => Ok(Some(CreateFunctionUsing::Jar(uri))),
5896            Keyword::FILE => Ok(Some(CreateFunctionUsing::File(uri))),
5897            Keyword::ARCHIVE => Ok(Some(CreateFunctionUsing::Archive(uri))),
5898            _ => self.expected(
5899                "JAR, FILE or ARCHIVE, got {:?}",
5900                TokenWithSpan::wrap(Token::make_keyword(format!("{keyword:?}").as_str())),
5901            ),
5902        }
5903    }
5904
5905    /// Parse a `CREATE FUNCTION` statement.
5906    pub fn parse_create_function(
5907        &mut self,
5908        or_alter: bool,
5909        or_replace: bool,
5910        temporary: bool,
5911    ) -> Result<Statement, ParserError> {
5912        if dialect_of!(self is HiveDialect) {
5913            self.parse_hive_create_function(or_replace, temporary)
5914                .map(Into::into)
5915        } else if dialect_of!(self is PostgreSqlDialect | GenericDialect) {
5916            self.parse_postgres_create_function(or_replace, temporary)
5917                .map(Into::into)
5918        } else if dialect_of!(self is DuckDbDialect) {
5919            self.parse_create_macro(or_replace, temporary)
5920        } else if dialect_of!(self is BigQueryDialect) {
5921            self.parse_bigquery_create_function(or_replace, temporary)
5922                .map(Into::into)
5923        } else if dialect_of!(self is MsSqlDialect) {
5924            self.parse_mssql_create_function(or_alter, or_replace, temporary)
5925                .map(Into::into)
5926        } else {
5927            self.prev_token();
5928            self.expected_ref("an object type after CREATE", self.peek_token_ref())
5929        }
5930    }
5931
5932    /// Parse `CREATE FUNCTION` for [PostgreSQL]
5933    ///
5934    /// [PostgreSQL]: https://www.postgresql.org/docs/15/sql-createfunction.html
5935    fn parse_postgres_create_function(
5936        &mut self,
5937        or_replace: bool,
5938        temporary: bool,
5939    ) -> Result<CreateFunction, ParserError> {
5940        let name = self.parse_object_name(false)?;
5941
5942        self.expect_token(&Token::LParen)?;
5943        let args = if Token::RParen != self.peek_token_ref().token {
5944            self.parse_comma_separated(Parser::parse_function_arg)?
5945        } else {
5946            vec![]
5947        };
5948        self.expect_token(&Token::RParen)?;
5949
5950        let return_type = if self.parse_keyword(Keyword::RETURNS) {
5951            Some(self.parse_function_return_type()?)
5952        } else {
5953            None
5954        };
5955
5956        #[derive(Default)]
5957        struct Body {
5958            language: Option<Ident>,
5959            behavior: Option<FunctionBehavior>,
5960            function_body: Option<CreateFunctionBody>,
5961            called_on_null: Option<FunctionCalledOnNull>,
5962            parallel: Option<FunctionParallel>,
5963            security: Option<FunctionSecurity>,
5964        }
5965        let mut body = Body::default();
5966        let mut set_params: Vec<FunctionDefinitionSetParam> = Vec::new();
5967        loop {
5968            fn ensure_not_set<T>(field: &Option<T>, name: &str) -> Result<(), ParserError> {
5969                if field.is_some() {
5970                    return Err(ParserError::ParserError(format!(
5971                        "{name} specified more than once",
5972                    )));
5973                }
5974                Ok(())
5975            }
5976            if self.parse_keyword(Keyword::AS) {
5977                ensure_not_set(&body.function_body, "AS")?;
5978                body.function_body = Some(self.parse_create_function_body_string()?);
5979            } else if self.parse_keyword(Keyword::LANGUAGE) {
5980                ensure_not_set(&body.language, "LANGUAGE")?;
5981                body.language = Some(self.parse_identifier()?);
5982            } else if self.parse_keyword(Keyword::IMMUTABLE) {
5983                ensure_not_set(&body.behavior, "IMMUTABLE | STABLE | VOLATILE")?;
5984                body.behavior = Some(FunctionBehavior::Immutable);
5985            } else if self.parse_keyword(Keyword::STABLE) {
5986                ensure_not_set(&body.behavior, "IMMUTABLE | STABLE | VOLATILE")?;
5987                body.behavior = Some(FunctionBehavior::Stable);
5988            } else if self.parse_keyword(Keyword::VOLATILE) {
5989                ensure_not_set(&body.behavior, "IMMUTABLE | STABLE | VOLATILE")?;
5990                body.behavior = Some(FunctionBehavior::Volatile);
5991            } else if self.parse_keywords(&[
5992                Keyword::CALLED,
5993                Keyword::ON,
5994                Keyword::NULL,
5995                Keyword::INPUT,
5996            ]) {
5997                ensure_not_set(
5998                    &body.called_on_null,
5999                    "CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT",
6000                )?;
6001                body.called_on_null = Some(FunctionCalledOnNull::CalledOnNullInput);
6002            } else if self.parse_keywords(&[
6003                Keyword::RETURNS,
6004                Keyword::NULL,
6005                Keyword::ON,
6006                Keyword::NULL,
6007                Keyword::INPUT,
6008            ]) {
6009                ensure_not_set(
6010                    &body.called_on_null,
6011                    "CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT",
6012                )?;
6013                body.called_on_null = Some(FunctionCalledOnNull::ReturnsNullOnNullInput);
6014            } else if self.parse_keyword(Keyword::STRICT) {
6015                ensure_not_set(
6016                    &body.called_on_null,
6017                    "CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT",
6018                )?;
6019                body.called_on_null = Some(FunctionCalledOnNull::Strict);
6020            } else if self.parse_keyword(Keyword::PARALLEL) {
6021                ensure_not_set(&body.parallel, "PARALLEL { UNSAFE | RESTRICTED | SAFE }")?;
6022                if self.parse_keyword(Keyword::UNSAFE) {
6023                    body.parallel = Some(FunctionParallel::Unsafe);
6024                } else if self.parse_keyword(Keyword::RESTRICTED) {
6025                    body.parallel = Some(FunctionParallel::Restricted);
6026                } else if self.parse_keyword(Keyword::SAFE) {
6027                    body.parallel = Some(FunctionParallel::Safe);
6028                } else {
6029                    return self
6030                        .expected_ref("one of UNSAFE | RESTRICTED | SAFE", self.peek_token_ref());
6031                }
6032            } else if self.parse_keyword(Keyword::SECURITY) {
6033                ensure_not_set(&body.security, "SECURITY { DEFINER | INVOKER }")?;
6034                if self.parse_keyword(Keyword::DEFINER) {
6035                    body.security = Some(FunctionSecurity::Definer);
6036                } else if self.parse_keyword(Keyword::INVOKER) {
6037                    body.security = Some(FunctionSecurity::Invoker);
6038                } else {
6039                    return self.expected_ref("DEFINER or INVOKER", self.peek_token_ref());
6040                }
6041            } else if self.parse_keyword(Keyword::SET) {
6042                let name = self.parse_object_name(false)?;
6043                let value = if self.parse_keywords(&[Keyword::FROM, Keyword::CURRENT]) {
6044                    FunctionSetValue::FromCurrent
6045                } else {
6046                    if !self.consume_token(&Token::Eq) && !self.parse_keyword(Keyword::TO) {
6047                        return self.expected_ref("= or TO", self.peek_token_ref());
6048                    }
6049                    if self.parse_keyword(Keyword::DEFAULT) {
6050                        FunctionSetValue::Default
6051                    } else {
6052                        let values = self.parse_comma_separated(Parser::parse_expr)?;
6053                        FunctionSetValue::Values(values)
6054                    }
6055                };
6056                set_params.push(FunctionDefinitionSetParam { name, value });
6057            } else if self.parse_keyword(Keyword::RETURN) {
6058                ensure_not_set(&body.function_body, "RETURN")?;
6059                body.function_body = Some(CreateFunctionBody::Return(self.parse_expr()?));
6060            } else {
6061                break;
6062            }
6063        }
6064
6065        Ok(CreateFunction {
6066            or_alter: false,
6067            or_replace,
6068            temporary,
6069            name,
6070            args: Some(args),
6071            return_type,
6072            behavior: body.behavior,
6073            called_on_null: body.called_on_null,
6074            parallel: body.parallel,
6075            security: body.security,
6076            set_params,
6077            language: body.language,
6078            function_body: body.function_body,
6079            if_not_exists: false,
6080            using: None,
6081            determinism_specifier: None,
6082            options: None,
6083            remote_connection: None,
6084        })
6085    }
6086
6087    /// Parse `CREATE FUNCTION` for [Hive]
6088    ///
6089    /// [Hive]: https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-Create/Drop/ReloadFunction
6090    fn parse_hive_create_function(
6091        &mut self,
6092        or_replace: bool,
6093        temporary: bool,
6094    ) -> Result<CreateFunction, ParserError> {
6095        let name = self.parse_object_name(false)?;
6096        self.expect_keyword_is(Keyword::AS)?;
6097
6098        let body = self.parse_create_function_body_string()?;
6099        let using = self.parse_optional_create_function_using()?;
6100
6101        Ok(CreateFunction {
6102            or_alter: false,
6103            or_replace,
6104            temporary,
6105            name,
6106            function_body: Some(body),
6107            using,
6108            if_not_exists: false,
6109            args: None,
6110            return_type: None,
6111            behavior: None,
6112            called_on_null: None,
6113            parallel: None,
6114            security: None,
6115            set_params: vec![],
6116            language: None,
6117            determinism_specifier: None,
6118            options: None,
6119            remote_connection: None,
6120        })
6121    }
6122
6123    /// Parse `CREATE FUNCTION` for [BigQuery]
6124    ///
6125    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_function_statement
6126    fn parse_bigquery_create_function(
6127        &mut self,
6128        or_replace: bool,
6129        temporary: bool,
6130    ) -> Result<CreateFunction, ParserError> {
6131        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
6132        let (name, args) = self.parse_create_function_name_and_params()?;
6133
6134        let return_type = if self.parse_keyword(Keyword::RETURNS) {
6135            Some(self.parse_function_return_type()?)
6136        } else {
6137            None
6138        };
6139
6140        let determinism_specifier = if self.parse_keyword(Keyword::DETERMINISTIC) {
6141            Some(FunctionDeterminismSpecifier::Deterministic)
6142        } else if self.parse_keywords(&[Keyword::NOT, Keyword::DETERMINISTIC]) {
6143            Some(FunctionDeterminismSpecifier::NotDeterministic)
6144        } else {
6145            None
6146        };
6147
6148        let language = if self.parse_keyword(Keyword::LANGUAGE) {
6149            Some(self.parse_identifier()?)
6150        } else {
6151            None
6152        };
6153
6154        let remote_connection =
6155            if self.parse_keywords(&[Keyword::REMOTE, Keyword::WITH, Keyword::CONNECTION]) {
6156                Some(self.parse_object_name(false)?)
6157            } else {
6158                None
6159            };
6160
6161        // `OPTIONS` may come before of after the function body but
6162        // may be specified at most once.
6163        let mut options = self.maybe_parse_options(Keyword::OPTIONS)?;
6164
6165        let function_body = if remote_connection.is_none() {
6166            self.expect_keyword_is(Keyword::AS)?;
6167            let expr = self.parse_expr()?;
6168            if options.is_none() {
6169                options = self.maybe_parse_options(Keyword::OPTIONS)?;
6170                Some(CreateFunctionBody::AsBeforeOptions {
6171                    body: expr,
6172                    link_symbol: None,
6173                })
6174            } else {
6175                Some(CreateFunctionBody::AsAfterOptions(expr))
6176            }
6177        } else {
6178            None
6179        };
6180
6181        Ok(CreateFunction {
6182            or_alter: false,
6183            or_replace,
6184            temporary,
6185            if_not_exists,
6186            name,
6187            args: Some(args),
6188            return_type,
6189            function_body,
6190            language,
6191            determinism_specifier,
6192            options,
6193            remote_connection,
6194            using: None,
6195            behavior: None,
6196            called_on_null: None,
6197            parallel: None,
6198            security: None,
6199            set_params: vec![],
6200        })
6201    }
6202
6203    /// Parse `CREATE FUNCTION` for [MsSql]
6204    ///
6205    /// [MsSql]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql
6206    fn parse_mssql_create_function(
6207        &mut self,
6208        or_alter: bool,
6209        or_replace: bool,
6210        temporary: bool,
6211    ) -> Result<CreateFunction, ParserError> {
6212        let (name, args) = self.parse_create_function_name_and_params()?;
6213
6214        self.expect_keyword(Keyword::RETURNS)?;
6215
6216        let return_table = self.maybe_parse(|p| {
6217            let return_table_name = p.parse_identifier()?;
6218
6219            p.expect_keyword_is(Keyword::TABLE)?;
6220            p.prev_token();
6221
6222            let table_column_defs = match p.parse_data_type()? {
6223                DataType::Table(Some(table_column_defs)) if !table_column_defs.is_empty() => {
6224                    table_column_defs
6225                }
6226                _ => parser_err!(
6227                    "Expected table column definitions after TABLE keyword",
6228                    p.peek_token_ref().span.start
6229                )?,
6230            };
6231
6232            Ok(DataType::NamedTable {
6233                name: ObjectName(vec![ObjectNamePart::Identifier(return_table_name)]),
6234                columns: table_column_defs,
6235            })
6236        })?;
6237
6238        let data_type = match return_table {
6239            Some(table_type) => table_type,
6240            None => self.parse_data_type()?,
6241        };
6242        let return_type = Some(FunctionReturnType::DataType(data_type));
6243
6244        let _ = self.parse_keyword(Keyword::AS);
6245
6246        let function_body = if self.peek_keyword(Keyword::BEGIN) {
6247            let begin_token = self.expect_keyword(Keyword::BEGIN)?;
6248            let statements = self.parse_statement_list(&[Keyword::END])?;
6249            let end_token = self.expect_keyword(Keyword::END)?;
6250
6251            Some(CreateFunctionBody::AsBeginEnd(BeginEndStatements {
6252                begin_token: AttachedToken(begin_token),
6253                statements,
6254                end_token: AttachedToken(end_token),
6255            }))
6256        } else if self.parse_keyword(Keyword::RETURN) {
6257            if self.peek_token_ref().token == Token::LParen {
6258                Some(CreateFunctionBody::AsReturnExpr(self.parse_expr()?))
6259            } else if self.peek_keyword(Keyword::SELECT) {
6260                let select = self.parse_select()?;
6261                Some(CreateFunctionBody::AsReturnSelect(select))
6262            } else {
6263                parser_err!(
6264                    "Expected a subquery (or bare SELECT statement) after RETURN",
6265                    self.peek_token_ref().span.start
6266                )?
6267            }
6268        } else {
6269            parser_err!("Unparsable function body", self.peek_token_ref().span.start)?
6270        };
6271
6272        Ok(CreateFunction {
6273            or_alter,
6274            or_replace,
6275            temporary,
6276            if_not_exists: false,
6277            name,
6278            args: Some(args),
6279            return_type,
6280            function_body,
6281            language: None,
6282            determinism_specifier: None,
6283            options: None,
6284            remote_connection: None,
6285            using: None,
6286            behavior: None,
6287            called_on_null: None,
6288            parallel: None,
6289            security: None,
6290            set_params: vec![],
6291        })
6292    }
6293
6294    fn parse_function_return_type(&mut self) -> Result<FunctionReturnType, ParserError> {
6295        if self.parse_keyword(Keyword::SETOF) {
6296            Ok(FunctionReturnType::SetOf(self.parse_data_type()?))
6297        } else {
6298            Ok(FunctionReturnType::DataType(self.parse_data_type()?))
6299        }
6300    }
6301
6302    fn parse_create_function_name_and_params(
6303        &mut self,
6304    ) -> Result<(ObjectName, Vec<OperateFunctionArg>), ParserError> {
6305        let name = self.parse_object_name(false)?;
6306        let parse_function_param =
6307            |parser: &mut Parser| -> Result<OperateFunctionArg, ParserError> {
6308                let name = parser.parse_identifier()?;
6309                let data_type = parser.parse_data_type()?;
6310                let default_expr = if parser.consume_token(&Token::Eq) {
6311                    Some(parser.parse_expr()?)
6312                } else {
6313                    None
6314                };
6315
6316                Ok(OperateFunctionArg {
6317                    mode: None,
6318                    name: Some(name),
6319                    data_type,
6320                    default_expr,
6321                })
6322            };
6323        self.expect_token(&Token::LParen)?;
6324        let args = self.parse_comma_separated0(parse_function_param, Token::RParen)?;
6325        self.expect_token(&Token::RParen)?;
6326        Ok((name, args))
6327    }
6328
6329    fn parse_function_arg(&mut self) -> Result<OperateFunctionArg, ParserError> {
6330        let mode = if self.parse_keyword(Keyword::IN) {
6331            Some(ArgMode::In)
6332        } else if self.parse_keyword(Keyword::OUT) {
6333            Some(ArgMode::Out)
6334        } else if self.parse_keyword(Keyword::INOUT) {
6335            Some(ArgMode::InOut)
6336        } else if self.parse_keyword(Keyword::VARIADIC) {
6337            Some(ArgMode::Variadic)
6338        } else {
6339            None
6340        };
6341
6342        // parse: [ argname ] argtype
6343        let mut name = None;
6344        let mut data_type = self.parse_data_type()?;
6345
6346        // To check whether the first token is a name or a type, we need to
6347        // peek the next token, which if it is another type keyword, then the
6348        // first token is a name and not a type in itself.
6349        let data_type_idx = self.get_current_index();
6350
6351        // DEFAULT will be parsed as `DataType::Custom`, which is undesirable in this context
6352        fn parse_data_type_no_default(parser: &mut Parser) -> Result<DataType, ParserError> {
6353            if parser.peek_keyword(Keyword::DEFAULT) {
6354                // This dummy error is ignored in `maybe_parse`
6355                parser_err!(
6356                    "The DEFAULT keyword is not a type",
6357                    parser.peek_token_ref().span.start
6358                )
6359            } else {
6360                parser.parse_data_type()
6361            }
6362        }
6363
6364        if let Some(next_data_type) = self.maybe_parse(parse_data_type_no_default)? {
6365            let token = self.token_at(data_type_idx).clone();
6366
6367            // We ensure that the token is a `Word` token, and not other special tokens.
6368            match token.token {
6369                Token::Word(word) => name = Some(word.into_ident(token.span)),
6370                _ => return self.expected("a name or type", token),
6371            }
6372
6373            data_type = next_data_type;
6374        }
6375
6376        let default_expr = if self.parse_keyword(Keyword::DEFAULT) || self.consume_token(&Token::Eq)
6377        {
6378            Some(self.parse_expr()?)
6379        } else {
6380            None
6381        };
6382        Ok(OperateFunctionArg {
6383            mode,
6384            name,
6385            data_type,
6386            default_expr,
6387        })
6388    }
6389
6390    fn parse_aggregate_function_arg(&mut self) -> Result<OperateFunctionArg, ParserError> {
6391        let mode = if self.parse_keyword(Keyword::IN) {
6392            Some(ArgMode::In)
6393        } else {
6394            if self
6395                .peek_one_of_keywords(&[Keyword::OUT, Keyword::INOUT, Keyword::VARIADIC])
6396                .is_some()
6397            {
6398                return self.expected_ref(
6399                    "IN or argument type in aggregate signature",
6400                    self.peek_token_ref(),
6401                );
6402            }
6403            None
6404        };
6405
6406        // Parse: [ argname ] argtype, but do not consume ORDER from
6407        // `... argtype ORDER BY ...` as a type-name disambiguator.
6408        let mut name = None;
6409        let mut data_type = self.parse_data_type()?;
6410        let data_type_idx = self.get_current_index();
6411
6412        fn parse_data_type_for_aggregate_arg(parser: &mut Parser) -> Result<DataType, ParserError> {
6413            if parser.peek_keyword(Keyword::DEFAULT)
6414                || parser.peek_keyword(Keyword::ORDER)
6415                || parser.peek_token_ref().token == Token::Comma
6416                || parser.peek_token_ref().token == Token::RParen
6417            {
6418                // Dummy error ignored by maybe_parse
6419                parser_err!(
6420                    "The current token cannot start an aggregate argument type",
6421                    parser.peek_token_ref().span.start
6422                )
6423            } else {
6424                parser.parse_data_type()
6425            }
6426        }
6427
6428        if let Some(next_data_type) = self.maybe_parse(parse_data_type_for_aggregate_arg)? {
6429            let token = self.token_at(data_type_idx).clone();
6430            match token.token {
6431                Token::Word(word) => name = Some(word.into_ident(token.span)),
6432                _ => return self.expected("a name or type", token),
6433            }
6434
6435            data_type = next_data_type;
6436        }
6437
6438        if self.peek_keyword(Keyword::DEFAULT) || self.peek_token_ref().token == Token::Eq {
6439            return self.expected_ref(
6440                "',' or ')' or ORDER BY after aggregate argument type",
6441                self.peek_token_ref(),
6442            );
6443        }
6444
6445        Ok(OperateFunctionArg {
6446            mode,
6447            name,
6448            data_type,
6449            default_expr: None,
6450        })
6451    }
6452
6453    /// Parse statements of the DropTrigger type such as:
6454    ///
6455    /// ```sql
6456    /// DROP TRIGGER [ IF EXISTS ] name ON table_name [ CASCADE | RESTRICT ]
6457    /// ```
6458    pub fn parse_drop_trigger(&mut self) -> Result<DropTrigger, ParserError> {
6459        if !dialect_of!(self is PostgreSqlDialect | SQLiteDialect | GenericDialect | MySqlDialect | MsSqlDialect)
6460        {
6461            self.prev_token();
6462            return self.expected_ref("an object type after DROP", self.peek_token_ref());
6463        }
6464        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
6465        let trigger_name = self.parse_object_name(false)?;
6466        let table_name = if self.parse_keyword(Keyword::ON) {
6467            Some(self.parse_object_name(false)?)
6468        } else {
6469            None
6470        };
6471        let option = match self.parse_one_of_keywords(&[Keyword::CASCADE, Keyword::RESTRICT]) {
6472            Some(Keyword::CASCADE) => Some(ReferentialAction::Cascade),
6473            Some(Keyword::RESTRICT) => Some(ReferentialAction::Restrict),
6474            Some(unexpected_keyword) => return Err(ParserError::ParserError(
6475                format!("Internal parser error: expected any of {{CASCADE, RESTRICT}}, got {unexpected_keyword:?}"),
6476            )),
6477            None => None,
6478        };
6479        Ok(DropTrigger {
6480            if_exists,
6481            trigger_name,
6482            table_name,
6483            option,
6484        })
6485    }
6486
6487    /// Parse a `CREATE TRIGGER` statement.
6488    pub fn parse_create_trigger(
6489        &mut self,
6490        temporary: bool,
6491        or_alter: bool,
6492        or_replace: bool,
6493        is_constraint: bool,
6494    ) -> Result<CreateTrigger, ParserError> {
6495        if !dialect_of!(self is PostgreSqlDialect | SQLiteDialect | GenericDialect | MySqlDialect | MsSqlDialect)
6496        {
6497            self.prev_token();
6498            return self.expected_ref("an object type after CREATE", self.peek_token_ref());
6499        }
6500
6501        let name = self.parse_object_name(false)?;
6502        let period = self.maybe_parse(|parser| parser.parse_trigger_period())?;
6503
6504        let events = self.parse_keyword_separated(Keyword::OR, Parser::parse_trigger_event)?;
6505        self.expect_keyword_is(Keyword::ON)?;
6506        let table_name = self.parse_object_name(false)?;
6507
6508        let referenced_table_name = if self.parse_keyword(Keyword::FROM) {
6509            self.parse_object_name(true).ok()
6510        } else {
6511            None
6512        };
6513
6514        let characteristics = self.parse_constraint_characteristics()?;
6515
6516        let mut referencing = vec![];
6517        if self.parse_keyword(Keyword::REFERENCING) {
6518            while let Some(refer) = self.parse_trigger_referencing()? {
6519                referencing.push(refer);
6520            }
6521        }
6522
6523        let trigger_object = if self.parse_keyword(Keyword::FOR) {
6524            let include_each = self.parse_keyword(Keyword::EACH);
6525            let trigger_object =
6526                match self.expect_one_of_keywords(&[Keyword::ROW, Keyword::STATEMENT])? {
6527                    Keyword::ROW => TriggerObject::Row,
6528                    Keyword::STATEMENT => TriggerObject::Statement,
6529                    unexpected_keyword => return Err(ParserError::ParserError(
6530                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in ROW/STATEMENT"),
6531                    )),
6532                };
6533
6534            Some(if include_each {
6535                TriggerObjectKind::ForEach(trigger_object)
6536            } else {
6537                TriggerObjectKind::For(trigger_object)
6538            })
6539        } else {
6540            let _ = self.parse_keyword(Keyword::FOR);
6541
6542            None
6543        };
6544
6545        let condition = self
6546            .parse_keyword(Keyword::WHEN)
6547            .then(|| self.parse_expr())
6548            .transpose()?;
6549
6550        let mut exec_body = None;
6551        let mut statements = None;
6552        if self.parse_keyword(Keyword::EXECUTE) {
6553            exec_body = Some(self.parse_trigger_exec_body()?);
6554        } else {
6555            statements = Some(self.parse_conditional_statements(&[Keyword::END])?);
6556        }
6557
6558        Ok(CreateTrigger {
6559            or_alter,
6560            temporary,
6561            or_replace,
6562            is_constraint,
6563            name,
6564            period,
6565            period_before_table: true,
6566            events,
6567            table_name,
6568            referenced_table_name,
6569            referencing,
6570            trigger_object,
6571            condition,
6572            exec_body,
6573            statements_as: false,
6574            statements,
6575            characteristics,
6576        })
6577    }
6578
6579    /// Parse the period part of a trigger (`BEFORE`, `AFTER`, etc.).
6580    pub fn parse_trigger_period(&mut self) -> Result<TriggerPeriod, ParserError> {
6581        Ok(
6582            match self.expect_one_of_keywords(&[
6583                Keyword::FOR,
6584                Keyword::BEFORE,
6585                Keyword::AFTER,
6586                Keyword::INSTEAD,
6587            ])? {
6588                Keyword::FOR => TriggerPeriod::For,
6589                Keyword::BEFORE => TriggerPeriod::Before,
6590                Keyword::AFTER => TriggerPeriod::After,
6591                Keyword::INSTEAD => self
6592                    .expect_keyword_is(Keyword::OF)
6593                    .map(|_| TriggerPeriod::InsteadOf)?,
6594                unexpected_keyword => return Err(ParserError::ParserError(
6595                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in trigger period"),
6596                )),
6597            },
6598        )
6599    }
6600
6601    /// Parse the event part of a trigger (`INSERT`, `UPDATE`, etc.).
6602    pub fn parse_trigger_event(&mut self) -> Result<TriggerEvent, ParserError> {
6603        Ok(
6604            match self.expect_one_of_keywords(&[
6605                Keyword::INSERT,
6606                Keyword::UPDATE,
6607                Keyword::DELETE,
6608                Keyword::TRUNCATE,
6609            ])? {
6610                Keyword::INSERT => TriggerEvent::Insert,
6611                Keyword::UPDATE => {
6612                    if self.parse_keyword(Keyword::OF) {
6613                        let cols = self.parse_comma_separated(Parser::parse_identifier)?;
6614                        TriggerEvent::Update(cols)
6615                    } else {
6616                        TriggerEvent::Update(vec![])
6617                    }
6618                }
6619                Keyword::DELETE => TriggerEvent::Delete,
6620                Keyword::TRUNCATE => TriggerEvent::Truncate,
6621                unexpected_keyword => return Err(ParserError::ParserError(
6622                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in trigger event"),
6623                )),
6624            },
6625        )
6626    }
6627
6628    /// Parse the `REFERENCING` clause of a trigger.
6629    pub fn parse_trigger_referencing(&mut self) -> Result<Option<TriggerReferencing>, ParserError> {
6630        let refer_type = match self.parse_one_of_keywords(&[Keyword::OLD, Keyword::NEW]) {
6631            Some(Keyword::OLD) if self.parse_keyword(Keyword::TABLE) => {
6632                TriggerReferencingType::OldTable
6633            }
6634            Some(Keyword::NEW) if self.parse_keyword(Keyword::TABLE) => {
6635                TriggerReferencingType::NewTable
6636            }
6637            _ => {
6638                return Ok(None);
6639            }
6640        };
6641
6642        let is_as = self.parse_keyword(Keyword::AS);
6643        let transition_relation_name = self.parse_object_name(false)?;
6644        Ok(Some(TriggerReferencing {
6645            refer_type,
6646            is_as,
6647            transition_relation_name,
6648        }))
6649    }
6650
6651    /// Parse the execution body of a trigger (`FUNCTION` or `PROCEDURE`).
6652    pub fn parse_trigger_exec_body(&mut self) -> Result<TriggerExecBody, ParserError> {
6653        Ok(TriggerExecBody {
6654            exec_type: match self
6655                .expect_one_of_keywords(&[Keyword::FUNCTION, Keyword::PROCEDURE])?
6656            {
6657                Keyword::FUNCTION => TriggerExecBodyType::Function,
6658                Keyword::PROCEDURE => TriggerExecBodyType::Procedure,
6659                unexpected_keyword => return Err(ParserError::ParserError(
6660                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in trigger exec body"),
6661                )),
6662            },
6663            func_desc: self.parse_function_desc()?,
6664        })
6665    }
6666
6667    /// Parse a `CREATE MACRO` statement.
6668    pub fn parse_create_macro(
6669        &mut self,
6670        or_replace: bool,
6671        temporary: bool,
6672    ) -> Result<Statement, ParserError> {
6673        if dialect_of!(self is DuckDbDialect |  GenericDialect) {
6674            let name = self.parse_object_name(false)?;
6675            self.expect_token(&Token::LParen)?;
6676            let args = if self.consume_token(&Token::RParen) {
6677                self.prev_token();
6678                None
6679            } else {
6680                Some(self.parse_comma_separated(Parser::parse_macro_arg)?)
6681            };
6682
6683            self.expect_token(&Token::RParen)?;
6684            self.expect_keyword_is(Keyword::AS)?;
6685
6686            Ok(Statement::CreateMacro {
6687                or_replace,
6688                temporary,
6689                name,
6690                args,
6691                definition: if self.parse_keyword(Keyword::TABLE) {
6692                    MacroDefinition::Table(self.parse_query()?)
6693                } else {
6694                    MacroDefinition::Expr(self.parse_expr()?)
6695                },
6696            })
6697        } else {
6698            self.prev_token();
6699            self.expected_ref("an object type after CREATE", self.peek_token_ref())
6700        }
6701    }
6702
6703    fn parse_macro_arg(&mut self) -> Result<MacroArg, ParserError> {
6704        let name = self.parse_identifier()?;
6705
6706        let default_expr =
6707            if self.consume_token(&Token::Assignment) || self.consume_token(&Token::RArrow) {
6708                Some(self.parse_expr()?)
6709            } else {
6710                None
6711            };
6712        Ok(MacroArg { name, default_expr })
6713    }
6714
6715    /// Parse a `CREATE EXTERNAL TABLE` statement.
6716    pub fn parse_create_external_table(
6717        &mut self,
6718        or_replace: bool,
6719    ) -> Result<CreateTable, ParserError> {
6720        self.expect_keyword_is(Keyword::TABLE)?;
6721        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
6722        let table_name = self.parse_object_name(false)?;
6723        let (columns, constraints) = self.parse_columns()?;
6724
6725        let hive_distribution = self.parse_hive_distribution()?;
6726        let hive_formats = self.parse_hive_formats()?;
6727
6728        let file_format = if let Some(ref hf) = hive_formats {
6729            if let Some(ref ff) = hf.storage {
6730                match ff {
6731                    HiveIOFormat::FileFormat { format } => Some(*format),
6732                    _ => None,
6733                }
6734            } else {
6735                None
6736            }
6737        } else {
6738            None
6739        };
6740        let location = hive_formats.as_ref().and_then(|hf| hf.location.clone());
6741
6742        let with_connection = if self.parse_keywords(&[Keyword::WITH, Keyword::CONNECTION]) {
6743            Some(self.parse_object_name(false)?)
6744        } else {
6745            None
6746        };
6747        let table_properties = self.parse_options(Keyword::TBLPROPERTIES)?;
6748        let table_options = if !table_properties.is_empty() {
6749            CreateTableOptions::TableProperties(table_properties)
6750        } else if let Some(options) = self.maybe_parse_options(Keyword::OPTIONS)? {
6751            CreateTableOptions::Options(options)
6752        } else {
6753            CreateTableOptions::None
6754        };
6755        Ok(CreateTableBuilder::new(table_name)
6756            .columns(columns)
6757            .constraints(constraints)
6758            .hive_distribution(hive_distribution)
6759            .hive_formats(hive_formats)
6760            .table_options(table_options)
6761            .with_connection(with_connection)
6762            .or_replace(or_replace)
6763            .if_not_exists(if_not_exists)
6764            .external(true)
6765            .file_format(file_format)
6766            .location(location)
6767            .build())
6768    }
6769
6770    /// Parse `CREATE SNAPSHOT TABLE` statement.
6771    ///
6772    /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_snapshot_table_statement>
6773    pub fn parse_create_snapshot_table(&mut self) -> Result<CreateTable, ParserError> {
6774        self.expect_keywords(&[Keyword::SNAPSHOT, Keyword::TABLE])?;
6775        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
6776        let table_name = self.parse_object_name(true)?;
6777
6778        self.expect_keyword_is(Keyword::CLONE)?;
6779        let clone = Some(self.parse_object_name(true)?);
6780
6781        let version =
6782            if self.parse_keywords(&[Keyword::FOR, Keyword::SYSTEM_TIME, Keyword::AS, Keyword::OF])
6783            {
6784                Some(TableVersion::ForSystemTimeAsOf(self.parse_expr()?))
6785            } else {
6786                None
6787            };
6788
6789        let table_options = if let Some(options) = self.maybe_parse_options(Keyword::OPTIONS)? {
6790            CreateTableOptions::Options(options)
6791        } else {
6792            CreateTableOptions::None
6793        };
6794
6795        Ok(CreateTableBuilder::new(table_name)
6796            .snapshot(true)
6797            .if_not_exists(if_not_exists)
6798            .clone_clause(clone)
6799            .version(version)
6800            .table_options(table_options)
6801            .build())
6802    }
6803
6804    /// Parse a file format for external tables.
6805    pub fn parse_file_format(&mut self) -> Result<FileFormat, ParserError> {
6806        let next_token = self.next_token();
6807        match &next_token.token {
6808            Token::Word(w) => match w.keyword {
6809                Keyword::AVRO => Ok(FileFormat::AVRO),
6810                Keyword::JSONFILE => Ok(FileFormat::JSONFILE),
6811                Keyword::ORC => Ok(FileFormat::ORC),
6812                Keyword::PARQUET => Ok(FileFormat::PARQUET),
6813                Keyword::RCFILE => Ok(FileFormat::RCFILE),
6814                Keyword::SEQUENCEFILE => Ok(FileFormat::SEQUENCEFILE),
6815                Keyword::TEXTFILE => Ok(FileFormat::TEXTFILE),
6816                _ => self.expected("fileformat", next_token),
6817            },
6818            _ => self.expected("fileformat", next_token),
6819        }
6820    }
6821
6822    fn parse_analyze_format_kind(&mut self) -> Result<AnalyzeFormatKind, ParserError> {
6823        if self.consume_token(&Token::Eq) {
6824            Ok(AnalyzeFormatKind::Assignment(self.parse_analyze_format()?))
6825        } else {
6826            Ok(AnalyzeFormatKind::Keyword(self.parse_analyze_format()?))
6827        }
6828    }
6829
6830    /// Parse an `ANALYZE FORMAT`.
6831    pub fn parse_analyze_format(&mut self) -> Result<AnalyzeFormat, ParserError> {
6832        let next_token = self.next_token();
6833        match &next_token.token {
6834            Token::Word(w) => match w.keyword {
6835                Keyword::TEXT => Ok(AnalyzeFormat::TEXT),
6836                Keyword::GRAPHVIZ => Ok(AnalyzeFormat::GRAPHVIZ),
6837                Keyword::JSON => Ok(AnalyzeFormat::JSON),
6838                Keyword::TREE => Ok(AnalyzeFormat::TREE),
6839                _ => self.expected("fileformat", next_token),
6840            },
6841            _ => self.expected("fileformat", next_token),
6842        }
6843    }
6844
6845    /// Parse a `CREATE VIEW` statement.
6846    pub fn parse_create_view(
6847        &mut self,
6848        or_alter: bool,
6849        or_replace: bool,
6850        temporary: bool,
6851        create_view_params: Option<CreateViewParams>,
6852    ) -> Result<CreateView, ParserError> {
6853        let secure = self.parse_keyword(Keyword::SECURE);
6854        let materialized = self.parse_keyword(Keyword::MATERIALIZED);
6855        self.expect_keyword_is(Keyword::VIEW)?;
6856        let allow_unquoted_hyphen = dialect_of!(self is BigQueryDialect);
6857        // Tries to parse IF NOT EXISTS either before name or after name
6858        // Name before IF NOT EXISTS is supported by snowflake but undocumented
6859        let if_not_exists_first =
6860            self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
6861        let name = self.parse_object_name(allow_unquoted_hyphen)?;
6862        let name_before_not_exists = !if_not_exists_first
6863            && self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
6864        let if_not_exists = if_not_exists_first || name_before_not_exists;
6865        let mut copy_grants = self.parse_keywords(&[Keyword::COPY, Keyword::GRANTS]);
6866        // Many dialects support `OR ALTER` right after `CREATE`, but we don't (yet).
6867        // ANSI SQL and Postgres support RECURSIVE here, but we don't support it either.
6868        let columns = self.parse_view_columns()?;
6869        // Snowflake also documents `COPY GRANTS` *after* the column list; accept
6870        // either position, but not both.
6871        // <https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax>
6872        if !copy_grants {
6873            copy_grants = self.parse_keywords(&[Keyword::COPY, Keyword::GRANTS]);
6874        }
6875        let mut options = CreateTableOptions::None;
6876        let with_options = self.parse_options(Keyword::WITH)?;
6877        if !with_options.is_empty() {
6878            options = CreateTableOptions::With(with_options);
6879        }
6880
6881        let cluster_by = if self.parse_keyword(Keyword::CLUSTER) {
6882            self.expect_keyword_is(Keyword::BY)?;
6883            self.parse_parenthesized_column_list(Optional, false)?
6884        } else {
6885            vec![]
6886        };
6887
6888        if dialect_of!(self is BigQueryDialect | GenericDialect) {
6889            if let Some(opts) = self.maybe_parse_options(Keyword::OPTIONS)? {
6890                if !opts.is_empty() {
6891                    options = CreateTableOptions::Options(opts);
6892                }
6893            };
6894        }
6895
6896        let to = if dialect_of!(self is ClickHouseDialect | GenericDialect)
6897            && self.parse_keyword(Keyword::TO)
6898        {
6899            Some(self.parse_object_name(false)?)
6900        } else {
6901            None
6902        };
6903
6904        let comment = if self.dialect.supports_create_view_comment_syntax()
6905            && self.parse_keyword(Keyword::COMMENT)
6906        {
6907            self.expect_token(&Token::Eq)?;
6908            Some(self.parse_comment_value()?)
6909        } else {
6910            None
6911        };
6912
6913        self.expect_keyword_is(Keyword::AS)?;
6914        let query = self.parse_query()?;
6915        // Optional `WITH [ CASCADED | LOCAL ] CHECK OPTION` is widely supported here.
6916
6917        let with_no_schema_binding = dialect_of!(self is RedshiftSqlDialect | GenericDialect)
6918            && self.parse_keywords(&[
6919                Keyword::WITH,
6920                Keyword::NO,
6921                Keyword::SCHEMA,
6922                Keyword::BINDING,
6923            ]);
6924
6925        Ok(CreateView {
6926            or_alter,
6927            name,
6928            columns,
6929            query,
6930            materialized,
6931            secure,
6932            or_replace,
6933            options,
6934            cluster_by,
6935            comment,
6936            with_no_schema_binding,
6937            if_not_exists,
6938            temporary,
6939            copy_grants,
6940            to,
6941            params: create_view_params,
6942            name_before_not_exists,
6943        })
6944    }
6945
6946    /// Parse optional parameters for the `CREATE VIEW` statement supported by [MySQL].
6947    ///
6948    /// [MySQL]: https://dev.mysql.com/doc/refman/9.1/en/create-view.html
6949    fn parse_create_view_params(&mut self) -> Result<Option<CreateViewParams>, ParserError> {
6950        let algorithm = if self.parse_keyword(Keyword::ALGORITHM) {
6951            self.expect_token(&Token::Eq)?;
6952            Some(
6953                match self.expect_one_of_keywords(&[
6954                    Keyword::UNDEFINED,
6955                    Keyword::MERGE,
6956                    Keyword::TEMPTABLE,
6957                ])? {
6958                    Keyword::UNDEFINED => CreateViewAlgorithm::Undefined,
6959                    Keyword::MERGE => CreateViewAlgorithm::Merge,
6960                    Keyword::TEMPTABLE => CreateViewAlgorithm::TempTable,
6961                    _ => {
6962                        self.prev_token();
6963                        let found = self.next_token();
6964                        return self
6965                            .expected("UNDEFINED or MERGE or TEMPTABLE after ALGORITHM =", found);
6966                    }
6967                },
6968            )
6969        } else {
6970            None
6971        };
6972        let definer = if self.parse_keyword(Keyword::DEFINER) {
6973            self.expect_token(&Token::Eq)?;
6974            Some(self.parse_grantee_name()?)
6975        } else {
6976            None
6977        };
6978        let security = if self.parse_keywords(&[Keyword::SQL, Keyword::SECURITY]) {
6979            Some(
6980                match self.expect_one_of_keywords(&[Keyword::DEFINER, Keyword::INVOKER])? {
6981                    Keyword::DEFINER => CreateViewSecurity::Definer,
6982                    Keyword::INVOKER => CreateViewSecurity::Invoker,
6983                    _ => {
6984                        self.prev_token();
6985                        let found = self.next_token();
6986                        return self.expected("DEFINER or INVOKER after SQL SECURITY", found);
6987                    }
6988                },
6989            )
6990        } else {
6991            None
6992        };
6993        if algorithm.is_some() || definer.is_some() || security.is_some() {
6994            Ok(Some(CreateViewParams {
6995                algorithm,
6996                definer,
6997                security,
6998            }))
6999        } else {
7000            Ok(None)
7001        }
7002    }
7003
7004    /// Parse a `CREATE ROLE` statement.
7005    pub fn parse_create_role(&mut self) -> Result<CreateRole, ParserError> {
7006        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
7007        let names = self.parse_comma_separated(|p| p.parse_object_name(false))?;
7008
7009        let _ = self.parse_keyword(Keyword::WITH); // [ WITH ]
7010
7011        let optional_keywords = if dialect_of!(self is MsSqlDialect) {
7012            vec![Keyword::AUTHORIZATION]
7013        } else if dialect_of!(self is PostgreSqlDialect) {
7014            vec![
7015                Keyword::LOGIN,
7016                Keyword::NOLOGIN,
7017                Keyword::INHERIT,
7018                Keyword::NOINHERIT,
7019                Keyword::BYPASSRLS,
7020                Keyword::NOBYPASSRLS,
7021                Keyword::PASSWORD,
7022                Keyword::CREATEDB,
7023                Keyword::NOCREATEDB,
7024                Keyword::CREATEROLE,
7025                Keyword::NOCREATEROLE,
7026                Keyword::SUPERUSER,
7027                Keyword::NOSUPERUSER,
7028                Keyword::REPLICATION,
7029                Keyword::NOREPLICATION,
7030                Keyword::CONNECTION,
7031                Keyword::VALID,
7032                Keyword::IN,
7033                Keyword::ROLE,
7034                Keyword::ADMIN,
7035                Keyword::USER,
7036            ]
7037        } else {
7038            vec![]
7039        };
7040
7041        // MSSQL
7042        let mut authorization_owner = None;
7043        // Postgres
7044        let mut login = None;
7045        let mut inherit = None;
7046        let mut bypassrls = None;
7047        let mut password = None;
7048        let mut create_db = None;
7049        let mut create_role = None;
7050        let mut superuser = None;
7051        let mut replication = None;
7052        let mut connection_limit = None;
7053        let mut valid_until = None;
7054        let mut in_role = vec![];
7055        let mut in_group = vec![];
7056        let mut role = vec![];
7057        let mut user = vec![];
7058        let mut admin = vec![];
7059
7060        while let Some(keyword) = self.parse_one_of_keywords(&optional_keywords) {
7061            let loc = self
7062                .tokens
7063                .get(self.index - 1)
7064                .map_or(Location { line: 0, column: 0 }, |t| t.span.start);
7065            match keyword {
7066                Keyword::AUTHORIZATION => {
7067                    if authorization_owner.is_some() {
7068                        parser_err!("Found multiple AUTHORIZATION", loc)
7069                    } else {
7070                        authorization_owner = Some(self.parse_object_name(false)?);
7071                        Ok(())
7072                    }
7073                }
7074                Keyword::LOGIN | Keyword::NOLOGIN => {
7075                    if login.is_some() {
7076                        parser_err!("Found multiple LOGIN or NOLOGIN", loc)
7077                    } else {
7078                        login = Some(keyword == Keyword::LOGIN);
7079                        Ok(())
7080                    }
7081                }
7082                Keyword::INHERIT | Keyword::NOINHERIT => {
7083                    if inherit.is_some() {
7084                        parser_err!("Found multiple INHERIT or NOINHERIT", loc)
7085                    } else {
7086                        inherit = Some(keyword == Keyword::INHERIT);
7087                        Ok(())
7088                    }
7089                }
7090                Keyword::BYPASSRLS | Keyword::NOBYPASSRLS => {
7091                    if bypassrls.is_some() {
7092                        parser_err!("Found multiple BYPASSRLS or NOBYPASSRLS", loc)
7093                    } else {
7094                        bypassrls = Some(keyword == Keyword::BYPASSRLS);
7095                        Ok(())
7096                    }
7097                }
7098                Keyword::CREATEDB | Keyword::NOCREATEDB => {
7099                    if create_db.is_some() {
7100                        parser_err!("Found multiple CREATEDB or NOCREATEDB", loc)
7101                    } else {
7102                        create_db = Some(keyword == Keyword::CREATEDB);
7103                        Ok(())
7104                    }
7105                }
7106                Keyword::CREATEROLE | Keyword::NOCREATEROLE => {
7107                    if create_role.is_some() {
7108                        parser_err!("Found multiple CREATEROLE or NOCREATEROLE", loc)
7109                    } else {
7110                        create_role = Some(keyword == Keyword::CREATEROLE);
7111                        Ok(())
7112                    }
7113                }
7114                Keyword::SUPERUSER | Keyword::NOSUPERUSER => {
7115                    if superuser.is_some() {
7116                        parser_err!("Found multiple SUPERUSER or NOSUPERUSER", loc)
7117                    } else {
7118                        superuser = Some(keyword == Keyword::SUPERUSER);
7119                        Ok(())
7120                    }
7121                }
7122                Keyword::REPLICATION | Keyword::NOREPLICATION => {
7123                    if replication.is_some() {
7124                        parser_err!("Found multiple REPLICATION or NOREPLICATION", loc)
7125                    } else {
7126                        replication = Some(keyword == Keyword::REPLICATION);
7127                        Ok(())
7128                    }
7129                }
7130                Keyword::PASSWORD => {
7131                    if password.is_some() {
7132                        parser_err!("Found multiple PASSWORD", loc)
7133                    } else {
7134                        password = if self.parse_keyword(Keyword::NULL) {
7135                            Some(Password::NullPassword)
7136                        } else {
7137                            Some(Password::Password(Expr::Value(self.parse_value()?)))
7138                        };
7139                        Ok(())
7140                    }
7141                }
7142                Keyword::CONNECTION => {
7143                    self.expect_keyword_is(Keyword::LIMIT)?;
7144                    if connection_limit.is_some() {
7145                        parser_err!("Found multiple CONNECTION LIMIT", loc)
7146                    } else {
7147                        connection_limit = Some(Expr::Value(self.parse_number_value()?));
7148                        Ok(())
7149                    }
7150                }
7151                Keyword::VALID => {
7152                    self.expect_keyword_is(Keyword::UNTIL)?;
7153                    if valid_until.is_some() {
7154                        parser_err!("Found multiple VALID UNTIL", loc)
7155                    } else {
7156                        valid_until = Some(Expr::Value(self.parse_value()?));
7157                        Ok(())
7158                    }
7159                }
7160                Keyword::IN => {
7161                    if self.parse_keyword(Keyword::ROLE) {
7162                        if !in_role.is_empty() {
7163                            parser_err!("Found multiple IN ROLE", loc)
7164                        } else {
7165                            in_role = self.parse_comma_separated(|p| p.parse_identifier())?;
7166                            Ok(())
7167                        }
7168                    } else if self.parse_keyword(Keyword::GROUP) {
7169                        if !in_group.is_empty() {
7170                            parser_err!("Found multiple IN GROUP", loc)
7171                        } else {
7172                            in_group = self.parse_comma_separated(|p| p.parse_identifier())?;
7173                            Ok(())
7174                        }
7175                    } else {
7176                        self.expected_ref("ROLE or GROUP after IN", self.peek_token_ref())
7177                    }
7178                }
7179                Keyword::ROLE => {
7180                    if !role.is_empty() {
7181                        parser_err!("Found multiple ROLE", loc)
7182                    } else {
7183                        role = self.parse_comma_separated(|p| p.parse_identifier())?;
7184                        Ok(())
7185                    }
7186                }
7187                Keyword::USER => {
7188                    if !user.is_empty() {
7189                        parser_err!("Found multiple USER", loc)
7190                    } else {
7191                        user = self.parse_comma_separated(|p| p.parse_identifier())?;
7192                        Ok(())
7193                    }
7194                }
7195                Keyword::ADMIN => {
7196                    if !admin.is_empty() {
7197                        parser_err!("Found multiple ADMIN", loc)
7198                    } else {
7199                        admin = self.parse_comma_separated(|p| p.parse_identifier())?;
7200                        Ok(())
7201                    }
7202                }
7203                _ => break,
7204            }?
7205        }
7206
7207        Ok(CreateRole {
7208            names,
7209            if_not_exists,
7210            login,
7211            inherit,
7212            bypassrls,
7213            password,
7214            create_db,
7215            create_role,
7216            replication,
7217            superuser,
7218            connection_limit,
7219            valid_until,
7220            in_role,
7221            in_group,
7222            role,
7223            user,
7224            admin,
7225            authorization_owner,
7226        })
7227    }
7228
7229    /// Parse an `OWNER` clause.
7230    pub fn parse_owner(&mut self) -> Result<Owner, ParserError> {
7231        let owner = match self.parse_one_of_keywords(&[Keyword::CURRENT_USER, Keyword::CURRENT_ROLE, Keyword::SESSION_USER]) {
7232            Some(Keyword::CURRENT_USER) => Owner::CurrentUser,
7233            Some(Keyword::CURRENT_ROLE) => Owner::CurrentRole,
7234            Some(Keyword::SESSION_USER) => Owner::SessionUser,
7235            Some(unexpected_keyword) => return Err(ParserError::ParserError(
7236                format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in owner"),
7237            )),
7238            None => {
7239                match self.parse_identifier() {
7240                    Ok(ident) => Owner::Ident(ident),
7241                    Err(e) => {
7242                        return Err(ParserError::ParserError(format!("Expected: CURRENT_USER, CURRENT_ROLE, SESSION_USER or identifier after OWNER TO. {e}")))
7243                    }
7244                }
7245            }
7246        };
7247        Ok(owner)
7248    }
7249
7250    /// Parses a [Statement::CreateDomain] statement.
7251    fn parse_create_domain(&mut self) -> Result<CreateDomain, ParserError> {
7252        let name = self.parse_object_name(false)?;
7253        self.expect_keyword_is(Keyword::AS)?;
7254        let data_type = self.parse_data_type()?;
7255        let collation = if self.parse_keyword(Keyword::COLLATE) {
7256            Some(self.parse_identifier()?)
7257        } else {
7258            None
7259        };
7260        let default = if self.parse_keyword(Keyword::DEFAULT) {
7261            Some(self.parse_expr()?)
7262        } else {
7263            None
7264        };
7265        let mut constraints = Vec::new();
7266        while let Some(constraint) = self.parse_optional_table_constraint()? {
7267            constraints.push(constraint);
7268        }
7269
7270        Ok(CreateDomain {
7271            name,
7272            data_type,
7273            collation,
7274            default,
7275            constraints,
7276        })
7277    }
7278
7279    /// ```sql
7280    ///     CREATE POLICY name ON table_name [ AS { PERMISSIVE | RESTRICTIVE } ]
7281    ///     [ FOR { ALL | SELECT | INSERT | UPDATE | DELETE } ]
7282    ///     [ TO { role_name | PUBLIC | CURRENT_USER | CURRENT_ROLE | SESSION_USER } [, ...] ]
7283    ///     [ USING ( using_expression ) ]
7284    ///     [ WITH CHECK ( with_check_expression ) ]
7285    /// ```
7286    ///
7287    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-createpolicy.html)
7288    pub fn parse_create_policy(&mut self) -> Result<CreatePolicy, ParserError> {
7289        let name = self.parse_identifier()?;
7290        self.expect_keyword_is(Keyword::ON)?;
7291        let table_name = self.parse_object_name(false)?;
7292
7293        let policy_type = if self.parse_keyword(Keyword::AS) {
7294            let keyword =
7295                self.expect_one_of_keywords(&[Keyword::PERMISSIVE, Keyword::RESTRICTIVE])?;
7296            Some(match keyword {
7297                Keyword::PERMISSIVE => CreatePolicyType::Permissive,
7298                Keyword::RESTRICTIVE => CreatePolicyType::Restrictive,
7299                unexpected_keyword => return Err(ParserError::ParserError(
7300                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in policy type"),
7301                )),
7302            })
7303        } else {
7304            None
7305        };
7306
7307        let command = if self.parse_keyword(Keyword::FOR) {
7308            let keyword = self.expect_one_of_keywords(&[
7309                Keyword::ALL,
7310                Keyword::SELECT,
7311                Keyword::INSERT,
7312                Keyword::UPDATE,
7313                Keyword::DELETE,
7314            ])?;
7315            Some(match keyword {
7316                Keyword::ALL => CreatePolicyCommand::All,
7317                Keyword::SELECT => CreatePolicyCommand::Select,
7318                Keyword::INSERT => CreatePolicyCommand::Insert,
7319                Keyword::UPDATE => CreatePolicyCommand::Update,
7320                Keyword::DELETE => CreatePolicyCommand::Delete,
7321                unexpected_keyword => return Err(ParserError::ParserError(
7322                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in policy command"),
7323                )),
7324            })
7325        } else {
7326            None
7327        };
7328
7329        let to = if self.parse_keyword(Keyword::TO) {
7330            Some(self.parse_comma_separated(|p| p.parse_owner())?)
7331        } else {
7332            None
7333        };
7334
7335        let using = if self.parse_keyword(Keyword::USING) {
7336            self.expect_token(&Token::LParen)?;
7337            let expr = self.parse_expr()?;
7338            self.expect_token(&Token::RParen)?;
7339            Some(expr)
7340        } else {
7341            None
7342        };
7343
7344        let with_check = if self.parse_keywords(&[Keyword::WITH, Keyword::CHECK]) {
7345            self.expect_token(&Token::LParen)?;
7346            let expr = self.parse_expr()?;
7347            self.expect_token(&Token::RParen)?;
7348            Some(expr)
7349        } else {
7350            None
7351        };
7352
7353        Ok(CreatePolicy {
7354            name,
7355            table_name,
7356            policy_type,
7357            command,
7358            to,
7359            using,
7360            with_check,
7361        })
7362    }
7363
7364    /// ```sql
7365    /// CREATE CONNECTOR [IF NOT EXISTS] connector_name
7366    /// [TYPE datasource_type]
7367    /// [URL datasource_url]
7368    /// [COMMENT connector_comment]
7369    /// [WITH DCPROPERTIES(property_name=property_value, ...)]
7370    /// ```
7371    ///
7372    /// [Hive Documentation](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27362034#LanguageManualDDL-CreateDataConnectorCreateConnector)
7373    pub fn parse_create_connector(&mut self) -> Result<CreateConnector, ParserError> {
7374        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
7375        let name = self.parse_identifier()?;
7376
7377        let connector_type = if self.parse_keyword(Keyword::TYPE) {
7378            Some(self.parse_literal_string()?)
7379        } else {
7380            None
7381        };
7382
7383        let url = if self.parse_keyword(Keyword::URL) {
7384            Some(self.parse_literal_string()?)
7385        } else {
7386            None
7387        };
7388
7389        let comment = self.parse_optional_inline_comment()?;
7390
7391        let with_dcproperties =
7392            match self.parse_options_with_keywords(&[Keyword::WITH, Keyword::DCPROPERTIES])? {
7393                properties if !properties.is_empty() => Some(properties),
7394                _ => None,
7395            };
7396
7397        Ok(CreateConnector {
7398            name,
7399            if_not_exists,
7400            connector_type,
7401            url,
7402            comment,
7403            with_dcproperties,
7404        })
7405    }
7406
7407    /// Parse an operator name, which can contain special characters like +, -, <, >, =
7408    /// that are tokenized as operator tokens rather than identifiers.
7409    /// This is used for PostgreSQL CREATE OPERATOR statements.
7410    ///
7411    /// Examples: `+`, `myschema.+`, `pg_catalog.<=`
7412    fn parse_operator_name(&mut self) -> Result<ObjectName, ParserError> {
7413        let mut parts = vec![];
7414        loop {
7415            parts.push(ObjectNamePart::Identifier(Ident::new(
7416                self.next_token().to_string(),
7417            )));
7418            if !self.consume_token(&Token::Period) {
7419                break;
7420            }
7421        }
7422        Ok(ObjectName(parts))
7423    }
7424
7425    /// Parse a [Statement::CreateOperator]
7426    ///
7427    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-createoperator.html)
7428    pub fn parse_create_operator(&mut self) -> Result<CreateOperator, ParserError> {
7429        let name = self.parse_operator_name()?;
7430        self.expect_token(&Token::LParen)?;
7431
7432        let mut function: Option<ObjectName> = None;
7433        let mut is_procedure = false;
7434        let mut left_arg: Option<DataType> = None;
7435        let mut right_arg: Option<DataType> = None;
7436        let mut options: Vec<OperatorOption> = Vec::new();
7437
7438        loop {
7439            let keyword = self.expect_one_of_keywords(&[
7440                Keyword::FUNCTION,
7441                Keyword::PROCEDURE,
7442                Keyword::LEFTARG,
7443                Keyword::RIGHTARG,
7444                Keyword::COMMUTATOR,
7445                Keyword::NEGATOR,
7446                Keyword::RESTRICT,
7447                Keyword::JOIN,
7448                Keyword::HASHES,
7449                Keyword::MERGES,
7450            ])?;
7451
7452            match keyword {
7453                Keyword::HASHES if !options.iter().any(|o| matches!(o, OperatorOption::Hashes)) => {
7454                    options.push(OperatorOption::Hashes);
7455                }
7456                Keyword::MERGES if !options.iter().any(|o| matches!(o, OperatorOption::Merges)) => {
7457                    options.push(OperatorOption::Merges);
7458                }
7459                Keyword::FUNCTION | Keyword::PROCEDURE if function.is_none() => {
7460                    self.expect_token(&Token::Eq)?;
7461                    function = Some(self.parse_object_name(false)?);
7462                    is_procedure = keyword == Keyword::PROCEDURE;
7463                }
7464                Keyword::LEFTARG if left_arg.is_none() => {
7465                    self.expect_token(&Token::Eq)?;
7466                    left_arg = Some(self.parse_data_type()?);
7467                }
7468                Keyword::RIGHTARG if right_arg.is_none() => {
7469                    self.expect_token(&Token::Eq)?;
7470                    right_arg = Some(self.parse_data_type()?);
7471                }
7472                Keyword::COMMUTATOR
7473                    if !options
7474                        .iter()
7475                        .any(|o| matches!(o, OperatorOption::Commutator(_))) =>
7476                {
7477                    self.expect_token(&Token::Eq)?;
7478                    if self.parse_keyword(Keyword::OPERATOR) {
7479                        self.expect_token(&Token::LParen)?;
7480                        let op = self.parse_operator_name()?;
7481                        self.expect_token(&Token::RParen)?;
7482                        options.push(OperatorOption::Commutator(op));
7483                    } else {
7484                        options.push(OperatorOption::Commutator(self.parse_operator_name()?));
7485                    }
7486                }
7487                Keyword::NEGATOR
7488                    if !options
7489                        .iter()
7490                        .any(|o| matches!(o, OperatorOption::Negator(_))) =>
7491                {
7492                    self.expect_token(&Token::Eq)?;
7493                    if self.parse_keyword(Keyword::OPERATOR) {
7494                        self.expect_token(&Token::LParen)?;
7495                        let op = self.parse_operator_name()?;
7496                        self.expect_token(&Token::RParen)?;
7497                        options.push(OperatorOption::Negator(op));
7498                    } else {
7499                        options.push(OperatorOption::Negator(self.parse_operator_name()?));
7500                    }
7501                }
7502                Keyword::RESTRICT
7503                    if !options
7504                        .iter()
7505                        .any(|o| matches!(o, OperatorOption::Restrict(_))) =>
7506                {
7507                    self.expect_token(&Token::Eq)?;
7508                    options.push(OperatorOption::Restrict(Some(
7509                        self.parse_object_name(false)?,
7510                    )));
7511                }
7512                Keyword::JOIN if !options.iter().any(|o| matches!(o, OperatorOption::Join(_))) => {
7513                    self.expect_token(&Token::Eq)?;
7514                    options.push(OperatorOption::Join(Some(self.parse_object_name(false)?)));
7515                }
7516                _ => {
7517                    return Err(ParserError::ParserError(format!(
7518                        "Duplicate or unexpected keyword {:?} in CREATE OPERATOR",
7519                        keyword
7520                    )))
7521                }
7522            }
7523
7524            if !self.consume_token(&Token::Comma) {
7525                break;
7526            }
7527        }
7528
7529        // Expect closing parenthesis
7530        self.expect_token(&Token::RParen)?;
7531
7532        // FUNCTION is required
7533        let function = function.ok_or_else(|| {
7534            ParserError::ParserError("CREATE OPERATOR requires FUNCTION parameter".to_string())
7535        })?;
7536
7537        Ok(CreateOperator {
7538            name,
7539            function,
7540            is_procedure,
7541            left_arg,
7542            right_arg,
7543            options,
7544        })
7545    }
7546
7547    /// Parse a [Statement::CreateOperatorFamily]
7548    ///
7549    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-createopfamily.html)
7550    pub fn parse_create_operator_family(&mut self) -> Result<CreateOperatorFamily, ParserError> {
7551        let name = self.parse_object_name(false)?;
7552        self.expect_keyword(Keyword::USING)?;
7553        let using = self.parse_identifier()?;
7554
7555        Ok(CreateOperatorFamily { name, using })
7556    }
7557
7558    /// Parse a [Statement::CreateOperatorClass]
7559    ///
7560    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-createopclass.html)
7561    pub fn parse_create_operator_class(&mut self) -> Result<CreateOperatorClass, ParserError> {
7562        let name = self.parse_object_name(false)?;
7563        let default = self.parse_keyword(Keyword::DEFAULT);
7564        self.expect_keywords(&[Keyword::FOR, Keyword::TYPE])?;
7565        let for_type = self.parse_data_type()?;
7566        self.expect_keyword(Keyword::USING)?;
7567        let using = self.parse_identifier()?;
7568
7569        let family = if self.parse_keyword(Keyword::FAMILY) {
7570            Some(self.parse_object_name(false)?)
7571        } else {
7572            None
7573        };
7574
7575        self.expect_keyword(Keyword::AS)?;
7576
7577        let mut items = vec![];
7578        loop {
7579            if self.parse_keyword(Keyword::OPERATOR) {
7580                let strategy_number = self.parse_literal_uint()?;
7581                let operator_name = self.parse_operator_name()?;
7582
7583                // Optional operator argument types
7584                let op_types = if self.consume_token(&Token::LParen) {
7585                    let left = self.parse_data_type()?;
7586                    self.expect_token(&Token::Comma)?;
7587                    let right = self.parse_data_type()?;
7588                    self.expect_token(&Token::RParen)?;
7589                    Some(OperatorArgTypes { left, right })
7590                } else {
7591                    None
7592                };
7593
7594                // Optional purpose
7595                let purpose = if self.parse_keyword(Keyword::FOR) {
7596                    if self.parse_keyword(Keyword::SEARCH) {
7597                        Some(OperatorPurpose::ForSearch)
7598                    } else if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
7599                        let sort_family = self.parse_object_name(false)?;
7600                        Some(OperatorPurpose::ForOrderBy { sort_family })
7601                    } else {
7602                        return self
7603                            .expected_ref("SEARCH or ORDER BY after FOR", self.peek_token_ref());
7604                    }
7605                } else {
7606                    None
7607                };
7608
7609                items.push(OperatorClassItem::Operator {
7610                    strategy_number,
7611                    operator_name,
7612                    op_types,
7613                    purpose,
7614                });
7615            } else if self.parse_keyword(Keyword::FUNCTION) {
7616                let support_number = self.parse_literal_uint()?;
7617
7618                // Optional operator types
7619                let op_types = if self.consume_token(&Token::LParen)
7620                    && self.peek_token_ref().token != Token::RParen
7621                {
7622                    let mut types = vec![];
7623                    loop {
7624                        types.push(self.parse_data_type()?);
7625                        if !self.consume_token(&Token::Comma) {
7626                            break;
7627                        }
7628                    }
7629                    self.expect_token(&Token::RParen)?;
7630                    Some(types)
7631                } else if self.consume_token(&Token::LParen) {
7632                    self.expect_token(&Token::RParen)?;
7633                    Some(vec![])
7634                } else {
7635                    None
7636                };
7637
7638                let function_name = self.parse_object_name(false)?;
7639
7640                // Function argument types
7641                let argument_types = if self.consume_token(&Token::LParen) {
7642                    let mut types = vec![];
7643                    loop {
7644                        if self.peek_token_ref().token == Token::RParen {
7645                            break;
7646                        }
7647                        types.push(self.parse_data_type()?);
7648                        if !self.consume_token(&Token::Comma) {
7649                            break;
7650                        }
7651                    }
7652                    self.expect_token(&Token::RParen)?;
7653                    types
7654                } else {
7655                    vec![]
7656                };
7657
7658                items.push(OperatorClassItem::Function {
7659                    support_number,
7660                    op_types,
7661                    function_name,
7662                    argument_types,
7663                });
7664            } else if self.parse_keyword(Keyword::STORAGE) {
7665                let storage_type = self.parse_data_type()?;
7666                items.push(OperatorClassItem::Storage { storage_type });
7667            } else {
7668                break;
7669            }
7670
7671            // Check for comma separator
7672            if !self.consume_token(&Token::Comma) {
7673                break;
7674            }
7675        }
7676
7677        Ok(CreateOperatorClass {
7678            name,
7679            default,
7680            for_type,
7681            using,
7682            family,
7683            items,
7684        })
7685    }
7686
7687    /// Parse a `DROP` statement.
7688    pub fn parse_drop(&mut self) -> Result<Statement, ParserError> {
7689        // MySQL dialect supports `TEMPORARY`
7690        let temporary = dialect_of!(self is MySqlDialect | GenericDialect | DuckDbDialect)
7691            && self.parse_keyword(Keyword::TEMPORARY);
7692        let persistent = dialect_of!(self is DuckDbDialect)
7693            && self.parse_one_of_keywords(&[Keyword::PERSISTENT]).is_some();
7694
7695        let object_type = if self.parse_keyword(Keyword::TABLE) {
7696            ObjectType::Table
7697        } else if self.parse_keyword(Keyword::COLLATION) {
7698            ObjectType::Collation
7699        } else if self.parse_keyword(Keyword::VIEW) {
7700            ObjectType::View
7701        } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEW]) {
7702            ObjectType::MaterializedView
7703        } else if self.parse_keyword(Keyword::INDEX) {
7704            ObjectType::Index
7705        } else if self.parse_keyword(Keyword::ROLE) {
7706            ObjectType::Role
7707        } else if self.parse_keyword(Keyword::SCHEMA) {
7708            ObjectType::Schema
7709        } else if self.parse_keyword(Keyword::DATABASE) {
7710            ObjectType::Database
7711        } else if self.parse_keyword(Keyword::SEQUENCE) {
7712            ObjectType::Sequence
7713        } else if self.parse_keyword(Keyword::STAGE) {
7714            ObjectType::Stage
7715        } else if self.parse_keyword(Keyword::TYPE) {
7716            ObjectType::Type
7717        } else if self.parse_keyword(Keyword::USER) {
7718            ObjectType::User
7719        } else if self.parse_keyword(Keyword::STREAM) {
7720            ObjectType::Stream
7721        } else if self.parse_keyword(Keyword::WAREHOUSE) {
7722            ObjectType::Warehouse
7723        } else if self.parse_keyword(Keyword::FUNCTION) {
7724            return self.parse_drop_function().map(Into::into);
7725        } else if self.parse_keyword(Keyword::POLICY) {
7726            return self.parse_drop_policy().map(Into::into);
7727        } else if self.parse_keyword(Keyword::CONNECTOR) {
7728            return self.parse_drop_connector();
7729        } else if self.parse_keyword(Keyword::DOMAIN) {
7730            return self.parse_drop_domain().map(Into::into);
7731        } else if self.parse_keyword(Keyword::PROCEDURE) {
7732            return self.parse_drop_procedure();
7733        } else if self.parse_keyword(Keyword::SECRET) {
7734            return self.parse_drop_secret(temporary, persistent);
7735        } else if self.parse_keyword(Keyword::TRIGGER) {
7736            return self.parse_drop_trigger().map(Into::into);
7737        } else if self.parse_keyword(Keyword::EXTENSION) {
7738            return self.parse_drop_extension();
7739        } else if self.parse_keyword(Keyword::OPERATOR) {
7740            // Check if this is DROP OPERATOR FAMILY or DROP OPERATOR CLASS
7741            return if self.parse_keyword(Keyword::FAMILY) {
7742                self.parse_drop_operator_family()
7743            } else if self.parse_keyword(Keyword::CLASS) {
7744                self.parse_drop_operator_class()
7745            } else {
7746                self.parse_drop_operator()
7747            };
7748        } else {
7749            return self.expected_ref(
7750                "COLLATION, CONNECTOR, DATABASE, EXTENSION, FUNCTION, INDEX, OPERATOR, POLICY, PROCEDURE, ROLE, SCHEMA, SECRET, SEQUENCE, STAGE, TABLE, TRIGGER, TYPE, VIEW, MATERIALIZED VIEW, USER or WAREHOUSE after DROP",
7751                self.peek_token_ref(),
7752            );
7753        };
7754        // Many dialects support the non-standard `IF EXISTS` clause and allow
7755        // specifying multiple objects to delete in a single statement
7756        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7757        let names = self.parse_comma_separated(|p| p.parse_object_name(false))?;
7758
7759        let loc = self.peek_token_ref().span.start;
7760        let cascade = self.parse_keyword(Keyword::CASCADE);
7761        let restrict = self.parse_keyword(Keyword::RESTRICT);
7762        let purge = self.parse_keyword(Keyword::PURGE);
7763        if cascade && restrict {
7764            return parser_err!("Cannot specify both CASCADE and RESTRICT in DROP", loc);
7765        }
7766        if object_type == ObjectType::Role && (cascade || restrict || purge) {
7767            return parser_err!(
7768                "Cannot specify CASCADE, RESTRICT, or PURGE in DROP ROLE",
7769                loc
7770            );
7771        }
7772        let table = if self.parse_keyword(Keyword::ON) {
7773            Some(self.parse_object_name(false)?)
7774        } else {
7775            None
7776        };
7777        Ok(Statement::Drop {
7778            object_type,
7779            if_exists,
7780            names,
7781            cascade,
7782            restrict,
7783            purge,
7784            temporary,
7785            table,
7786        })
7787    }
7788
7789    fn parse_optional_drop_behavior(&mut self) -> Option<DropBehavior> {
7790        match self.parse_one_of_keywords(&[Keyword::CASCADE, Keyword::RESTRICT]) {
7791            Some(Keyword::CASCADE) => Some(DropBehavior::Cascade),
7792            Some(Keyword::RESTRICT) => Some(DropBehavior::Restrict),
7793            _ => None,
7794        }
7795    }
7796
7797    /// ```sql
7798    /// DROP FUNCTION [ IF EXISTS ] name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ] [, ...]
7799    /// [ CASCADE | RESTRICT ]
7800    /// ```
7801    fn parse_drop_function(&mut self) -> Result<DropFunction, ParserError> {
7802        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7803        let func_desc = self.parse_comma_separated(Parser::parse_function_desc)?;
7804        let drop_behavior = self.parse_optional_drop_behavior();
7805        Ok(DropFunction {
7806            if_exists,
7807            func_desc,
7808            drop_behavior,
7809        })
7810    }
7811
7812    /// ```sql
7813    /// DROP POLICY [ IF EXISTS ] name ON table_name [ CASCADE | RESTRICT ]
7814    /// ```
7815    ///
7816    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-droppolicy.html)
7817    fn parse_drop_policy(&mut self) -> Result<DropPolicy, ParserError> {
7818        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7819        let name = self.parse_identifier()?;
7820        self.expect_keyword_is(Keyword::ON)?;
7821        let table_name = self.parse_object_name(false)?;
7822        let drop_behavior = self.parse_optional_drop_behavior();
7823        Ok(DropPolicy {
7824            if_exists,
7825            name,
7826            table_name,
7827            drop_behavior,
7828        })
7829    }
7830    /// ```sql
7831    /// DROP CONNECTOR [IF EXISTS] name
7832    /// ```
7833    ///
7834    /// See [Hive](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27362034#LanguageManualDDL-DropConnector)
7835    fn parse_drop_connector(&mut self) -> Result<Statement, ParserError> {
7836        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7837        let name = self.parse_identifier()?;
7838        Ok(Statement::DropConnector { if_exists, name })
7839    }
7840
7841    /// ```sql
7842    /// DROP DOMAIN [ IF EXISTS ] name [ CASCADE | RESTRICT ]
7843    /// ```
7844    fn parse_drop_domain(&mut self) -> Result<DropDomain, ParserError> {
7845        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7846        let name = self.parse_object_name(false)?;
7847        let drop_behavior = self.parse_optional_drop_behavior();
7848        Ok(DropDomain {
7849            if_exists,
7850            name,
7851            drop_behavior,
7852        })
7853    }
7854
7855    /// ```sql
7856    /// DROP PROCEDURE [ IF EXISTS ] name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ] [, ...]
7857    /// [ CASCADE | RESTRICT ]
7858    /// ```
7859    fn parse_drop_procedure(&mut self) -> Result<Statement, ParserError> {
7860        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7861        let proc_desc = self.parse_comma_separated(Parser::parse_function_desc)?;
7862        let drop_behavior = self.parse_optional_drop_behavior();
7863        Ok(Statement::DropProcedure {
7864            if_exists,
7865            proc_desc,
7866            drop_behavior,
7867        })
7868    }
7869
7870    fn parse_function_desc(&mut self) -> Result<FunctionDesc, ParserError> {
7871        let name = self.parse_object_name(false)?;
7872
7873        let args = if self.consume_token(&Token::LParen) {
7874            if self.consume_token(&Token::RParen) {
7875                Some(vec![])
7876            } else {
7877                let args = self.parse_comma_separated(Parser::parse_function_arg)?;
7878                self.expect_token(&Token::RParen)?;
7879                Some(args)
7880            }
7881        } else {
7882            None
7883        };
7884
7885        Ok(FunctionDesc { name, args })
7886    }
7887
7888    /// See [DuckDB Docs](https://duckdb.org/docs/sql/statements/create_secret.html) for more details.
7889    fn parse_drop_secret(
7890        &mut self,
7891        temporary: bool,
7892        persistent: bool,
7893    ) -> Result<Statement, ParserError> {
7894        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7895        let name = self.parse_identifier()?;
7896        let storage_specifier = if self.parse_keyword(Keyword::FROM) {
7897            self.parse_identifier().ok()
7898        } else {
7899            None
7900        };
7901        let temp = match (temporary, persistent) {
7902            (true, false) => Some(true),
7903            (false, true) => Some(false),
7904            (false, false) => None,
7905            _ => self.expected_ref("TEMPORARY or PERSISTENT", self.peek_token_ref())?,
7906        };
7907
7908        Ok(Statement::DropSecret {
7909            if_exists,
7910            temporary: temp,
7911            name,
7912            storage_specifier,
7913        })
7914    }
7915
7916    /// Parse a `DECLARE` statement.
7917    ///
7918    /// ```sql
7919    /// DECLARE name [ BINARY ] [ ASENSITIVE | INSENSITIVE ] [ [ NO ] SCROLL ]
7920    ///     CURSOR [ { WITH | WITHOUT } HOLD ] FOR query
7921    /// ```
7922    ///
7923    /// The syntax can vary significantly between warehouses. See the grammar
7924    /// on the warehouse specific function in such cases.
7925    pub fn parse_declare(&mut self) -> Result<Statement, ParserError> {
7926        if dialect_of!(self is BigQueryDialect) {
7927            return self.parse_big_query_declare();
7928        }
7929        if dialect_of!(self is SnowflakeDialect) {
7930            return self.parse_snowflake_declare();
7931        }
7932        if dialect_of!(self is MsSqlDialect) {
7933            return self.parse_mssql_declare();
7934        }
7935
7936        let name = self.parse_identifier()?;
7937
7938        let binary = Some(self.parse_keyword(Keyword::BINARY));
7939        let sensitive = if self.parse_keyword(Keyword::INSENSITIVE) {
7940            Some(true)
7941        } else if self.parse_keyword(Keyword::ASENSITIVE) {
7942            Some(false)
7943        } else {
7944            None
7945        };
7946        let scroll = if self.parse_keyword(Keyword::SCROLL) {
7947            Some(true)
7948        } else if self.parse_keywords(&[Keyword::NO, Keyword::SCROLL]) {
7949            Some(false)
7950        } else {
7951            None
7952        };
7953
7954        self.expect_keyword_is(Keyword::CURSOR)?;
7955        let declare_type = Some(DeclareType::Cursor);
7956
7957        let hold = match self.parse_one_of_keywords(&[Keyword::WITH, Keyword::WITHOUT]) {
7958            Some(keyword) => {
7959                self.expect_keyword_is(Keyword::HOLD)?;
7960
7961                match keyword {
7962                    Keyword::WITH => Some(true),
7963                    Keyword::WITHOUT => Some(false),
7964                    unexpected_keyword => return Err(ParserError::ParserError(
7965                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in cursor hold"),
7966                    )),
7967                }
7968            }
7969            None => None,
7970        };
7971
7972        self.expect_keyword_is(Keyword::FOR)?;
7973
7974        let query = Some(self.parse_query()?);
7975
7976        Ok(Statement::Declare {
7977            stmts: vec![Declare {
7978                names: vec![name],
7979                data_type: None,
7980                assignment: None,
7981                declare_type,
7982                binary,
7983                sensitive,
7984                scroll,
7985                hold,
7986                for_query: query,
7987            }],
7988        })
7989    }
7990
7991    /// Parse a [BigQuery] `DECLARE` statement.
7992    ///
7993    /// Syntax:
7994    /// ```text
7995    /// DECLARE variable_name[, ...] [{ <variable_type> | <DEFAULT expression> }];
7996    /// ```
7997    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#declare
7998    pub fn parse_big_query_declare(&mut self) -> Result<Statement, ParserError> {
7999        let names = self.parse_comma_separated(Parser::parse_identifier)?;
8000
8001        let data_type = match &self.peek_token_ref().token {
8002            Token::Word(w) if w.keyword == Keyword::DEFAULT => None,
8003            _ => Some(self.parse_data_type()?),
8004        };
8005
8006        let expr = if data_type.is_some() {
8007            if self.parse_keyword(Keyword::DEFAULT) {
8008                Some(self.parse_expr()?)
8009            } else {
8010                None
8011            }
8012        } else {
8013            // If no variable type - default expression must be specified, per BQ docs.
8014            // i.e `DECLARE foo;` is invalid.
8015            self.expect_keyword_is(Keyword::DEFAULT)?;
8016            Some(self.parse_expr()?)
8017        };
8018
8019        Ok(Statement::Declare {
8020            stmts: vec![Declare {
8021                names,
8022                data_type,
8023                assignment: expr.map(|expr| DeclareAssignment::Default(Box::new(expr))),
8024                declare_type: None,
8025                binary: None,
8026                sensitive: None,
8027                scroll: None,
8028                hold: None,
8029                for_query: None,
8030            }],
8031        })
8032    }
8033
8034    /// Parse a [Snowflake] `DECLARE` statement.
8035    ///
8036    /// Syntax:
8037    /// ```text
8038    /// DECLARE
8039    ///   [{ <variable_declaration>
8040    ///      | <cursor_declaration>
8041    ///      | <resultset_declaration>
8042    ///      | <exception_declaration> }; ... ]
8043    ///
8044    /// <variable_declaration>
8045    /// <variable_name> [<type>] [ { DEFAULT | := } <expression>]
8046    ///
8047    /// <cursor_declaration>
8048    /// <cursor_name> CURSOR FOR <query>
8049    ///
8050    /// <resultset_declaration>
8051    /// <resultset_name> RESULTSET [ { DEFAULT | := } ( <query> ) ] ;
8052    ///
8053    /// <exception_declaration>
8054    /// <exception_name> EXCEPTION [ ( <exception_number> , '<exception_message>' ) ] ;
8055    /// ```
8056    ///
8057    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/snowflake-scripting/declare
8058    pub fn parse_snowflake_declare(&mut self) -> Result<Statement, ParserError> {
8059        let mut stmts = vec![];
8060        loop {
8061            let name = self.parse_identifier()?;
8062            let (declare_type, for_query, assigned_expr, data_type) =
8063                if self.parse_keyword(Keyword::CURSOR) {
8064                    self.expect_keyword_is(Keyword::FOR)?;
8065                    match &self.peek_token_ref().token {
8066                        Token::Word(w) if w.keyword == Keyword::SELECT => (
8067                            Some(DeclareType::Cursor),
8068                            Some(self.parse_query()?),
8069                            None,
8070                            None,
8071                        ),
8072                        _ => (
8073                            Some(DeclareType::Cursor),
8074                            None,
8075                            Some(DeclareAssignment::For(Box::new(self.parse_expr()?))),
8076                            None,
8077                        ),
8078                    }
8079                } else if self.parse_keyword(Keyword::RESULTSET) {
8080                    let assigned_expr = if self.peek_token_ref().token != Token::SemiColon {
8081                        self.parse_snowflake_variable_declaration_expression()?
8082                    } else {
8083                        // Nothing more to do. The statement has no further parameters.
8084                        None
8085                    };
8086
8087                    (Some(DeclareType::ResultSet), None, assigned_expr, None)
8088                } else if self.parse_keyword(Keyword::EXCEPTION) {
8089                    let assigned_expr = if self.peek_token_ref().token == Token::LParen {
8090                        Some(DeclareAssignment::Expr(Box::new(self.parse_expr()?)))
8091                    } else {
8092                        // Nothing more to do. The statement has no further parameters.
8093                        None
8094                    };
8095
8096                    (Some(DeclareType::Exception), None, assigned_expr, None)
8097                } else {
8098                    // Without an explicit keyword, the only valid option is variable declaration.
8099                    let (assigned_expr, data_type) = if let Some(assigned_expr) =
8100                        self.parse_snowflake_variable_declaration_expression()?
8101                    {
8102                        (Some(assigned_expr), None)
8103                    } else if let Token::Word(_) = &self.peek_token_ref().token {
8104                        let data_type = self.parse_data_type()?;
8105                        (
8106                            self.parse_snowflake_variable_declaration_expression()?,
8107                            Some(data_type),
8108                        )
8109                    } else {
8110                        (None, None)
8111                    };
8112                    (None, None, assigned_expr, data_type)
8113                };
8114            let stmt = Declare {
8115                names: vec![name],
8116                data_type,
8117                assignment: assigned_expr,
8118                declare_type,
8119                binary: None,
8120                sensitive: None,
8121                scroll: None,
8122                hold: None,
8123                for_query,
8124            };
8125
8126            stmts.push(stmt);
8127            if self.consume_token(&Token::SemiColon) {
8128                match &self.peek_token_ref().token {
8129                    Token::Word(w)
8130                        if ALL_KEYWORDS
8131                            .binary_search(&w.value.to_uppercase().as_str())
8132                            .is_err() =>
8133                    {
8134                        // Not a keyword - start of a new declaration.
8135                        continue;
8136                    }
8137                    _ => {
8138                        // Put back the semicolon, this is the end of the DECLARE statement.
8139                        self.prev_token();
8140                    }
8141                }
8142            }
8143
8144            break;
8145        }
8146
8147        Ok(Statement::Declare { stmts })
8148    }
8149
8150    /// Parse a [MsSql] `DECLARE` statement.
8151    ///
8152    /// Syntax:
8153    /// ```text
8154    /// DECLARE
8155    // {
8156    //   { @local_variable [AS] data_type [ = value ] }
8157    //   | { @cursor_variable_name CURSOR [ FOR ] }
8158    // } [ ,...n ]
8159    /// ```
8160    /// [MsSql]: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/declare-local-variable-transact-sql?view=sql-server-ver16
8161    pub fn parse_mssql_declare(&mut self) -> Result<Statement, ParserError> {
8162        let stmts = self.parse_comma_separated(Parser::parse_mssql_declare_stmt)?;
8163
8164        Ok(Statement::Declare { stmts })
8165    }
8166
8167    /// Parse the body of a [MsSql] `DECLARE`statement.
8168    ///
8169    /// Syntax:
8170    /// ```text
8171    // {
8172    //   { @local_variable [AS] data_type [ = value ] }
8173    //   | { @cursor_variable_name CURSOR [ FOR ]}
8174    // } [ ,...n ]
8175    /// ```
8176    /// [MsSql]: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/declare-local-variable-transact-sql?view=sql-server-ver16
8177    pub fn parse_mssql_declare_stmt(&mut self) -> Result<Declare, ParserError> {
8178        let name = {
8179            let ident = self.parse_identifier()?;
8180            if !ident.value.starts_with('@')
8181                && !matches!(
8182                    &self.peek_token_ref().token,
8183                    Token::Word(w) if w.keyword == Keyword::CURSOR
8184                )
8185            {
8186                Err(ParserError::TokenizerError(
8187                    "Invalid MsSql variable declaration.".to_string(),
8188                ))
8189            } else {
8190                Ok(ident)
8191            }
8192        }?;
8193
8194        let (declare_type, data_type) = match &self.peek_token_ref().token {
8195            Token::Word(w) => match w.keyword {
8196                Keyword::CURSOR => {
8197                    self.next_token();
8198                    (Some(DeclareType::Cursor), None)
8199                }
8200                Keyword::AS => {
8201                    self.next_token();
8202                    (None, Some(self.parse_data_type()?))
8203                }
8204                _ => (None, Some(self.parse_data_type()?)),
8205            },
8206            _ => (None, Some(self.parse_data_type()?)),
8207        };
8208
8209        let (for_query, assignment) = if self.peek_keyword(Keyword::FOR) {
8210            self.next_token();
8211            let query = Some(self.parse_query()?);
8212            (query, None)
8213        } else {
8214            let assignment = self.parse_mssql_variable_declaration_expression()?;
8215            (None, assignment)
8216        };
8217
8218        Ok(Declare {
8219            names: vec![name],
8220            data_type,
8221            assignment,
8222            declare_type,
8223            binary: None,
8224            sensitive: None,
8225            scroll: None,
8226            hold: None,
8227            for_query,
8228        })
8229    }
8230
8231    /// Parses the assigned expression in a variable declaration.
8232    ///
8233    /// Syntax:
8234    /// ```text
8235    /// [ { DEFAULT | := } <expression>]
8236    /// ```
8237    /// <https://docs.snowflake.com/en/sql-reference/snowflake-scripting/declare#variable-declaration-syntax>
8238    pub fn parse_snowflake_variable_declaration_expression(
8239        &mut self,
8240    ) -> Result<Option<DeclareAssignment>, ParserError> {
8241        Ok(match &self.peek_token_ref().token {
8242            Token::Word(w) if w.keyword == Keyword::DEFAULT => {
8243                self.next_token(); // Skip `DEFAULT`
8244                Some(DeclareAssignment::Default(Box::new(self.parse_expr()?)))
8245            }
8246            Token::Assignment => {
8247                self.next_token(); // Skip `:=`
8248                Some(DeclareAssignment::DuckAssignment(Box::new(
8249                    self.parse_expr()?,
8250                )))
8251            }
8252            _ => None,
8253        })
8254    }
8255
8256    /// Parses the assigned expression in a variable declaration.
8257    ///
8258    /// Syntax:
8259    /// ```text
8260    /// [ = <expression>]
8261    /// ```
8262    pub fn parse_mssql_variable_declaration_expression(
8263        &mut self,
8264    ) -> Result<Option<DeclareAssignment>, ParserError> {
8265        Ok(match &self.peek_token_ref().token {
8266            Token::Eq => {
8267                self.next_token(); // Skip `=`
8268                Some(DeclareAssignment::MsSqlAssignment(Box::new(
8269                    self.parse_expr()?,
8270                )))
8271            }
8272            _ => None,
8273        })
8274    }
8275
8276    /// Parse `FETCH [direction] { FROM | IN } cursor INTO target;` statement.
8277    pub fn parse_fetch_statement(&mut self) -> Result<Statement, ParserError> {
8278        let direction = if self.parse_keyword(Keyword::NEXT) {
8279            FetchDirection::Next
8280        } else if self.parse_keyword(Keyword::PRIOR) {
8281            FetchDirection::Prior
8282        } else if self.parse_keyword(Keyword::FIRST) {
8283            FetchDirection::First
8284        } else if self.parse_keyword(Keyword::LAST) {
8285            FetchDirection::Last
8286        } else if self.parse_keyword(Keyword::ABSOLUTE) {
8287            FetchDirection::Absolute {
8288                limit: self.parse_number_value()?,
8289            }
8290        } else if self.parse_keyword(Keyword::RELATIVE) {
8291            FetchDirection::Relative {
8292                limit: self.parse_number_value()?,
8293            }
8294        } else if self.parse_keyword(Keyword::FORWARD) {
8295            if self.parse_keyword(Keyword::ALL) {
8296                FetchDirection::ForwardAll
8297            } else {
8298                FetchDirection::Forward {
8299                    // TODO: Support optional
8300                    limit: Some(self.parse_number_value()?),
8301                }
8302            }
8303        } else if self.parse_keyword(Keyword::BACKWARD) {
8304            if self.parse_keyword(Keyword::ALL) {
8305                FetchDirection::BackwardAll
8306            } else {
8307                FetchDirection::Backward {
8308                    // TODO: Support optional
8309                    limit: Some(self.parse_number_value()?),
8310                }
8311            }
8312        } else if self.parse_keyword(Keyword::ALL) {
8313            FetchDirection::All
8314        } else {
8315            FetchDirection::Count {
8316                limit: self.parse_number_value()?,
8317            }
8318        };
8319
8320        let position = if self.peek_keyword(Keyword::FROM) {
8321            self.expect_keyword(Keyword::FROM)?;
8322            FetchPosition::From
8323        } else if self.peek_keyword(Keyword::IN) {
8324            self.expect_keyword(Keyword::IN)?;
8325            FetchPosition::In
8326        } else {
8327            return parser_err!("Expected FROM or IN", self.peek_token_ref().span.start);
8328        };
8329
8330        let name = self.parse_identifier()?;
8331
8332        let into = if self.parse_keyword(Keyword::INTO) {
8333            Some(self.parse_object_name(false)?)
8334        } else {
8335            None
8336        };
8337
8338        Ok(Statement::Fetch {
8339            name,
8340            direction,
8341            position,
8342            into,
8343        })
8344    }
8345
8346    /// Parse a `DISCARD` statement.
8347    pub fn parse_discard(&mut self) -> Result<Statement, ParserError> {
8348        let object_type = if self.parse_keyword(Keyword::ALL) {
8349            DiscardObject::ALL
8350        } else if self.parse_keyword(Keyword::PLANS) {
8351            DiscardObject::PLANS
8352        } else if self.parse_keyword(Keyword::SEQUENCES) {
8353            DiscardObject::SEQUENCES
8354        } else if self.parse_keyword(Keyword::TEMP) || self.parse_keyword(Keyword::TEMPORARY) {
8355            DiscardObject::TEMP
8356        } else {
8357            return self.expected_ref(
8358                "ALL, PLANS, SEQUENCES, TEMP or TEMPORARY after DISCARD",
8359                self.peek_token_ref(),
8360            );
8361        };
8362        Ok(Statement::Discard { object_type })
8363    }
8364
8365    /// Parse a `CREATE INDEX` statement.
8366    pub fn parse_create_index(&mut self, unique: bool) -> Result<CreateIndex, ParserError> {
8367        let concurrently = self.parse_keyword(Keyword::CONCURRENTLY);
8368        let r#async = self.parse_keyword(Keyword::ASYNC);
8369        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
8370
8371        let mut using = None;
8372
8373        let index_name = if if_not_exists || !self.parse_keyword(Keyword::ON) {
8374            let index_name = self.parse_object_name(false)?;
8375            // MySQL allows `USING index_type` either before or after `ON table_name`
8376            using = self.parse_optional_using_then_index_type()?;
8377            self.expect_keyword_is(Keyword::ON)?;
8378            Some(index_name)
8379        } else {
8380            None
8381        };
8382
8383        let table_name = self.parse_object_name(false)?;
8384
8385        // MySQL allows having two `USING` clauses.
8386        // In that case, the second clause overwrites the first.
8387        using = self.parse_optional_using_then_index_type()?.or(using);
8388
8389        let columns = self.parse_parenthesized_index_column_list()?;
8390
8391        let include = if self.parse_keyword(Keyword::INCLUDE) {
8392            self.expect_token(&Token::LParen)?;
8393            let columns = self.parse_comma_separated(|p| p.parse_identifier())?;
8394            self.expect_token(&Token::RParen)?;
8395            columns
8396        } else {
8397            vec![]
8398        };
8399
8400        let nulls_distinct = if self.parse_keyword(Keyword::NULLS) {
8401            let not = self.parse_keyword(Keyword::NOT);
8402            self.expect_keyword_is(Keyword::DISTINCT)?;
8403            Some(!not)
8404        } else {
8405            None
8406        };
8407
8408        let with = if self.dialect.supports_create_index_with_clause()
8409            && self.parse_keyword(Keyword::WITH)
8410        {
8411            self.expect_token(&Token::LParen)?;
8412            let with_params = self.parse_comma_separated(Parser::parse_expr)?;
8413            self.expect_token(&Token::RParen)?;
8414            with_params
8415        } else {
8416            Vec::new()
8417        };
8418
8419        let predicate = if self.parse_keyword(Keyword::WHERE) {
8420            Some(self.parse_expr()?)
8421        } else {
8422            None
8423        };
8424
8425        // MySQL options (including the modern style of `USING` after the column list instead of
8426        // before, which is deprecated) shouldn't conflict with other preceding options (e.g. `WITH
8427        // PARSER` won't be caught by the above `WITH` clause parsing because MySQL doesn't set that
8428        // support flag). This is probably invalid syntax for other dialects, but it is simpler to
8429        // parse it anyway (as we do inside `ALTER TABLE` and `CREATE TABLE` parsing).
8430        let index_options = self.parse_index_options()?;
8431
8432        // MySQL allows `ALGORITHM` and `LOCK` options. Unlike in `ALTER TABLE`, they need not be comma separated.
8433        let mut alter_options = Vec::new();
8434        while self
8435            .peek_one_of_keywords(&[Keyword::ALGORITHM, Keyword::LOCK])
8436            .is_some()
8437        {
8438            alter_options.push(self.parse_alter_table_operation()?)
8439        }
8440
8441        Ok(CreateIndex {
8442            name: index_name,
8443            table_name,
8444            using,
8445            columns,
8446            unique,
8447            concurrently,
8448            r#async,
8449            if_not_exists,
8450            include,
8451            nulls_distinct,
8452            with,
8453            predicate,
8454            index_options,
8455            alter_options,
8456        })
8457    }
8458
8459    /// Parse a `CREATE EXTENSION` statement.
8460    pub fn parse_create_extension(&mut self) -> Result<CreateExtension, ParserError> {
8461        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
8462        let name = self.parse_identifier()?;
8463
8464        let (schema, version, cascade) = if self.parse_keyword(Keyword::WITH) {
8465            let schema = if self.parse_keyword(Keyword::SCHEMA) {
8466                Some(self.parse_identifier()?)
8467            } else {
8468                None
8469            };
8470
8471            let version = if self.parse_keyword(Keyword::VERSION) {
8472                Some(self.parse_identifier()?)
8473            } else {
8474                None
8475            };
8476
8477            let cascade = self.parse_keyword(Keyword::CASCADE);
8478
8479            (schema, version, cascade)
8480        } else {
8481            (None, None, false)
8482        };
8483
8484        Ok(CreateExtension {
8485            name,
8486            if_not_exists,
8487            schema,
8488            version,
8489            cascade,
8490        })
8491    }
8492
8493    /// Parse a PostgreSQL-specific [Statement::CreateCollation] statement.
8494    pub fn parse_create_collation(&mut self) -> Result<CreateCollation, ParserError> {
8495        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
8496        let name = self.parse_object_name(false)?;
8497
8498        let definition = if self.parse_keyword(Keyword::FROM) {
8499            CreateCollationDefinition::From(self.parse_object_name(false)?)
8500        } else if self.consume_token(&Token::LParen) {
8501            let options = self.parse_comma_separated(Parser::parse_sql_option)?;
8502            self.expect_token(&Token::RParen)?;
8503            CreateCollationDefinition::Options(options)
8504        } else {
8505            return self.expected_ref(
8506                "FROM or parenthesized option list after CREATE COLLATION name",
8507                self.peek_token_ref(),
8508            );
8509        };
8510
8511        Ok(CreateCollation {
8512            if_not_exists,
8513            name,
8514            definition,
8515        })
8516    }
8517
8518    /// Parse a PostgreSQL-specific [Statement::DropExtension] statement.
8519    pub fn parse_drop_extension(&mut self) -> Result<Statement, ParserError> {
8520        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
8521        let names = self.parse_comma_separated(|p| p.parse_identifier())?;
8522        let cascade_or_restrict =
8523            self.parse_one_of_keywords(&[Keyword::CASCADE, Keyword::RESTRICT]);
8524        Ok(Statement::DropExtension(DropExtension {
8525            names,
8526            if_exists,
8527            cascade_or_restrict: cascade_or_restrict
8528                .map(|k| match k {
8529                    Keyword::CASCADE => Ok(ReferentialAction::Cascade),
8530                    Keyword::RESTRICT => Ok(ReferentialAction::Restrict),
8531                    _ => self.expected_ref("CASCADE or RESTRICT", self.peek_token_ref()),
8532                })
8533                .transpose()?,
8534        }))
8535    }
8536
8537    /// Parse a[Statement::DropOperator] statement.
8538    ///
8539    pub fn parse_drop_operator(&mut self) -> Result<Statement, ParserError> {
8540        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
8541        let operators = self.parse_comma_separated(|p| p.parse_drop_operator_signature())?;
8542        let drop_behavior = self.parse_optional_drop_behavior();
8543        Ok(Statement::DropOperator(DropOperator {
8544            if_exists,
8545            operators,
8546            drop_behavior,
8547        }))
8548    }
8549
8550    /// Parse an operator signature for a [Statement::DropOperator]
8551    /// Format: `name ( { left_type | NONE } , right_type )`
8552    fn parse_drop_operator_signature(&mut self) -> Result<DropOperatorSignature, ParserError> {
8553        let name = self.parse_operator_name()?;
8554        self.expect_token(&Token::LParen)?;
8555
8556        // Parse left operand type (or NONE for prefix operators)
8557        let left_type = if self.parse_keyword(Keyword::NONE) {
8558            None
8559        } else {
8560            Some(self.parse_data_type()?)
8561        };
8562
8563        self.expect_token(&Token::Comma)?;
8564
8565        // Parse right operand type (always required)
8566        let right_type = self.parse_data_type()?;
8567
8568        self.expect_token(&Token::RParen)?;
8569
8570        Ok(DropOperatorSignature {
8571            name,
8572            left_type,
8573            right_type,
8574        })
8575    }
8576
8577    /// Parse a [Statement::DropOperatorFamily]
8578    ///
8579    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-dropopfamily.html)
8580    pub fn parse_drop_operator_family(&mut self) -> Result<Statement, ParserError> {
8581        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
8582        let names = self.parse_comma_separated(|p| p.parse_object_name(false))?;
8583        self.expect_keyword(Keyword::USING)?;
8584        let using = self.parse_identifier()?;
8585        let drop_behavior = self.parse_optional_drop_behavior();
8586        Ok(Statement::DropOperatorFamily(DropOperatorFamily {
8587            if_exists,
8588            names,
8589            using,
8590            drop_behavior,
8591        }))
8592    }
8593
8594    /// Parse a [Statement::DropOperatorClass]
8595    ///
8596    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-dropopclass.html)
8597    pub fn parse_drop_operator_class(&mut self) -> Result<Statement, ParserError> {
8598        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
8599        let names = self.parse_comma_separated(|p| p.parse_object_name(false))?;
8600        self.expect_keyword(Keyword::USING)?;
8601        let using = self.parse_identifier()?;
8602        let drop_behavior = self.parse_optional_drop_behavior();
8603        Ok(Statement::DropOperatorClass(DropOperatorClass {
8604            if_exists,
8605            names,
8606            using,
8607            drop_behavior,
8608        }))
8609    }
8610
8611    /// Parse Hive distribution style.
8612    ///
8613    /// TODO: Support parsing for `SKEWED` distribution style.
8614    pub fn parse_hive_distribution(&mut self) -> Result<HiveDistributionStyle, ParserError> {
8615        if self.parse_keywords(&[Keyword::PARTITIONED, Keyword::BY]) {
8616            self.expect_token(&Token::LParen)?;
8617            let columns =
8618                self.parse_comma_separated(|parser| parser.parse_column_def_inner(true))?;
8619            self.expect_token(&Token::RParen)?;
8620            Ok(HiveDistributionStyle::PARTITIONED { columns })
8621        } else {
8622            Ok(HiveDistributionStyle::NONE)
8623        }
8624    }
8625
8626    /// Parse Redshift `DISTSTYLE { AUTO | EVEN | KEY | ALL }`.
8627    ///
8628    /// See <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html>
8629    fn parse_dist_style(&mut self) -> Result<DistStyle, ParserError> {
8630        let token = self.next_token();
8631        match &token.token {
8632            Token::Word(w) => match w.keyword {
8633                Keyword::AUTO => Ok(DistStyle::Auto),
8634                Keyword::EVEN => Ok(DistStyle::Even),
8635                Keyword::KEY => Ok(DistStyle::Key),
8636                Keyword::ALL => Ok(DistStyle::All),
8637                _ => self.expected("AUTO, EVEN, KEY, or ALL", token),
8638            },
8639            _ => self.expected("AUTO, EVEN, KEY, or ALL", token),
8640        }
8641    }
8642
8643    /// Parse Hive formats.
8644    pub fn parse_hive_formats(&mut self) -> Result<Option<HiveFormat>, ParserError> {
8645        let mut hive_format: Option<HiveFormat> = None;
8646        loop {
8647            match self.parse_one_of_keywords(&[
8648                Keyword::ROW,
8649                Keyword::STORED,
8650                Keyword::LOCATION,
8651                Keyword::WITH,
8652                Keyword::USING,
8653            ]) {
8654                Some(Keyword::ROW) => {
8655                    hive_format
8656                        .get_or_insert_with(HiveFormat::default)
8657                        .row_format = Some(self.parse_row_format()?);
8658                }
8659                Some(Keyword::STORED) => {
8660                    self.expect_keyword_is(Keyword::AS)?;
8661                    if self.parse_keyword(Keyword::INPUTFORMAT) {
8662                        let input_format = self.parse_expr()?;
8663                        self.expect_keyword_is(Keyword::OUTPUTFORMAT)?;
8664                        let output_format = self.parse_expr()?;
8665                        hive_format.get_or_insert_with(HiveFormat::default).storage =
8666                            Some(HiveIOFormat::IOF {
8667                                input_format,
8668                                output_format,
8669                            });
8670                    } else {
8671                        let format = self.parse_file_format()?;
8672                        hive_format.get_or_insert_with(HiveFormat::default).storage =
8673                            Some(HiveIOFormat::FileFormat { format });
8674                    }
8675                }
8676                Some(Keyword::LOCATION) => {
8677                    hive_format.get_or_insert_with(HiveFormat::default).location =
8678                        Some(self.parse_literal_string()?);
8679                }
8680                Some(Keyword::WITH) => {
8681                    self.prev_token();
8682                    let properties = self
8683                        .parse_options_with_keywords(&[Keyword::WITH, Keyword::SERDEPROPERTIES])?;
8684                    if !properties.is_empty() {
8685                        hive_format
8686                            .get_or_insert_with(HiveFormat::default)
8687                            .serde_properties = Some(properties);
8688                    } else {
8689                        break;
8690                    }
8691                }
8692                Some(Keyword::USING) if self.dialect.supports_create_table_using() => {
8693                    let format = self.parse_identifier()?;
8694                    hive_format.get_or_insert_with(HiveFormat::default).storage =
8695                        Some(HiveIOFormat::Using { format });
8696                }
8697                Some(Keyword::USING) => {
8698                    // USING is not a table format keyword in this dialect; put it back
8699                    self.prev_token();
8700                    break;
8701                }
8702                None => break,
8703                _ => break,
8704            }
8705        }
8706
8707        Ok(hive_format)
8708    }
8709
8710    /// Parse Hive row format.
8711    pub fn parse_row_format(&mut self) -> Result<HiveRowFormat, ParserError> {
8712        self.expect_keyword_is(Keyword::FORMAT)?;
8713        match self.parse_one_of_keywords(&[Keyword::SERDE, Keyword::DELIMITED]) {
8714            Some(Keyword::SERDE) => {
8715                let class = self.parse_literal_string()?;
8716                Ok(HiveRowFormat::SERDE { class })
8717            }
8718            _ => {
8719                let mut row_delimiters = vec![];
8720
8721                loop {
8722                    match self.parse_one_of_keywords(&[
8723                        Keyword::FIELDS,
8724                        Keyword::COLLECTION,
8725                        Keyword::MAP,
8726                        Keyword::LINES,
8727                        Keyword::NULL,
8728                    ]) {
8729                        Some(Keyword::FIELDS)
8730                            if self.parse_keywords(&[Keyword::TERMINATED, Keyword::BY]) =>
8731                        {
8732                            row_delimiters.push(HiveRowDelimiter {
8733                                delimiter: HiveDelimiter::FieldsTerminatedBy,
8734                                char: self.parse_identifier()?,
8735                            });
8736
8737                            if self.parse_keywords(&[Keyword::ESCAPED, Keyword::BY]) {
8738                                row_delimiters.push(HiveRowDelimiter {
8739                                    delimiter: HiveDelimiter::FieldsEscapedBy,
8740                                    char: self.parse_identifier()?,
8741                                });
8742                            }
8743                        }
8744                        Some(Keyword::COLLECTION)
8745                            if self.parse_keywords(&[
8746                                Keyword::ITEMS,
8747                                Keyword::TERMINATED,
8748                                Keyword::BY,
8749                            ]) =>
8750                        {
8751                            row_delimiters.push(HiveRowDelimiter {
8752                                delimiter: HiveDelimiter::CollectionItemsTerminatedBy,
8753                                char: self.parse_identifier()?,
8754                            });
8755                        }
8756                        Some(Keyword::MAP)
8757                            if self.parse_keywords(&[
8758                                Keyword::KEYS,
8759                                Keyword::TERMINATED,
8760                                Keyword::BY,
8761                            ]) =>
8762                        {
8763                            row_delimiters.push(HiveRowDelimiter {
8764                                delimiter: HiveDelimiter::MapKeysTerminatedBy,
8765                                char: self.parse_identifier()?,
8766                            });
8767                        }
8768                        Some(Keyword::LINES)
8769                            if self.parse_keywords(&[Keyword::TERMINATED, Keyword::BY]) =>
8770                        {
8771                            row_delimiters.push(HiveRowDelimiter {
8772                                delimiter: HiveDelimiter::LinesTerminatedBy,
8773                                char: self.parse_identifier()?,
8774                            });
8775                        }
8776                        Some(Keyword::NULL)
8777                            if self.parse_keywords(&[Keyword::DEFINED, Keyword::AS]) =>
8778                        {
8779                            row_delimiters.push(HiveRowDelimiter {
8780                                delimiter: HiveDelimiter::NullDefinedAs,
8781                                char: self.parse_identifier()?,
8782                            });
8783                        }
8784                        Some(Keyword::NULL) => break,
8785                        _ => {
8786                            break;
8787                        }
8788                    }
8789                }
8790
8791                Ok(HiveRowFormat::DELIMITED {
8792                    delimiters: row_delimiters,
8793                })
8794            }
8795        }
8796    }
8797
8798    fn parse_optional_on_cluster(&mut self) -> Result<Option<Ident>, ParserError> {
8799        if self.parse_keywords(&[Keyword::ON, Keyword::CLUSTER]) {
8800            Ok(Some(self.parse_identifier()?))
8801        } else {
8802            Ok(None)
8803        }
8804    }
8805
8806    /// Parse `CREATE TABLE` statement.
8807    #[allow(clippy::too_many_arguments)]
8808    pub fn parse_create_table(
8809        &mut self,
8810        or_replace: bool,
8811        temporary: bool,
8812        unlogged: bool,
8813        global: Option<bool>,
8814        transient: bool,
8815        volatile: bool,
8816        multiset: Option<bool>,
8817    ) -> Result<CreateTable, ParserError> {
8818        let allow_unquoted_hyphen = dialect_of!(self is BigQueryDialect);
8819        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
8820        let table_name = self.parse_object_name(allow_unquoted_hyphen)?;
8821
8822        let fallback = if self.dialect.supports_leading_comma_before_table_options()
8823            && self.consume_token(&Token::Comma)
8824        {
8825            let fallback = self.maybe_parse_fallback()?;
8826            if fallback.is_none() {
8827                self.prev_token(); // Put back comma.
8828            }
8829            fallback
8830        } else {
8831            None
8832        };
8833
8834        // PostgreSQL PARTITION OF for child partition tables
8835        // Note: This is a PostgreSQL-specific feature, but the dialect check was intentionally
8836        // removed to allow GenericDialect and other dialects to parse this syntax. This enables
8837        // multi-dialect SQL tools to work with PostgreSQL-specific DDL statements.
8838        //
8839        // PARTITION OF can be combined with other table definition clauses in the AST,
8840        // though PostgreSQL itself prohibits PARTITION OF with AS SELECT or LIKE clauses.
8841        // The parser accepts these combinations for flexibility; semantic validation
8842        // is left to downstream tools.
8843        // Child partitions can have their own constraints and indexes.
8844        let partition_of = if self.parse_keywords(&[Keyword::PARTITION, Keyword::OF]) {
8845            Some(self.parse_object_name(allow_unquoted_hyphen)?)
8846        } else {
8847            None
8848        };
8849
8850        // Clickhouse has `ON CLUSTER 'cluster'` syntax for DDLs
8851        let on_cluster = self.parse_optional_on_cluster()?;
8852
8853        let like = self.maybe_parse_create_table_like(allow_unquoted_hyphen)?;
8854
8855        let clone = if self.parse_keyword(Keyword::CLONE) {
8856            self.parse_object_name(allow_unquoted_hyphen).ok()
8857        } else {
8858            None
8859        };
8860
8861        // parse optional column list (schema)
8862        let (columns, constraints) = self.parse_columns()?;
8863        let comment_after_column_def =
8864            if dialect_of!(self is HiveDialect) && self.parse_keyword(Keyword::COMMENT) {
8865                let next_token = self.next_token();
8866                match next_token.token {
8867                    Token::SingleQuotedString(str) => Some(CommentDef::WithoutEq(str)),
8868                    _ => self.expected("comment", next_token)?,
8869                }
8870            } else {
8871                None
8872            };
8873
8874        // PostgreSQL PARTITION OF: partition bound specification
8875        let for_values = if partition_of.is_some() {
8876            if self.peek_keyword(Keyword::FOR) || self.peek_keyword(Keyword::DEFAULT) {
8877                Some(self.parse_partition_for_values()?)
8878            } else {
8879                return self.expected_ref(
8880                    "FOR VALUES or DEFAULT after PARTITION OF",
8881                    self.peek_token_ref(),
8882                );
8883            }
8884        } else {
8885            None
8886        };
8887
8888        // SQLite supports `WITHOUT ROWID` at the end of `CREATE TABLE`
8889        let without_rowid = self.parse_keywords(&[Keyword::WITHOUT, Keyword::ROWID]);
8890
8891        let hive_distribution = self.parse_hive_distribution()?;
8892        let clustered_by = self.parse_optional_clustered_by()?;
8893        let hive_formats = self.parse_hive_formats()?;
8894
8895        let create_table_config = self.parse_optional_create_table_config()?;
8896
8897        // ClickHouse supports `PRIMARY KEY`, before `ORDER BY`
8898        // https://clickhouse.com/docs/en/sql-reference/statements/create/table#primary-key
8899        let primary_key = if dialect_of!(self is ClickHouseDialect | GenericDialect)
8900            && self.parse_keywords(&[Keyword::PRIMARY, Keyword::KEY])
8901        {
8902            Some(Box::new(self.parse_expr()?))
8903        } else {
8904            None
8905        };
8906
8907        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
8908            Some(self.parse_sorting_key()?)
8909        } else {
8910            None
8911        };
8912
8913        // ClickHouse allows PARTITION BY after ORDER BY
8914        // https://clickhouse.com/docs/en/sql-reference/statements/create/table#partition-by
8915        let partition_by = if create_table_config.partition_by.is_none()
8916            && self.dialect.supports_partition_by_after_order_by()
8917            && self.parse_keywords(&[Keyword::PARTITION, Keyword::BY])
8918        {
8919            Some(Box::new(self.parse_expr()?))
8920        } else {
8921            create_table_config.partition_by
8922        };
8923
8924        let on_commit = if self.parse_keywords(&[Keyword::ON, Keyword::COMMIT]) {
8925            Some(self.parse_create_table_on_commit()?)
8926        } else {
8927            None
8928        };
8929
8930        let strict = self.parse_keyword(Keyword::STRICT);
8931
8932        // Redshift: BACKUP YES|NO
8933        let backup = if self.parse_keyword(Keyword::BACKUP) {
8934            let keyword = self.expect_one_of_keywords(&[Keyword::YES, Keyword::NO])?;
8935            Some(keyword == Keyword::YES)
8936        } else {
8937            None
8938        };
8939
8940        // Redshift: DISTSTYLE, DISTKEY, SORTKEY
8941        let diststyle = if self.parse_keyword(Keyword::DISTSTYLE) {
8942            Some(self.parse_dist_style()?)
8943        } else {
8944            None
8945        };
8946        let distkey = if self.parse_keyword(Keyword::DISTKEY) {
8947            self.expect_token(&Token::LParen)?;
8948            let expr = self.parse_expr()?;
8949            self.expect_token(&Token::RParen)?;
8950            Some(expr)
8951        } else {
8952            None
8953        };
8954        let sortkey = if self.parse_keyword(Keyword::SORTKEY) {
8955            self.expect_token(&Token::LParen)?;
8956            let columns = self.parse_comma_separated(|p| p.parse_expr())?;
8957            self.expect_token(&Token::RParen)?;
8958            Some(columns)
8959        } else {
8960            None
8961        };
8962
8963        // Parse optional `AS ( query )`
8964        let query = if self.parse_keyword(Keyword::AS) {
8965            Some(self.parse_query()?)
8966        } else if self.dialect.supports_create_table_select() && self.parse_keyword(Keyword::SELECT)
8967        {
8968            // rewind the SELECT keyword
8969            self.prev_token();
8970            Some(self.parse_query()?)
8971        } else {
8972            None
8973        };
8974
8975        // `WITH DATA` clause only applies if there is a query body.
8976        let with_data = if query.is_some() {
8977            self.maybe_parse_with_data()?
8978        } else {
8979            None
8980        };
8981
8982        Ok(CreateTableBuilder::new(table_name)
8983            .temporary(temporary)
8984            .unlogged(unlogged)
8985            .columns(columns)
8986            .constraints(constraints)
8987            .or_replace(or_replace)
8988            .if_not_exists(if_not_exists)
8989            .transient(transient)
8990            .volatile(volatile)
8991            .multiset(multiset)
8992            .fallback(fallback)
8993            .hive_distribution(hive_distribution)
8994            .hive_formats(hive_formats)
8995            .global(global)
8996            .query(query)
8997            .without_rowid(without_rowid)
8998            .like(like)
8999            .clone_clause(clone)
9000            .comment_after_column_def(comment_after_column_def)
9001            .order_by(order_by)
9002            .on_commit(on_commit)
9003            .on_cluster(on_cluster)
9004            .clustered_by(clustered_by)
9005            .partition_by(partition_by)
9006            .cluster_by(create_table_config.cluster_by)
9007            .inherits(create_table_config.inherits)
9008            .partition_of(partition_of)
9009            .for_values(for_values)
9010            .table_options(create_table_config.table_options)
9011            .primary_key(primary_key)
9012            .with_data(with_data)
9013            .strict(strict)
9014            .backup(backup)
9015            .diststyle(diststyle)
9016            .distkey(distkey)
9017            .sortkey(sortkey)
9018            .build())
9019    }
9020
9021    /// Parse `MULTISET` table-kind prefix on `CREATE TABLE`.
9022    fn maybe_parse_multiset(&mut self) -> Option<bool> {
9023        match self.parse_one_of_keywords(&[Keyword::SET, Keyword::MULTISET]) {
9024            Some(Keyword::MULTISET) => Some(true),
9025            Some(Keyword::SET) => Some(false),
9026            _ => None,
9027        }
9028    }
9029
9030    /// Parse `FALLBACK` option on a `CREATE TABLE` statement,
9031    fn maybe_parse_fallback(&mut self) -> Result<Option<bool>, ParserError> {
9032        if self.parse_keywords(&[Keyword::NO, Keyword::FALLBACK]) {
9033            Ok(Some(false))
9034        } else if self.parse_keyword(Keyword::FALLBACK) {
9035            Ok(Some(true))
9036        } else {
9037            Ok(None)
9038        }
9039    }
9040
9041    /// Parse [`WithData`] clause on `CREATE TABLE ... AS` statement.
9042    fn maybe_parse_with_data(&mut self) -> Result<Option<WithData>, ParserError> {
9043        let data = if self.parse_keywords(&[Keyword::WITH, Keyword::DATA]) {
9044            true
9045        } else if self.parse_keywords(&[Keyword::WITH, Keyword::NO, Keyword::DATA]) {
9046            false
9047        } else {
9048            return Ok(None);
9049        };
9050
9051        let statistics = if self.parse_keywords(&[Keyword::AND, Keyword::STATISTICS]) {
9052            Some(true)
9053        } else if self.parse_keywords(&[Keyword::AND, Keyword::NO, Keyword::STATISTICS]) {
9054            Some(false)
9055        } else {
9056            None
9057        };
9058
9059        Ok(Some(WithData { data, statistics }))
9060    }
9061
9062    fn maybe_parse_create_table_like(
9063        &mut self,
9064        allow_unquoted_hyphen: bool,
9065    ) -> Result<Option<CreateTableLikeKind>, ParserError> {
9066        let like = if self.dialect.supports_create_table_like_parenthesized()
9067            && self.consume_token(&Token::LParen)
9068        {
9069            if self.parse_keyword(Keyword::LIKE) {
9070                let name = self.parse_object_name(allow_unquoted_hyphen)?;
9071                let defaults = if self.parse_keywords(&[Keyword::INCLUDING, Keyword::DEFAULTS]) {
9072                    Some(CreateTableLikeDefaults::Including)
9073                } else if self.parse_keywords(&[Keyword::EXCLUDING, Keyword::DEFAULTS]) {
9074                    Some(CreateTableLikeDefaults::Excluding)
9075                } else {
9076                    None
9077                };
9078                self.expect_token(&Token::RParen)?;
9079                Some(CreateTableLikeKind::Parenthesized(CreateTableLike {
9080                    name,
9081                    defaults,
9082                }))
9083            } else {
9084                // Rollback the '(' it's probably the columns list
9085                self.prev_token();
9086                None
9087            }
9088        } else if self.parse_keyword(Keyword::LIKE) || self.parse_keyword(Keyword::ILIKE) {
9089            let name = self.parse_object_name(allow_unquoted_hyphen)?;
9090            Some(CreateTableLikeKind::Plain(CreateTableLike {
9091                name,
9092                defaults: None,
9093            }))
9094        } else {
9095            None
9096        };
9097        Ok(like)
9098    }
9099
9100    pub(crate) fn parse_create_table_on_commit(&mut self) -> Result<OnCommit, ParserError> {
9101        if self.parse_keywords(&[Keyword::DELETE, Keyword::ROWS]) {
9102            Ok(OnCommit::DeleteRows)
9103        } else if self.parse_keywords(&[Keyword::PRESERVE, Keyword::ROWS]) {
9104            Ok(OnCommit::PreserveRows)
9105        } else if self.parse_keywords(&[Keyword::DROP]) {
9106            Ok(OnCommit::Drop)
9107        } else {
9108            parser_err!(
9109                "Expecting DELETE ROWS, PRESERVE ROWS or DROP",
9110                self.peek_token_ref()
9111            )
9112        }
9113    }
9114
9115    /// Parse [ForValues] of a `PARTITION OF` clause.
9116    ///
9117    /// Parses: `FOR VALUES partition_bound_spec | DEFAULT`
9118    ///
9119    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtable.html)
9120    fn parse_partition_for_values(&mut self) -> Result<ForValues, ParserError> {
9121        if self.parse_keyword(Keyword::DEFAULT) {
9122            return Ok(ForValues::Default);
9123        }
9124
9125        self.expect_keywords(&[Keyword::FOR, Keyword::VALUES])?;
9126
9127        if self.parse_keyword(Keyword::IN) {
9128            // FOR VALUES IN (expr, ...)
9129            self.expect_token(&Token::LParen)?;
9130            if self.peek_token_ref().token == Token::RParen {
9131                return self.expected_ref("at least one value", self.peek_token_ref());
9132            }
9133            let values = self.parse_comma_separated(Parser::parse_expr)?;
9134            self.expect_token(&Token::RParen)?;
9135            Ok(ForValues::In(values))
9136        } else if self.parse_keyword(Keyword::FROM) {
9137            // FOR VALUES FROM (...) TO (...)
9138            self.expect_token(&Token::LParen)?;
9139            if self.peek_token_ref().token == Token::RParen {
9140                return self.expected_ref("at least one value", self.peek_token_ref());
9141            }
9142            let from = self.parse_comma_separated(Parser::parse_partition_bound_value)?;
9143            self.expect_token(&Token::RParen)?;
9144            self.expect_keyword(Keyword::TO)?;
9145            self.expect_token(&Token::LParen)?;
9146            if self.peek_token_ref().token == Token::RParen {
9147                return self.expected_ref("at least one value", self.peek_token_ref());
9148            }
9149            let to = self.parse_comma_separated(Parser::parse_partition_bound_value)?;
9150            self.expect_token(&Token::RParen)?;
9151            Ok(ForValues::From { from, to })
9152        } else if self.parse_keyword(Keyword::WITH) {
9153            // FOR VALUES WITH (MODULUS n, REMAINDER r)
9154            self.expect_token(&Token::LParen)?;
9155            self.expect_keyword(Keyword::MODULUS)?;
9156            let modulus = self.parse_literal_uint()?;
9157            self.expect_token(&Token::Comma)?;
9158            self.expect_keyword(Keyword::REMAINDER)?;
9159            let remainder = self.parse_literal_uint()?;
9160            self.expect_token(&Token::RParen)?;
9161            Ok(ForValues::With { modulus, remainder })
9162        } else {
9163            self.expected_ref("IN, FROM, or WITH after FOR VALUES", self.peek_token_ref())
9164        }
9165    }
9166
9167    /// Parse a single partition bound value (MINVALUE, MAXVALUE, or expression).
9168    fn parse_partition_bound_value(&mut self) -> Result<PartitionBoundValue, ParserError> {
9169        if self.parse_keyword(Keyword::MINVALUE) {
9170            Ok(PartitionBoundValue::MinValue)
9171        } else if self.parse_keyword(Keyword::MAXVALUE) {
9172            Ok(PartitionBoundValue::MaxValue)
9173        } else {
9174            Ok(PartitionBoundValue::Expr(self.parse_expr()?))
9175        }
9176    }
9177
9178    /// Parse configuration like inheritance, partitioning, clustering information during the table creation.
9179    ///
9180    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#syntax_2)
9181    /// [PostgreSQL](https://www.postgresql.org/docs/current/ddl-partitioning.html)
9182    /// [MySql](https://dev.mysql.com/doc/refman/8.4/en/create-table.html)
9183    fn parse_optional_create_table_config(
9184        &mut self,
9185    ) -> Result<CreateTableConfiguration, ParserError> {
9186        let mut table_options = CreateTableOptions::None;
9187
9188        let inherits = if self.parse_keyword(Keyword::INHERITS) {
9189            Some(self.parse_parenthesized_qualified_column_list(IsOptional::Mandatory, false)?)
9190        } else {
9191            None
9192        };
9193
9194        // PostgreSQL supports `WITH ( options )`, before `AS`
9195        let with_options = self.parse_options(Keyword::WITH)?;
9196        if !with_options.is_empty() {
9197            table_options = CreateTableOptions::With(with_options)
9198        }
9199
9200        let table_properties = self.parse_options(Keyword::TBLPROPERTIES)?;
9201        if !table_properties.is_empty() {
9202            table_options = CreateTableOptions::TableProperties(table_properties);
9203        }
9204        let partition_by = if dialect_of!(self is BigQueryDialect | PostgreSqlDialect | GenericDialect)
9205            && self.parse_keywords(&[Keyword::PARTITION, Keyword::BY])
9206        {
9207            Some(Box::new(self.parse_expr()?))
9208        } else {
9209            None
9210        };
9211
9212        let mut cluster_by = None;
9213        if dialect_of!(self is BigQueryDialect | GenericDialect) {
9214            if self.parse_keywords(&[Keyword::CLUSTER, Keyword::BY]) {
9215                cluster_by = Some(WrappedCollection::NoWrapping(
9216                    self.parse_comma_separated(|p| p.parse_expr())?,
9217                ));
9218            };
9219
9220            if let Token::Word(word) = &self.peek_token_ref().token {
9221                if word.keyword == Keyword::OPTIONS {
9222                    table_options =
9223                        CreateTableOptions::Options(self.parse_options(Keyword::OPTIONS)?)
9224                }
9225            };
9226        }
9227
9228        if !dialect_of!(self is HiveDialect) && table_options == CreateTableOptions::None {
9229            let plain_options = self.parse_plain_options()?;
9230            if !plain_options.is_empty() {
9231                table_options = CreateTableOptions::Plain(plain_options)
9232            }
9233        };
9234
9235        Ok(CreateTableConfiguration {
9236            partition_by,
9237            cluster_by,
9238            inherits,
9239            table_options,
9240        })
9241    }
9242
9243    fn parse_plain_option(&mut self) -> Result<Option<SqlOption>, ParserError> {
9244        // Single parameter option
9245        // <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9246        if self.parse_keywords(&[Keyword::START, Keyword::TRANSACTION]) {
9247            return Ok(Some(SqlOption::Ident(Ident::new("START TRANSACTION"))));
9248        }
9249
9250        // Custom option
9251        // <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9252        if self.parse_keywords(&[Keyword::COMMENT]) {
9253            let has_eq = self.consume_token(&Token::Eq);
9254            let value = self.next_token();
9255
9256            let comment = match (has_eq, value.token) {
9257                (true, Token::SingleQuotedString(s)) => {
9258                    Ok(Some(SqlOption::Comment(CommentDef::WithEq(s))))
9259                }
9260                (false, Token::SingleQuotedString(s)) => {
9261                    Ok(Some(SqlOption::Comment(CommentDef::WithoutEq(s))))
9262                }
9263                (_, token) => {
9264                    self.expected("Token::SingleQuotedString", TokenWithSpan::wrap(token))
9265                }
9266            };
9267            return comment;
9268        }
9269
9270        // <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9271        // <https://clickhouse.com/docs/sql-reference/statements/create/table>
9272        if self.parse_keywords(&[Keyword::ENGINE]) {
9273            let _ = self.consume_token(&Token::Eq);
9274            let value = self.next_token();
9275
9276            let engine = match value.token {
9277                Token::Word(w) => {
9278                    let parameters = if self.peek_token_ref().token == Token::LParen {
9279                        self.parse_parenthesized_identifiers()?
9280                    } else {
9281                        vec![]
9282                    };
9283
9284                    Ok(Some(SqlOption::NamedParenthesizedList(
9285                        NamedParenthesizedList {
9286                            key: Ident::new("ENGINE"),
9287                            name: Some(Ident::new(w.value)),
9288                            values: parameters,
9289                        },
9290                    )))
9291                }
9292                _ => {
9293                    return self.expected("Token::Word", value)?;
9294                }
9295            };
9296
9297            return engine;
9298        }
9299
9300        // <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9301        if self.parse_keywords(&[Keyword::TABLESPACE]) {
9302            let _ = self.consume_token(&Token::Eq);
9303            let value = self.next_token();
9304
9305            let tablespace = match value.token {
9306                Token::Word(Word { value: name, .. }) | Token::SingleQuotedString(name) => {
9307                    let storage = match self.parse_keyword(Keyword::STORAGE) {
9308                        true => {
9309                            let _ = self.consume_token(&Token::Eq);
9310                            let storage_token = self.next_token();
9311                            match &storage_token.token {
9312                                Token::Word(w) => match w.value.to_uppercase().as_str() {
9313                                    "DISK" => Some(StorageType::Disk),
9314                                    "MEMORY" => Some(StorageType::Memory),
9315                                    _ => self
9316                                        .expected("Storage type (DISK or MEMORY)", storage_token)?,
9317                                },
9318                                _ => self.expected("Token::Word", storage_token)?,
9319                            }
9320                        }
9321                        false => None,
9322                    };
9323
9324                    Ok(Some(SqlOption::TableSpace(TablespaceOption {
9325                        name,
9326                        storage,
9327                    })))
9328                }
9329                _ => {
9330                    return self.expected("Token::Word", value)?;
9331                }
9332            };
9333
9334            return tablespace;
9335        }
9336
9337        // <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9338        if self.parse_keyword(Keyword::UNION) {
9339            let _ = self.consume_token(&Token::Eq);
9340            let value = self.next_token();
9341
9342            match value.token {
9343                Token::LParen => {
9344                    let tables: Vec<Ident> =
9345                        self.parse_comma_separated0(Parser::parse_identifier, Token::RParen)?;
9346                    self.expect_token(&Token::RParen)?;
9347
9348                    return Ok(Some(SqlOption::NamedParenthesizedList(
9349                        NamedParenthesizedList {
9350                            key: Ident::new("UNION"),
9351                            name: None,
9352                            values: tables,
9353                        },
9354                    )));
9355                }
9356                _ => {
9357                    return self.expected("Token::LParen", value)?;
9358                }
9359            }
9360        }
9361
9362        // Key/Value parameter option
9363        let key = if self.parse_keywords(&[Keyword::DEFAULT, Keyword::CHARSET]) {
9364            Ident::new("DEFAULT CHARSET")
9365        } else if self.parse_keyword(Keyword::CHARSET) {
9366            Ident::new("CHARSET")
9367        } else if self.parse_keywords(&[Keyword::DEFAULT, Keyword::CHARACTER, Keyword::SET]) {
9368            Ident::new("DEFAULT CHARACTER SET")
9369        } else if self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET]) {
9370            Ident::new("CHARACTER SET")
9371        } else if self.parse_keywords(&[Keyword::DEFAULT, Keyword::COLLATE]) {
9372            Ident::new("DEFAULT COLLATE")
9373        } else if self.parse_keyword(Keyword::COLLATE) {
9374            Ident::new("COLLATE")
9375        } else if self.parse_keywords(&[Keyword::DATA, Keyword::DIRECTORY]) {
9376            Ident::new("DATA DIRECTORY")
9377        } else if self.parse_keywords(&[Keyword::INDEX, Keyword::DIRECTORY]) {
9378            Ident::new("INDEX DIRECTORY")
9379        } else if self.parse_keyword(Keyword::KEY_BLOCK_SIZE) {
9380            Ident::new("KEY_BLOCK_SIZE")
9381        } else if self.parse_keyword(Keyword::ROW_FORMAT) {
9382            Ident::new("ROW_FORMAT")
9383        } else if self.parse_keyword(Keyword::PACK_KEYS) {
9384            Ident::new("PACK_KEYS")
9385        } else if self.parse_keyword(Keyword::STATS_AUTO_RECALC) {
9386            Ident::new("STATS_AUTO_RECALC")
9387        } else if self.parse_keyword(Keyword::STATS_PERSISTENT) {
9388            Ident::new("STATS_PERSISTENT")
9389        } else if self.parse_keyword(Keyword::STATS_SAMPLE_PAGES) {
9390            Ident::new("STATS_SAMPLE_PAGES")
9391        } else if self.parse_keyword(Keyword::DELAY_KEY_WRITE) {
9392            Ident::new("DELAY_KEY_WRITE")
9393        } else if self.parse_keyword(Keyword::COMPRESSION) {
9394            Ident::new("COMPRESSION")
9395        } else if self.parse_keyword(Keyword::ENCRYPTION) {
9396            Ident::new("ENCRYPTION")
9397        } else if self.parse_keyword(Keyword::MAX_ROWS) {
9398            Ident::new("MAX_ROWS")
9399        } else if self.parse_keyword(Keyword::MIN_ROWS) {
9400            Ident::new("MIN_ROWS")
9401        } else if self.parse_keyword(Keyword::AUTOEXTEND_SIZE) {
9402            Ident::new("AUTOEXTEND_SIZE")
9403        } else if self.parse_keyword(Keyword::AVG_ROW_LENGTH) {
9404            Ident::new("AVG_ROW_LENGTH")
9405        } else if self.parse_keyword(Keyword::CHECKSUM) {
9406            Ident::new("CHECKSUM")
9407        } else if self.parse_keyword(Keyword::CONNECTION) {
9408            Ident::new("CONNECTION")
9409        } else if self.parse_keyword(Keyword::ENGINE_ATTRIBUTE) {
9410            Ident::new("ENGINE_ATTRIBUTE")
9411        } else if self.parse_keyword(Keyword::PASSWORD) {
9412            Ident::new("PASSWORD")
9413        } else if self.parse_keyword(Keyword::SECONDARY_ENGINE_ATTRIBUTE) {
9414            Ident::new("SECONDARY_ENGINE_ATTRIBUTE")
9415        } else if self.parse_keyword(Keyword::INSERT_METHOD) {
9416            Ident::new("INSERT_METHOD")
9417        } else if self.parse_keyword(Keyword::AUTO_INCREMENT) {
9418            Ident::new("AUTO_INCREMENT")
9419        } else {
9420            return Ok(None);
9421        };
9422
9423        let _ = self.consume_token(&Token::Eq);
9424
9425        let value = match self
9426            .maybe_parse(|parser| parser.parse_value())?
9427            .map(Expr::Value)
9428        {
9429            Some(expr) => expr,
9430            None => Expr::Identifier(self.parse_identifier()?),
9431        };
9432
9433        Ok(Some(SqlOption::KeyValue { key, value }))
9434    }
9435
9436    /// Parse plain options.
9437    pub fn parse_plain_options(&mut self) -> Result<Vec<SqlOption>, ParserError> {
9438        let mut options = Vec::new();
9439
9440        while let Some(option) = self.parse_plain_option()? {
9441            options.push(option);
9442            // Some dialects support comma-separated options; it shouldn't introduce ambiguity to
9443            // consume it for all dialects.
9444            let _ = self.consume_token(&Token::Comma);
9445        }
9446
9447        Ok(options)
9448    }
9449
9450    /// Parse optional inline comment.
9451    pub fn parse_optional_inline_comment(&mut self) -> Result<Option<CommentDef>, ParserError> {
9452        let comment = if self.parse_keyword(Keyword::COMMENT) {
9453            let has_eq = self.consume_token(&Token::Eq);
9454            let comment = self.parse_comment_value()?;
9455            Some(if has_eq {
9456                CommentDef::WithEq(comment)
9457            } else {
9458                CommentDef::WithoutEq(comment)
9459            })
9460        } else {
9461            None
9462        };
9463        Ok(comment)
9464    }
9465
9466    /// Parse comment value.
9467    pub fn parse_comment_value(&mut self) -> Result<String, ParserError> {
9468        let next_token = self.next_token();
9469        let value = match next_token.token {
9470            Token::SingleQuotedString(str) => str,
9471            Token::DollarQuotedString(str) => str.value,
9472            _ => self.expected("string literal", next_token)?,
9473        };
9474        Ok(value)
9475    }
9476
9477    /// Parse optional procedure parameters.
9478    pub fn parse_optional_procedure_parameters(
9479        &mut self,
9480    ) -> Result<Option<Vec<ProcedureParam>>, ParserError> {
9481        let mut params = vec![];
9482        if !self.consume_token(&Token::LParen) || self.consume_token(&Token::RParen) {
9483            return Ok(Some(params));
9484        }
9485        loop {
9486            if let Token::Word(_) = &self.peek_token_ref().token {
9487                params.push(self.parse_procedure_param()?)
9488            }
9489            let comma = self.consume_token(&Token::Comma);
9490            if self.consume_token(&Token::RParen) {
9491                // allow a trailing comma, even though it's not in standard
9492                break;
9493            } else if !comma {
9494                return self.expected_ref(
9495                    "',' or ')' after parameter definition",
9496                    self.peek_token_ref(),
9497                );
9498            }
9499        }
9500        Ok(Some(params))
9501    }
9502
9503    /// Parse columns and constraints.
9504    pub fn parse_columns(&mut self) -> Result<(Vec<ColumnDef>, Vec<TableConstraint>), ParserError> {
9505        let mut columns = vec![];
9506        let mut constraints = vec![];
9507        if !self.consume_token(&Token::LParen) || self.consume_token(&Token::RParen) {
9508            return Ok((columns, constraints));
9509        }
9510
9511        loop {
9512            if let Some(constraint) = self.parse_optional_table_constraint()? {
9513                constraints.push(constraint);
9514            } else if let Token::Word(_) = &self.peek_token_ref().token {
9515                columns.push(self.parse_column_def()?);
9516            } else if matches!(&self.peek_token_ref().token, Token::SingleQuotedString(_))
9517                && self.dialect.supports_string_literal_column_names()
9518            {
9519                columns.push(self.parse_column_def()?);
9520            } else {
9521                return self.expected_ref(
9522                    "column name or constraint definition",
9523                    self.peek_token_ref(),
9524                );
9525            }
9526
9527            let comma = self.consume_token(&Token::Comma);
9528            let rparen = self.peek_token_ref().token == Token::RParen;
9529
9530            if !comma && !rparen {
9531                return self
9532                    .expected_ref("',' or ')' after column definition", self.peek_token_ref());
9533            };
9534
9535            if rparen
9536                && (!comma
9537                    || self.dialect.supports_column_definition_trailing_commas()
9538                    || self.options.trailing_commas)
9539            {
9540                let _ = self.consume_token(&Token::RParen);
9541                break;
9542            }
9543        }
9544
9545        Ok((columns, constraints))
9546    }
9547
9548    /// Parse procedure parameter.
9549    pub fn parse_procedure_param(&mut self) -> Result<ProcedureParam, ParserError> {
9550        let mode = if self.parse_keyword(Keyword::IN) {
9551            Some(ArgMode::In)
9552        } else if self.parse_keyword(Keyword::OUT) {
9553            Some(ArgMode::Out)
9554        } else if self.parse_keyword(Keyword::INOUT) {
9555            Some(ArgMode::InOut)
9556        } else {
9557            None
9558        };
9559        let name = self.parse_identifier()?;
9560        let data_type = self.parse_data_type()?;
9561        let default = if self.consume_token(&Token::Eq) {
9562            Some(self.parse_expr()?)
9563        } else {
9564            None
9565        };
9566
9567        Ok(ProcedureParam {
9568            name,
9569            data_type,
9570            mode,
9571            default,
9572        })
9573    }
9574
9575    /// Parse column definition.
9576    pub fn parse_column_def(&mut self) -> Result<ColumnDef, ParserError> {
9577        self.parse_column_def_inner(false)
9578    }
9579
9580    fn parse_column_def_inner(
9581        &mut self,
9582        optional_data_type: bool,
9583    ) -> Result<ColumnDef, ParserError> {
9584        let col_name = self.parse_identifier()?;
9585        let data_type = if self.is_column_type_sqlite_unspecified() {
9586            DataType::Unspecified
9587        } else if optional_data_type {
9588            self.maybe_parse(|parser| parser.parse_data_type())?
9589                .unwrap_or(DataType::Unspecified)
9590        } else {
9591            self.parse_data_type()?
9592        };
9593        let mut options = vec![];
9594        loop {
9595            if self.parse_keyword(Keyword::CONSTRAINT) {
9596                let name = Some(self.parse_identifier()?);
9597                if let Some(option) = self.parse_optional_column_option()? {
9598                    options.push(ColumnOptionDef { name, option });
9599                } else {
9600                    return self.expected_ref(
9601                        "constraint details after CONSTRAINT <name>",
9602                        self.peek_token_ref(),
9603                    );
9604                }
9605            } else if let Some(option) = self.parse_optional_column_option()? {
9606                options.push(ColumnOptionDef { name: None, option });
9607            } else {
9608                break;
9609            };
9610        }
9611        Ok(ColumnDef {
9612            name: col_name,
9613            data_type,
9614            options,
9615        })
9616    }
9617
9618    fn is_column_type_sqlite_unspecified(&mut self) -> bool {
9619        if dialect_of!(self is SQLiteDialect) {
9620            match &self.peek_token_ref().token {
9621                Token::Word(word) => matches!(
9622                    word.keyword,
9623                    Keyword::CONSTRAINT
9624                        | Keyword::PRIMARY
9625                        | Keyword::NOT
9626                        | Keyword::UNIQUE
9627                        | Keyword::CHECK
9628                        | Keyword::DEFAULT
9629                        | Keyword::COLLATE
9630                        | Keyword::REFERENCES
9631                        | Keyword::GENERATED
9632                        | Keyword::AS
9633                ),
9634                _ => true, // e.g. comma immediately after column name
9635            }
9636        } else {
9637            false
9638        }
9639    }
9640
9641    /// Parse optional column option.
9642    pub fn parse_optional_column_option(&mut self) -> Result<Option<ColumnOption>, ParserError> {
9643        if let Some(option) = self.dialect.parse_column_option(self)? {
9644            return option;
9645        }
9646
9647        self.with_state(
9648            ColumnDefinition,
9649            |parser| -> Result<Option<ColumnOption>, ParserError> {
9650                parser.parse_optional_column_option_inner()
9651            },
9652        )
9653    }
9654
9655    fn parse_optional_column_option_inner(&mut self) -> Result<Option<ColumnOption>, ParserError> {
9656        if self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET]) {
9657            Ok(Some(ColumnOption::CharacterSet(
9658                self.parse_object_name(false)?,
9659            )))
9660        } else if self.parse_keywords(&[Keyword::COLLATE]) {
9661            Ok(Some(ColumnOption::Collation(
9662                self.parse_object_name(false)?,
9663            )))
9664        } else if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) {
9665            Ok(Some(ColumnOption::NotNull))
9666        } else if self.parse_keywords(&[Keyword::COMMENT]) {
9667            Ok(Some(ColumnOption::Comment(self.parse_comment_value()?)))
9668        } else if self.parse_keyword(Keyword::NULL) {
9669            Ok(Some(ColumnOption::Null))
9670        } else if self.parse_keyword(Keyword::DEFAULT) {
9671            Ok(Some(ColumnOption::Default(self.parse_expr()?)))
9672        } else if dialect_of!(self is ClickHouseDialect| GenericDialect)
9673            && self.parse_keyword(Keyword::MATERIALIZED)
9674        {
9675            Ok(Some(ColumnOption::Materialized(self.parse_expr()?)))
9676        } else if dialect_of!(self is ClickHouseDialect| GenericDialect)
9677            && self.parse_keyword(Keyword::ALIAS)
9678        {
9679            Ok(Some(ColumnOption::Alias(self.parse_expr()?)))
9680        } else if dialect_of!(self is ClickHouseDialect| GenericDialect)
9681            && self.parse_keyword(Keyword::EPHEMERAL)
9682        {
9683            // The expression is optional for the EPHEMERAL syntax, so we need to check
9684            // if the column definition has remaining tokens before parsing the expression.
9685            if matches!(self.peek_token_ref().token, Token::Comma | Token::RParen) {
9686                Ok(Some(ColumnOption::Ephemeral(None)))
9687            } else {
9688                Ok(Some(ColumnOption::Ephemeral(Some(self.parse_expr()?))))
9689            }
9690        } else if self.parse_keywords(&[Keyword::PRIMARY, Keyword::KEY]) {
9691            let characteristics = self.parse_constraint_characteristics()?;
9692            Ok(Some(
9693                PrimaryKeyConstraint {
9694                    name: None,
9695                    index_name: None,
9696                    index_type: None,
9697                    columns: vec![],
9698                    include: vec![],
9699                    index_options: vec![],
9700                    characteristics,
9701                }
9702                .into(),
9703            ))
9704        } else if self.parse_keyword(Keyword::UNIQUE) {
9705            let index_type_display =
9706                if self.dialect.supports_key_column_option() && self.parse_keyword(Keyword::KEY) {
9707                    KeyOrIndexDisplay::Key
9708                } else {
9709                    KeyOrIndexDisplay::None
9710                };
9711            let characteristics = self.parse_constraint_characteristics()?;
9712            Ok(Some(
9713                UniqueConstraint {
9714                    name: None,
9715                    index_name: None,
9716                    index_type_display,
9717                    index_type: None,
9718                    columns: vec![],
9719                    include: vec![],
9720                    index_options: vec![],
9721                    characteristics,
9722                    nulls_distinct: NullsDistinctOption::None,
9723                }
9724                .into(),
9725            ))
9726        } else if self.dialect.supports_key_column_option() && self.parse_keyword(Keyword::KEY) {
9727            // In MySQL, `KEY` in a column definition is shorthand for `PRIMARY KEY`.
9728            // See: https://dev.mysql.com/doc/refman/8.4/en/create-table.html
9729            let characteristics = self.parse_constraint_characteristics()?;
9730            Ok(Some(
9731                PrimaryKeyConstraint {
9732                    name: None,
9733                    index_name: None,
9734                    index_type: None,
9735                    columns: vec![],
9736                    include: vec![],
9737                    index_options: vec![],
9738                    characteristics,
9739                }
9740                .into(),
9741            ))
9742        } else if self.parse_keyword(Keyword::REFERENCES) {
9743            let foreign_table = self.parse_object_name(false)?;
9744            // PostgreSQL allows omitting the column list and
9745            // uses the primary key column of the foreign table by default
9746            let referred_columns = self.parse_parenthesized_column_list(Optional, false)?;
9747            let mut match_kind = None;
9748            let mut on_delete = None;
9749            let mut on_update = None;
9750            loop {
9751                if match_kind.is_none() && self.parse_keyword(Keyword::MATCH) {
9752                    match_kind = Some(self.parse_match_kind()?);
9753                } else if on_delete.is_none()
9754                    && self.parse_keywords(&[Keyword::ON, Keyword::DELETE])
9755                {
9756                    on_delete = Some(self.parse_referential_action()?);
9757                } else if on_update.is_none()
9758                    && self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
9759                {
9760                    on_update = Some(self.parse_referential_action()?);
9761                } else {
9762                    break;
9763                }
9764            }
9765            let characteristics = self.parse_constraint_characteristics()?;
9766
9767            Ok(Some(
9768                ForeignKeyConstraint {
9769                    name: None,       // Column-level constraints don't have names
9770                    index_name: None, // Not applicable for column-level constraints
9771                    columns: vec![],  // Not applicable for column-level constraints
9772                    foreign_table,
9773                    referred_columns,
9774                    on_delete,
9775                    on_update,
9776                    match_kind,
9777                    characteristics,
9778                }
9779                .into(),
9780            ))
9781        } else if self.parse_keyword(Keyword::CHECK) {
9782            self.expect_token(&Token::LParen)?;
9783            // since `CHECK` requires parentheses, we can parse the inner expression in ParserState::Normal
9784            let expr: Expr = self.with_state(ParserState::Normal, |p| p.parse_expr())?;
9785            self.expect_token(&Token::RParen)?;
9786            let no_inherit = self.parse_keywords(&[Keyword::NO, Keyword::INHERIT]);
9787
9788            let enforced = if self.parse_keyword(Keyword::ENFORCED) {
9789                Some(true)
9790            } else if self.parse_keywords(&[Keyword::NOT, Keyword::ENFORCED]) {
9791                Some(false)
9792            } else {
9793                None
9794            };
9795
9796            Ok(Some(
9797                CheckConstraint {
9798                    name: None, // Column-level check constraints don't have names
9799                    expr: Box::new(expr),
9800                    no_inherit,
9801                    enforced,
9802                }
9803                .into(),
9804            ))
9805        } else if self.parse_keyword(Keyword::AUTO_INCREMENT)
9806            && dialect_of!(self is MySqlDialect | GenericDialect)
9807        {
9808            // Support AUTO_INCREMENT for MySQL
9809            Ok(Some(ColumnOption::DialectSpecific(vec![
9810                Token::make_keyword("AUTO_INCREMENT"),
9811            ])))
9812        } else if self.parse_keyword(Keyword::AUTOINCREMENT)
9813            && dialect_of!(self is SQLiteDialect |  GenericDialect)
9814        {
9815            // Support AUTOINCREMENT for SQLite
9816            Ok(Some(ColumnOption::DialectSpecific(vec![
9817                Token::make_keyword("AUTOINCREMENT"),
9818            ])))
9819        } else if self.parse_keyword(Keyword::ASC)
9820            && self.dialect.supports_asc_desc_in_column_definition()
9821        {
9822            // Support ASC for SQLite
9823            Ok(Some(ColumnOption::DialectSpecific(vec![
9824                Token::make_keyword("ASC"),
9825            ])))
9826        } else if self.parse_keyword(Keyword::DESC)
9827            && self.dialect.supports_asc_desc_in_column_definition()
9828        {
9829            // Support DESC for SQLite
9830            Ok(Some(ColumnOption::DialectSpecific(vec![
9831                Token::make_keyword("DESC"),
9832            ])))
9833        } else if self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
9834            && dialect_of!(self is MySqlDialect | GenericDialect)
9835        {
9836            let expr = self.parse_expr()?;
9837            Ok(Some(ColumnOption::OnUpdate(expr)))
9838        } else if self.parse_keyword(Keyword::GENERATED) {
9839            self.parse_optional_column_option_generated()
9840        } else if dialect_of!(self is BigQueryDialect | GenericDialect)
9841            && self.parse_keyword(Keyword::OPTIONS)
9842        {
9843            self.prev_token();
9844            Ok(Some(ColumnOption::Options(
9845                self.parse_options(Keyword::OPTIONS)?,
9846            )))
9847        } else if self.parse_keyword(Keyword::AS)
9848            && dialect_of!(self is MySqlDialect | SQLiteDialect | DuckDbDialect | GenericDialect)
9849        {
9850            self.parse_optional_column_option_as()
9851        } else if self.parse_keyword(Keyword::SRID)
9852            && dialect_of!(self is MySqlDialect | GenericDialect)
9853        {
9854            Ok(Some(ColumnOption::Srid(Box::new(self.parse_expr()?))))
9855        } else if self.parse_keyword(Keyword::IDENTITY)
9856            && dialect_of!(self is MsSqlDialect | GenericDialect)
9857        {
9858            let parameters = if self.consume_token(&Token::LParen) {
9859                let seed = self.parse_number()?;
9860                self.expect_token(&Token::Comma)?;
9861                let increment = self.parse_number()?;
9862                self.expect_token(&Token::RParen)?;
9863
9864                Some(IdentityPropertyFormatKind::FunctionCall(
9865                    IdentityParameters { seed, increment },
9866                ))
9867            } else {
9868                None
9869            };
9870            Ok(Some(ColumnOption::Identity(
9871                IdentityPropertyKind::Identity(IdentityProperty {
9872                    parameters,
9873                    order: None,
9874                }),
9875            )))
9876        } else if dialect_of!(self is SQLiteDialect | GenericDialect)
9877            && self.parse_keywords(&[Keyword::ON, Keyword::CONFLICT])
9878        {
9879            // Support ON CONFLICT for SQLite
9880            Ok(Some(ColumnOption::OnConflict(
9881                self.expect_one_of_keywords(&[
9882                    Keyword::ROLLBACK,
9883                    Keyword::ABORT,
9884                    Keyword::FAIL,
9885                    Keyword::IGNORE,
9886                    Keyword::REPLACE,
9887                ])?,
9888            )))
9889        } else if self.parse_keyword(Keyword::INVISIBLE) {
9890            Ok(Some(ColumnOption::Invisible))
9891        } else {
9892            Ok(None)
9893        }
9894    }
9895
9896    pub(crate) fn parse_tag(&mut self) -> Result<Tag, ParserError> {
9897        let name = self.parse_object_name(false)?;
9898        self.expect_token(&Token::Eq)?;
9899        let value = self.parse_literal_string()?;
9900
9901        Ok(Tag::new(name, value))
9902    }
9903
9904    fn parse_optional_column_option_generated(
9905        &mut self,
9906    ) -> Result<Option<ColumnOption>, ParserError> {
9907        if self.parse_keywords(&[Keyword::ALWAYS, Keyword::AS, Keyword::IDENTITY]) {
9908            let mut sequence_options = vec![];
9909            if self.expect_token(&Token::LParen).is_ok() {
9910                sequence_options = self.parse_create_sequence_options()?;
9911                self.expect_token(&Token::RParen)?;
9912            }
9913            Ok(Some(ColumnOption::Generated {
9914                generated_as: GeneratedAs::Always,
9915                sequence_options: Some(sequence_options),
9916                generation_expr: None,
9917                generation_expr_mode: None,
9918                generated_keyword: true,
9919            }))
9920        } else if self.parse_keywords(&[
9921            Keyword::BY,
9922            Keyword::DEFAULT,
9923            Keyword::AS,
9924            Keyword::IDENTITY,
9925        ]) {
9926            let mut sequence_options = vec![];
9927            if self.expect_token(&Token::LParen).is_ok() {
9928                sequence_options = self.parse_create_sequence_options()?;
9929                self.expect_token(&Token::RParen)?;
9930            }
9931            Ok(Some(ColumnOption::Generated {
9932                generated_as: GeneratedAs::ByDefault,
9933                sequence_options: Some(sequence_options),
9934                generation_expr: None,
9935                generation_expr_mode: None,
9936                generated_keyword: true,
9937            }))
9938        } else if self.parse_keywords(&[Keyword::ALWAYS, Keyword::AS]) {
9939            if self.expect_token(&Token::LParen).is_ok() {
9940                let expr: Expr = self.with_state(ParserState::Normal, |p| p.parse_expr())?;
9941                self.expect_token(&Token::RParen)?;
9942                let (gen_as, expr_mode) = if self.parse_keywords(&[Keyword::STORED]) {
9943                    Ok((
9944                        GeneratedAs::ExpStored,
9945                        Some(GeneratedExpressionMode::Stored),
9946                    ))
9947                } else if dialect_of!(self is PostgreSqlDialect) {
9948                    // Postgres' AS IDENTITY branches are above, this one needs STORED
9949                    self.expected_ref("STORED", self.peek_token_ref())
9950                } else if self.parse_keywords(&[Keyword::VIRTUAL]) {
9951                    Ok((GeneratedAs::Always, Some(GeneratedExpressionMode::Virtual)))
9952                } else {
9953                    Ok((GeneratedAs::Always, None))
9954                }?;
9955
9956                Ok(Some(ColumnOption::Generated {
9957                    generated_as: gen_as,
9958                    sequence_options: None,
9959                    generation_expr: Some(expr),
9960                    generation_expr_mode: expr_mode,
9961                    generated_keyword: true,
9962                }))
9963            } else {
9964                Ok(None)
9965            }
9966        } else {
9967            Ok(None)
9968        }
9969    }
9970
9971    fn parse_optional_column_option_as(&mut self) -> Result<Option<ColumnOption>, ParserError> {
9972        // Some DBs allow 'AS (expr)', shorthand for GENERATED ALWAYS AS
9973        self.expect_token(&Token::LParen)?;
9974        let expr = self.parse_expr()?;
9975        self.expect_token(&Token::RParen)?;
9976
9977        let (gen_as, expr_mode) = if self.parse_keywords(&[Keyword::STORED]) {
9978            (
9979                GeneratedAs::ExpStored,
9980                Some(GeneratedExpressionMode::Stored),
9981            )
9982        } else if self.parse_keywords(&[Keyword::VIRTUAL]) {
9983            (GeneratedAs::Always, Some(GeneratedExpressionMode::Virtual))
9984        } else {
9985            (GeneratedAs::Always, None)
9986        };
9987
9988        Ok(Some(ColumnOption::Generated {
9989            generated_as: gen_as,
9990            sequence_options: None,
9991            generation_expr: Some(expr),
9992            generation_expr_mode: expr_mode,
9993            generated_keyword: false,
9994        }))
9995    }
9996
9997    /// Parse optional `CLUSTERED BY` clause for Hive/Generic dialects.
9998    pub fn parse_optional_clustered_by(&mut self) -> Result<Option<ClusteredBy>, ParserError> {
9999        let clustered_by = if dialect_of!(self is HiveDialect|GenericDialect)
10000            && self.parse_keywords(&[Keyword::CLUSTERED, Keyword::BY])
10001        {
10002            let columns = self.parse_parenthesized_column_list(Mandatory, false)?;
10003
10004            let sorted_by = if self.parse_keywords(&[Keyword::SORTED, Keyword::BY]) {
10005                self.expect_token(&Token::LParen)?;
10006                let sorted_by_columns = self.parse_comma_separated(|p| p.parse_order_by_expr())?;
10007                self.expect_token(&Token::RParen)?;
10008                Some(sorted_by_columns)
10009            } else {
10010                None
10011            };
10012
10013            self.expect_keyword_is(Keyword::INTO)?;
10014            let num_buckets = self.parse_number_value()?.value;
10015            self.expect_keyword_is(Keyword::BUCKETS)?;
10016            Some(ClusteredBy {
10017                columns,
10018                sorted_by,
10019                num_buckets,
10020            })
10021        } else {
10022            None
10023        };
10024        Ok(clustered_by)
10025    }
10026
10027    /// Parse a referential action used in foreign key clauses.
10028    ///
10029    /// Recognized forms: `RESTRICT`, `CASCADE`, `SET NULL`, `NO ACTION`, `SET DEFAULT`.
10030    pub fn parse_referential_action(&mut self) -> Result<ReferentialAction, ParserError> {
10031        if self.parse_keyword(Keyword::RESTRICT) {
10032            Ok(ReferentialAction::Restrict)
10033        } else if self.parse_keyword(Keyword::CASCADE) {
10034            Ok(ReferentialAction::Cascade)
10035        } else if self.parse_keywords(&[Keyword::SET, Keyword::NULL]) {
10036            Ok(ReferentialAction::SetNull)
10037        } else if self.parse_keywords(&[Keyword::NO, Keyword::ACTION]) {
10038            Ok(ReferentialAction::NoAction)
10039        } else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
10040            Ok(ReferentialAction::SetDefault)
10041        } else {
10042            self.expected_ref(
10043                "one of RESTRICT, CASCADE, SET NULL, NO ACTION or SET DEFAULT",
10044                self.peek_token_ref(),
10045            )
10046        }
10047    }
10048
10049    /// Parse a `MATCH` kind for constraint references: `FULL`, `PARTIAL`, or `SIMPLE`.
10050    pub fn parse_match_kind(&mut self) -> Result<ConstraintReferenceMatchKind, ParserError> {
10051        if self.parse_keyword(Keyword::FULL) {
10052            Ok(ConstraintReferenceMatchKind::Full)
10053        } else if self.parse_keyword(Keyword::PARTIAL) {
10054            Ok(ConstraintReferenceMatchKind::Partial)
10055        } else if self.parse_keyword(Keyword::SIMPLE) {
10056            Ok(ConstraintReferenceMatchKind::Simple)
10057        } else {
10058            self.expected_ref("one of FULL, PARTIAL or SIMPLE", self.peek_token_ref())
10059        }
10060    }
10061
10062    /// Parse `index_name [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]`
10063    /// after `{ PRIMARY KEY | UNIQUE } USING INDEX`.
10064    fn parse_constraint_using_index(
10065        &mut self,
10066        name: Option<Ident>,
10067    ) -> Result<ConstraintUsingIndex, ParserError> {
10068        let index_name = self.parse_identifier()?;
10069        let characteristics = self.parse_constraint_characteristics()?;
10070        Ok(ConstraintUsingIndex {
10071            name,
10072            index_name,
10073            characteristics,
10074        })
10075    }
10076
10077    /// Parse optional constraint characteristics such as `DEFERRABLE`, `INITIALLY` and `ENFORCED`.
10078    pub fn parse_constraint_characteristics(
10079        &mut self,
10080    ) -> Result<Option<ConstraintCharacteristics>, ParserError> {
10081        let mut cc = ConstraintCharacteristics::default();
10082
10083        loop {
10084            if cc.deferrable.is_none() && self.parse_keywords(&[Keyword::NOT, Keyword::DEFERRABLE])
10085            {
10086                cc.deferrable = Some(false);
10087            } else if cc.deferrable.is_none() && self.parse_keyword(Keyword::DEFERRABLE) {
10088                cc.deferrable = Some(true);
10089            } else if cc.initially.is_none() && self.parse_keyword(Keyword::INITIALLY) {
10090                if self.parse_keyword(Keyword::DEFERRED) {
10091                    cc.initially = Some(DeferrableInitial::Deferred);
10092                } else if self.parse_keyword(Keyword::IMMEDIATE) {
10093                    cc.initially = Some(DeferrableInitial::Immediate);
10094                } else {
10095                    self.expected_ref("one of DEFERRED or IMMEDIATE", self.peek_token_ref())?;
10096                }
10097            } else if cc.enforced.is_none() && self.parse_keyword(Keyword::ENFORCED) {
10098                cc.enforced = Some(true);
10099            } else if cc.enforced.is_none()
10100                && self.parse_keywords(&[Keyword::NOT, Keyword::ENFORCED])
10101            {
10102                cc.enforced = Some(false);
10103            } else {
10104                break;
10105            }
10106        }
10107
10108        if cc.deferrable.is_some() || cc.initially.is_some() || cc.enforced.is_some() {
10109            Ok(Some(cc))
10110        } else {
10111            Ok(None)
10112        }
10113    }
10114
10115    /// Parse an optional table constraint (e.g. `PRIMARY KEY`, `UNIQUE`, `FOREIGN KEY`, `CHECK`).
10116    pub fn parse_optional_table_constraint(
10117        &mut self,
10118    ) -> Result<Option<TableConstraint>, ParserError> {
10119        let name = if self.parse_keyword(Keyword::CONSTRAINT) {
10120            if self.dialect.supports_constraint_keyword_without_name()
10121                && self
10122                    .peek_one_of_keywords(&[
10123                        Keyword::CHECK,
10124                        Keyword::PRIMARY,
10125                        Keyword::UNIQUE,
10126                        Keyword::FOREIGN,
10127                    ])
10128                    .is_some()
10129            {
10130                None
10131            } else {
10132                Some(self.parse_identifier()?)
10133            }
10134        } else {
10135            None
10136        };
10137
10138        let next_token = self.next_token();
10139        match next_token.token {
10140            Token::Word(w) if w.keyword == Keyword::UNIQUE => {
10141                // PostgreSQL: UNIQUE USING INDEX index_name
10142                // https://www.postgresql.org/docs/current/sql-altertable.html
10143                if self.parse_keywords(&[Keyword::USING, Keyword::INDEX]) {
10144                    return Ok(Some(TableConstraint::UniqueUsingIndex(
10145                        self.parse_constraint_using_index(name)?,
10146                    )));
10147                }
10148
10149                let index_type_display = self.parse_index_type_display();
10150                if !dialect_of!(self is GenericDialect | MySqlDialect)
10151                    && !index_type_display.is_none()
10152                {
10153                    return self.expected_ref(
10154                        "`index_name` or `(column_name [, ...])`",
10155                        self.peek_token_ref(),
10156                    );
10157                }
10158
10159                let nulls_distinct = self.parse_optional_nulls_distinct()?;
10160
10161                // optional index name
10162                let index_name = self.parse_optional_ident()?;
10163                let index_type = self.parse_optional_using_then_index_type()?;
10164
10165                let columns = self.parse_parenthesized_index_column_list()?;
10166                let include = self.parse_optional_include_columns()?;
10167                let index_options = self.parse_index_options()?;
10168                let characteristics = self.parse_constraint_characteristics()?;
10169                Ok(Some(
10170                    UniqueConstraint {
10171                        name,
10172                        index_name,
10173                        index_type_display,
10174                        index_type,
10175                        columns,
10176                        include,
10177                        index_options,
10178                        characteristics,
10179                        nulls_distinct,
10180                    }
10181                    .into(),
10182                ))
10183            }
10184            Token::Word(w) if w.keyword == Keyword::PRIMARY => {
10185                // after `PRIMARY` always stay `KEY`
10186                self.expect_keyword_is(Keyword::KEY)?;
10187
10188                // PostgreSQL: PRIMARY KEY USING INDEX index_name
10189                // https://www.postgresql.org/docs/current/sql-altertable.html
10190                if self.parse_keywords(&[Keyword::USING, Keyword::INDEX]) {
10191                    return Ok(Some(TableConstraint::PrimaryKeyUsingIndex(
10192                        self.parse_constraint_using_index(name)?,
10193                    )));
10194                }
10195
10196                // optional index name
10197                let index_name = self.parse_optional_ident()?;
10198                let index_type = self.parse_optional_using_then_index_type()?;
10199
10200                let columns = self.parse_parenthesized_index_column_list()?;
10201                let include = self.parse_optional_include_columns()?;
10202                let index_options = self.parse_index_options()?;
10203                let characteristics = self.parse_constraint_characteristics()?;
10204                Ok(Some(
10205                    PrimaryKeyConstraint {
10206                        name,
10207                        index_name,
10208                        index_type,
10209                        columns,
10210                        include,
10211                        index_options,
10212                        characteristics,
10213                    }
10214                    .into(),
10215                ))
10216            }
10217            Token::Word(w) if w.keyword == Keyword::FOREIGN => {
10218                self.expect_keyword_is(Keyword::KEY)?;
10219                let index_name = self.parse_optional_ident()?;
10220                let columns = self.parse_parenthesized_column_list(Mandatory, false)?;
10221                self.expect_keyword_is(Keyword::REFERENCES)?;
10222                let foreign_table = self.parse_object_name(false)?;
10223                let referred_columns = self.parse_parenthesized_column_list(Optional, false)?;
10224                let mut match_kind = None;
10225                let mut on_delete = None;
10226                let mut on_update = None;
10227                loop {
10228                    if match_kind.is_none() && self.parse_keyword(Keyword::MATCH) {
10229                        match_kind = Some(self.parse_match_kind()?);
10230                    } else if on_delete.is_none()
10231                        && self.parse_keywords(&[Keyword::ON, Keyword::DELETE])
10232                    {
10233                        on_delete = Some(self.parse_referential_action()?);
10234                    } else if on_update.is_none()
10235                        && self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
10236                    {
10237                        on_update = Some(self.parse_referential_action()?);
10238                    } else {
10239                        break;
10240                    }
10241                }
10242
10243                let characteristics = self.parse_constraint_characteristics()?;
10244
10245                Ok(Some(
10246                    ForeignKeyConstraint {
10247                        name,
10248                        index_name,
10249                        columns,
10250                        foreign_table,
10251                        referred_columns,
10252                        on_delete,
10253                        on_update,
10254                        match_kind,
10255                        characteristics,
10256                    }
10257                    .into(),
10258                ))
10259            }
10260            Token::Word(w) if w.keyword == Keyword::CHECK => {
10261                self.expect_token(&Token::LParen)?;
10262                let expr = Box::new(self.parse_expr()?);
10263                self.expect_token(&Token::RParen)?;
10264                let no_inherit = self.parse_keywords(&[Keyword::NO, Keyword::INHERIT]);
10265
10266                let enforced = if self.parse_keyword(Keyword::ENFORCED) {
10267                    Some(true)
10268                } else if self.parse_keywords(&[Keyword::NOT, Keyword::ENFORCED]) {
10269                    Some(false)
10270                } else {
10271                    None
10272                };
10273
10274                Ok(Some(
10275                    CheckConstraint {
10276                        name,
10277                        expr,
10278                        no_inherit,
10279                        enforced,
10280                    }
10281                    .into(),
10282                ))
10283            }
10284            Token::Word(w)
10285                if (w.keyword == Keyword::INDEX || w.keyword == Keyword::KEY)
10286                    && dialect_of!(self is GenericDialect | MySqlDialect)
10287                    && name.is_none() =>
10288            {
10289                let display_as_key = w.keyword == Keyword::KEY;
10290
10291                let name = match &self.peek_token_ref().token {
10292                    Token::Word(word) if word.keyword == Keyword::USING => None,
10293                    _ => self.parse_optional_ident()?,
10294                };
10295
10296                let index_type = self.parse_optional_using_then_index_type()?;
10297                let columns = self.parse_parenthesized_index_column_list()?;
10298                let index_options = self.parse_index_options()?;
10299
10300                Ok(Some(
10301                    IndexConstraint {
10302                        display_as_key,
10303                        name,
10304                        index_type,
10305                        columns,
10306                        index_options,
10307                    }
10308                    .into(),
10309                ))
10310            }
10311            Token::Word(w)
10312                if (w.keyword == Keyword::FULLTEXT || w.keyword == Keyword::SPATIAL)
10313                    && dialect_of!(self is GenericDialect | MySqlDialect) =>
10314            {
10315                if let Some(name) = name {
10316                    return self.expected(
10317                        "FULLTEXT or SPATIAL option without constraint name",
10318                        TokenWithSpan {
10319                            token: Token::make_keyword(&name.to_string()),
10320                            span: next_token.span,
10321                        },
10322                    );
10323                }
10324
10325                let fulltext = w.keyword == Keyword::FULLTEXT;
10326
10327                let index_type_display = self.parse_index_type_display();
10328
10329                let opt_index_name = self.parse_optional_ident()?;
10330
10331                let columns = self.parse_parenthesized_index_column_list()?;
10332
10333                Ok(Some(
10334                    FullTextOrSpatialConstraint {
10335                        fulltext,
10336                        index_type_display,
10337                        opt_index_name,
10338                        columns,
10339                    }
10340                    .into(),
10341                ))
10342            }
10343            Token::Word(w)
10344                if w.keyword == Keyword::EXCLUDE && self.dialect.supports_exclude_constraint() =>
10345            {
10346                // `EXCLUDE` is a non-reserved keyword in PostgreSQL, so it is a
10347                // valid column name. Only treat it as an exclusion constraint
10348                // when it begins one (named, or followed by `USING` / `(`);
10349                // otherwise backtrack and let it parse as a column.
10350                if name.is_some()
10351                    || self.peek_keyword(Keyword::USING)
10352                    || self.peek_token_ref().token == Token::LParen
10353                {
10354                    Ok(Some(self.parse_exclude_constraint(name)?.into()))
10355                } else {
10356                    self.prev_token();
10357                    Ok(None)
10358                }
10359            }
10360            _ => {
10361                if name.is_some() {
10362                    self.expected("PRIMARY, UNIQUE, FOREIGN, CHECK, or EXCLUDE", next_token)
10363                } else {
10364                    self.prev_token();
10365                    Ok(None)
10366                }
10367            }
10368        }
10369    }
10370
10371    // The leading `EXCLUDE` keyword is already consumed by the caller.
10372    fn parse_exclude_constraint(
10373        &mut self,
10374        name: Option<Ident>,
10375    ) -> Result<ExcludeConstraint, ParserError> {
10376        let index_method = if self.parse_keyword(Keyword::USING) {
10377            Some(self.parse_identifier()?)
10378        } else {
10379            None
10380        };
10381
10382        self.expect_token(&Token::LParen)?;
10383        let elements = self.parse_comma_separated(|p| p.parse_exclude_constraint_element())?;
10384        self.expect_token(&Token::RParen)?;
10385
10386        let include = if self.parse_keyword(Keyword::INCLUDE) {
10387            self.expect_token(&Token::LParen)?;
10388            let cols = self.parse_comma_separated(|p| p.parse_identifier())?;
10389            self.expect_token(&Token::RParen)?;
10390            cols
10391        } else {
10392            vec![]
10393        };
10394
10395        let where_clause = if self.parse_keyword(Keyword::WHERE) {
10396            self.expect_token(&Token::LParen)?;
10397            let predicate = self.parse_expr()?;
10398            self.expect_token(&Token::RParen)?;
10399            Some(Box::new(predicate))
10400        } else {
10401            None
10402        };
10403
10404        let characteristics = self.parse_constraint_characteristics()?;
10405
10406        Ok(ExcludeConstraint {
10407            name,
10408            index_method,
10409            elements,
10410            include,
10411            where_clause,
10412            characteristics,
10413        })
10414    }
10415
10416    fn parse_exclude_constraint_element(
10417        &mut self,
10418    ) -> Result<ExcludeConstraintElement, ParserError> {
10419        let column = self.parse_create_index_expr()?;
10420        self.expect_keyword_is(Keyword::WITH)?;
10421        let operator = self.parse_exclude_constraint_operator()?;
10422        Ok(ExcludeConstraintElement { column, operator })
10423    }
10424
10425    /// Parse the operator that follows `WITH` in an `EXCLUDE` element.
10426    fn parse_exclude_constraint_operator(
10427        &mut self,
10428    ) -> Result<ExcludeConstraintOperator, ParserError> {
10429        if self.parse_keyword(Keyword::OPERATOR) {
10430            return Ok(ExcludeConstraintOperator::PGOperator(
10431                self.parse_pg_operator_ident_parts()?,
10432            ));
10433        }
10434
10435        let operator_token = self.next_token();
10436        Ok(ExcludeConstraintOperator::Token(
10437            operator_token.token.to_string(),
10438        ))
10439    }
10440
10441    /// Parse the body of a Postgres `OPERATOR(schema.op)` form: the
10442    /// parenthesized `.`-separated path of name parts after the `OPERATOR`
10443    /// keyword. Shared between binary expression parsing and exclusion
10444    /// constraint parsing.
10445    fn parse_pg_operator_ident_parts(&mut self) -> Result<Vec<String>, ParserError> {
10446        self.expect_token(&Token::LParen)?;
10447        if self.peek_token_ref().token == Token::RParen {
10448            let token = self.next_token();
10449            return self.expected("operator name", token);
10450        }
10451        let mut idents = vec![];
10452        loop {
10453            self.advance_token();
10454            idents.push(self.get_current_token().to_string());
10455            if !self.consume_token(&Token::Period) {
10456                break;
10457            }
10458        }
10459        self.expect_token(&Token::RParen)?;
10460        Ok(idents)
10461    }
10462
10463    fn parse_optional_nulls_distinct(&mut self) -> Result<NullsDistinctOption, ParserError> {
10464        Ok(if self.parse_keyword(Keyword::NULLS) {
10465            let not = self.parse_keyword(Keyword::NOT);
10466            self.expect_keyword_is(Keyword::DISTINCT)?;
10467            if not {
10468                NullsDistinctOption::NotDistinct
10469            } else {
10470                NullsDistinctOption::Distinct
10471            }
10472        } else {
10473            NullsDistinctOption::None
10474        })
10475    }
10476
10477    /// Optionally parse a parenthesized list of `SqlOption`s introduced by `keyword`.
10478    pub fn maybe_parse_options(
10479        &mut self,
10480        keyword: Keyword,
10481    ) -> Result<Option<Vec<SqlOption>>, ParserError> {
10482        if let Token::Word(word) = &self.peek_token_ref().token {
10483            if word.keyword == keyword {
10484                return Ok(Some(self.parse_options(keyword)?));
10485            }
10486        };
10487        Ok(None)
10488    }
10489
10490    /// Parse a parenthesized list of `SqlOption`s following `keyword`, or return an empty vec.
10491    pub fn parse_options(&mut self, keyword: Keyword) -> Result<Vec<SqlOption>, ParserError> {
10492        if self.parse_keyword(keyword) {
10493            self.expect_token(&Token::LParen)?;
10494            let options = self.parse_comma_separated0(Parser::parse_sql_option, Token::RParen)?;
10495            self.expect_token(&Token::RParen)?;
10496            Ok(options)
10497        } else {
10498            Ok(vec![])
10499        }
10500    }
10501
10502    /// Parse options introduced by one of `keywords` followed by a parenthesized list.
10503    pub fn parse_options_with_keywords(
10504        &mut self,
10505        keywords: &[Keyword],
10506    ) -> Result<Vec<SqlOption>, ParserError> {
10507        if self.parse_keywords(keywords) {
10508            self.expect_token(&Token::LParen)?;
10509            let options = self.parse_comma_separated(Parser::parse_sql_option)?;
10510            self.expect_token(&Token::RParen)?;
10511            Ok(options)
10512        } else {
10513            Ok(vec![])
10514        }
10515    }
10516
10517    /// Parse an index type token (e.g. `BTREE`, `HASH`, or a custom identifier).
10518    pub fn parse_index_type(&mut self) -> Result<IndexType, ParserError> {
10519        Ok(if self.parse_keyword(Keyword::BTREE) {
10520            IndexType::BTree
10521        } else if self.parse_keyword(Keyword::HASH) {
10522            IndexType::Hash
10523        } else if self.parse_keyword(Keyword::GIN) {
10524            IndexType::GIN
10525        } else if self.parse_keyword(Keyword::GIST) {
10526            IndexType::GiST
10527        } else if self.parse_keyword(Keyword::SPGIST) {
10528            IndexType::SPGiST
10529        } else if self.parse_keyword(Keyword::BRIN) {
10530            IndexType::BRIN
10531        } else if self.parse_keyword(Keyword::BLOOM) {
10532            IndexType::Bloom
10533        } else {
10534            IndexType::Custom(self.parse_identifier()?)
10535        })
10536    }
10537
10538    /// Optionally parse the `USING` keyword, followed by an [IndexType]
10539    /// Example:
10540    /// ```sql
10541    //// USING BTREE (name, age DESC)
10542    /// ```
10543    /// Optionally parse `USING <index_type>` and return the parsed `IndexType` if present.
10544    pub fn parse_optional_using_then_index_type(
10545        &mut self,
10546    ) -> Result<Option<IndexType>, ParserError> {
10547        if self.parse_keyword(Keyword::USING) {
10548            Ok(Some(self.parse_index_type()?))
10549        } else {
10550            Ok(None)
10551        }
10552    }
10553
10554    /// Parse `[ident]`, mostly `ident` is name, like:
10555    /// `window_name`, `index_name`, ...
10556    /// Parse an optional identifier, returning `Some(Ident)` if present.
10557    pub fn parse_optional_ident(&mut self) -> Result<Option<Ident>, ParserError> {
10558        self.maybe_parse(|parser| parser.parse_identifier())
10559    }
10560
10561    #[must_use]
10562    /// Parse optional `KEY` or `INDEX` display tokens used in index/constraint declarations.
10563    pub fn parse_index_type_display(&mut self) -> KeyOrIndexDisplay {
10564        if self.parse_keyword(Keyword::KEY) {
10565            KeyOrIndexDisplay::Key
10566        } else if self.parse_keyword(Keyword::INDEX) {
10567            KeyOrIndexDisplay::Index
10568        } else {
10569            KeyOrIndexDisplay::None
10570        }
10571    }
10572
10573    /// Parse an optional index option such as `USING <type>` or `COMMENT <string>`.
10574    pub fn parse_optional_index_option(&mut self) -> Result<Option<IndexOption>, ParserError> {
10575        if let Some(index_type) = self.parse_optional_using_then_index_type()? {
10576            Ok(Some(IndexOption::Using(index_type)))
10577        } else if self.parse_keyword(Keyword::COMMENT) {
10578            let s = self.parse_literal_string()?;
10579            Ok(Some(IndexOption::Comment(s)))
10580        } else {
10581            Ok(None)
10582        }
10583    }
10584
10585    /// Parse zero or more index options and return them as a vector.
10586    pub fn parse_index_options(&mut self) -> Result<Vec<IndexOption>, ParserError> {
10587        let mut options = Vec::new();
10588
10589        loop {
10590            match self.parse_optional_index_option()? {
10591                Some(index_option) => options.push(index_option),
10592                None => return Ok(options),
10593            }
10594        }
10595    }
10596
10597    /// Parse an optional `INCLUDE (col, ...)` clause on a table constraint.
10598    pub fn parse_optional_include_columns(&mut self) -> Result<Vec<Ident>, ParserError> {
10599        if self.parse_keyword(Keyword::INCLUDE) {
10600            self.expect_token(&Token::LParen)?;
10601            let columns = self.parse_comma_separated(|p| p.parse_identifier())?;
10602            self.expect_token(&Token::RParen)?;
10603            Ok(columns)
10604        } else {
10605            Ok(vec![])
10606        }
10607    }
10608
10609    /// Parse a single `SqlOption` used by various dialect-specific DDL statements.
10610    pub fn parse_sql_option(&mut self) -> Result<SqlOption, ParserError> {
10611        let is_mssql = dialect_of!(self is MsSqlDialect|GenericDialect);
10612
10613        match &self.peek_token_ref().token {
10614            Token::Word(w) if w.keyword == Keyword::HEAP && is_mssql => {
10615                Ok(SqlOption::Ident(self.parse_identifier()?))
10616            }
10617            Token::Word(w) if w.keyword == Keyword::PARTITION && is_mssql => {
10618                self.parse_option_partition()
10619            }
10620            Token::Word(w) if w.keyword == Keyword::CLUSTERED && is_mssql => {
10621                self.parse_option_clustered()
10622            }
10623            _ => {
10624                let name = self.parse_identifier()?;
10625                self.expect_token(&Token::Eq)?;
10626                let value = self.parse_expr()?;
10627
10628                Ok(SqlOption::KeyValue { key: name, value })
10629            }
10630        }
10631    }
10632
10633    /// Parse a `CLUSTERED` table option (MSSQL-specific syntaxes supported).
10634    pub fn parse_option_clustered(&mut self) -> Result<SqlOption, ParserError> {
10635        if self.parse_keywords(&[
10636            Keyword::CLUSTERED,
10637            Keyword::COLUMNSTORE,
10638            Keyword::INDEX,
10639            Keyword::ORDER,
10640        ]) {
10641            Ok(SqlOption::Clustered(
10642                TableOptionsClustered::ColumnstoreIndexOrder(
10643                    self.parse_parenthesized_column_list(IsOptional::Mandatory, false)?,
10644                ),
10645            ))
10646        } else if self.parse_keywords(&[Keyword::CLUSTERED, Keyword::COLUMNSTORE, Keyword::INDEX]) {
10647            Ok(SqlOption::Clustered(
10648                TableOptionsClustered::ColumnstoreIndex,
10649            ))
10650        } else if self.parse_keywords(&[Keyword::CLUSTERED, Keyword::INDEX]) {
10651            self.expect_token(&Token::LParen)?;
10652
10653            let columns = self.parse_comma_separated(|p| {
10654                let name = p.parse_identifier()?;
10655                let asc = p.parse_asc_desc();
10656
10657                Ok(ClusteredIndex { name, asc })
10658            })?;
10659
10660            self.expect_token(&Token::RParen)?;
10661
10662            Ok(SqlOption::Clustered(TableOptionsClustered::Index(columns)))
10663        } else {
10664            Err(ParserError::ParserError(
10665                "invalid CLUSTERED sequence".to_string(),
10666            ))
10667        }
10668    }
10669
10670    /// Parse a `PARTITION(...) FOR VALUES(...)` table option.
10671    pub fn parse_option_partition(&mut self) -> Result<SqlOption, ParserError> {
10672        self.expect_keyword_is(Keyword::PARTITION)?;
10673        self.expect_token(&Token::LParen)?;
10674        let column_name = self.parse_identifier()?;
10675
10676        self.expect_keyword_is(Keyword::RANGE)?;
10677        let range_direction = if self.parse_keyword(Keyword::LEFT) {
10678            Some(PartitionRangeDirection::Left)
10679        } else if self.parse_keyword(Keyword::RIGHT) {
10680            Some(PartitionRangeDirection::Right)
10681        } else {
10682            None
10683        };
10684
10685        self.expect_keywords(&[Keyword::FOR, Keyword::VALUES])?;
10686        self.expect_token(&Token::LParen)?;
10687
10688        let for_values = self.parse_comma_separated(Parser::parse_expr)?;
10689
10690        self.expect_token(&Token::RParen)?;
10691        self.expect_token(&Token::RParen)?;
10692
10693        Ok(SqlOption::Partition {
10694            column_name,
10695            range_direction,
10696            for_values,
10697        })
10698    }
10699
10700    /// Parse a parenthesized list of partition expressions and return a `Partition` value.
10701    pub fn parse_partition(&mut self) -> Result<Partition, ParserError> {
10702        self.expect_token(&Token::LParen)?;
10703        let partitions = self.parse_comma_separated(Parser::parse_expr)?;
10704        self.expect_token(&Token::RParen)?;
10705        Ok(Partition::Partitions(partitions))
10706    }
10707
10708    /// Parse a parenthesized `SELECT` projection used for projection-based operations.
10709    pub fn parse_projection_select(&mut self) -> Result<ProjectionSelect, ParserError> {
10710        self.expect_token(&Token::LParen)?;
10711        self.expect_keyword_is(Keyword::SELECT)?;
10712        let projection = self.parse_projection()?;
10713        let group_by = self.parse_optional_group_by()?;
10714        let order_by = self.parse_optional_order_by()?;
10715        self.expect_token(&Token::RParen)?;
10716        Ok(ProjectionSelect {
10717            projection,
10718            group_by,
10719            order_by,
10720        })
10721    }
10722    /// Parse `ALTER TABLE ... ADD PROJECTION ...` operation.
10723    pub fn parse_alter_table_add_projection(&mut self) -> Result<AlterTableOperation, ParserError> {
10724        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
10725        let name = self.parse_identifier()?;
10726        let query = self.parse_projection_select()?;
10727        Ok(AlterTableOperation::AddProjection {
10728            if_not_exists,
10729            name,
10730            select: query,
10731        })
10732    }
10733
10734    /// Parse Redshift `ALTER SORTKEY (column_list)`.
10735    ///
10736    /// See <https://docs.aws.amazon.com/redshift/latest/dg/r_ALTER_TABLE.html>
10737    fn parse_alter_sort_key(&mut self) -> Result<AlterTableOperation, ParserError> {
10738        self.expect_keyword_is(Keyword::ALTER)?;
10739        self.expect_keyword_is(Keyword::SORTKEY)?;
10740        self.expect_token(&Token::LParen)?;
10741        let columns = self.parse_comma_separated(|p| p.parse_expr())?;
10742        self.expect_token(&Token::RParen)?;
10743        Ok(AlterTableOperation::AlterSortKey { columns })
10744    }
10745
10746    /// Parse the expression(s) following ClickHouse `ORDER BY`: either a single
10747    /// expression or a possibly empty parenthesized list.
10748    fn parse_sorting_key(&mut self) -> Result<OneOrManyWithParens<Expr>, ParserError> {
10749        if self.consume_token(&Token::LParen) {
10750            let columns = if self.peek_token_ref().token != Token::RParen {
10751                self.parse_comma_separated(|p| p.parse_expr())?
10752            } else {
10753                vec![]
10754            };
10755            self.expect_token(&Token::RParen)?;
10756            Ok(OneOrManyWithParens::Many(columns))
10757        } else {
10758            Ok(OneOrManyWithParens::One(self.parse_expr()?))
10759        }
10760    }
10761
10762    /// Parse a single `ALTER TABLE` operation and return an `AlterTableOperation`.
10763    pub fn parse_alter_table_operation(&mut self) -> Result<AlterTableOperation, ParserError> {
10764        let operation = if self.parse_keyword(Keyword::ADD) {
10765            if let Some(constraint) = self.parse_optional_table_constraint()? {
10766                let not_valid = self.parse_keywords(&[Keyword::NOT, Keyword::VALID]);
10767                AlterTableOperation::AddConstraint {
10768                    constraint,
10769                    not_valid,
10770                }
10771            } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
10772                && self.parse_keyword(Keyword::PROJECTION)
10773            {
10774                return self.parse_alter_table_add_projection();
10775            } else {
10776                let if_not_exists =
10777                    self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
10778                let mut new_partitions = vec![];
10779                loop {
10780                    if self.parse_keyword(Keyword::PARTITION) {
10781                        new_partitions.push(self.parse_partition()?);
10782                    } else {
10783                        break;
10784                    }
10785                }
10786                if !new_partitions.is_empty() {
10787                    AlterTableOperation::AddPartitions {
10788                        if_not_exists,
10789                        new_partitions,
10790                    }
10791                } else {
10792                    let column_keyword = self.parse_keyword(Keyword::COLUMN);
10793
10794                    let if_not_exists = if dialect_of!(self is PostgreSqlDialect | BigQueryDialect | DuckDbDialect | GenericDialect)
10795                    {
10796                        self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS])
10797                            || if_not_exists
10798                    } else {
10799                        false
10800                    };
10801
10802                    let column_def = self.parse_column_def()?;
10803
10804                    let column_position = self.parse_column_position()?;
10805
10806                    AlterTableOperation::AddColumn {
10807                        column_keyword,
10808                        if_not_exists,
10809                        column_def,
10810                        column_position,
10811                    }
10812                }
10813            }
10814        } else if self.parse_keyword(Keyword::RENAME) {
10815            if dialect_of!(self is PostgreSqlDialect) && self.parse_keyword(Keyword::CONSTRAINT) {
10816                let old_name = self.parse_identifier()?;
10817                self.expect_keyword_is(Keyword::TO)?;
10818                let new_name = self.parse_identifier()?;
10819                AlterTableOperation::RenameConstraint { old_name, new_name }
10820            } else if self.parse_keyword(Keyword::TO) {
10821                let table_name = self.parse_object_name(false)?;
10822                AlterTableOperation::RenameTable {
10823                    table_name: RenameTableNameKind::To(table_name),
10824                }
10825            } else if self.parse_keyword(Keyword::AS) {
10826                let table_name = self.parse_object_name(false)?;
10827                AlterTableOperation::RenameTable {
10828                    table_name: RenameTableNameKind::As(table_name),
10829                }
10830            } else {
10831                let _ = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
10832                let old_column_name = self.parse_identifier()?;
10833                self.expect_keyword_is(Keyword::TO)?;
10834                let new_column_name = self.parse_identifier()?;
10835                AlterTableOperation::RenameColumn {
10836                    old_column_name,
10837                    new_column_name,
10838                }
10839            }
10840        } else if self.parse_keyword(Keyword::DISABLE) {
10841            if self.parse_keywords(&[Keyword::ROW, Keyword::LEVEL, Keyword::SECURITY]) {
10842                AlterTableOperation::DisableRowLevelSecurity {}
10843            } else if self.parse_keyword(Keyword::RULE) {
10844                let name = self.parse_identifier()?;
10845                AlterTableOperation::DisableRule { name }
10846            } else if self.parse_keyword(Keyword::TRIGGER) {
10847                let name = self.parse_identifier()?;
10848                AlterTableOperation::DisableTrigger { name }
10849            } else {
10850                return self.expected_ref(
10851                    "ROW LEVEL SECURITY, RULE, or TRIGGER after DISABLE",
10852                    self.peek_token_ref(),
10853                );
10854            }
10855        } else if self.parse_keyword(Keyword::ENABLE) {
10856            if self.parse_keywords(&[Keyword::ALWAYS, Keyword::RULE]) {
10857                let name = self.parse_identifier()?;
10858                AlterTableOperation::EnableAlwaysRule { name }
10859            } else if self.parse_keywords(&[Keyword::ALWAYS, Keyword::TRIGGER]) {
10860                let name = self.parse_identifier()?;
10861                AlterTableOperation::EnableAlwaysTrigger { name }
10862            } else if self.parse_keywords(&[Keyword::ROW, Keyword::LEVEL, Keyword::SECURITY]) {
10863                AlterTableOperation::EnableRowLevelSecurity {}
10864            } else if self.parse_keywords(&[Keyword::REPLICA, Keyword::RULE]) {
10865                let name = self.parse_identifier()?;
10866                AlterTableOperation::EnableReplicaRule { name }
10867            } else if self.parse_keywords(&[Keyword::REPLICA, Keyword::TRIGGER]) {
10868                let name = self.parse_identifier()?;
10869                AlterTableOperation::EnableReplicaTrigger { name }
10870            } else if self.parse_keyword(Keyword::RULE) {
10871                let name = self.parse_identifier()?;
10872                AlterTableOperation::EnableRule { name }
10873            } else if self.parse_keyword(Keyword::TRIGGER) {
10874                let name = self.parse_identifier()?;
10875                AlterTableOperation::EnableTrigger { name }
10876            } else {
10877                return self.expected_ref(
10878                    "ALWAYS, REPLICA, ROW LEVEL SECURITY, RULE, or TRIGGER after ENABLE",
10879                    self.peek_token_ref(),
10880                );
10881            }
10882        } else if self.parse_keywords(&[
10883            Keyword::FORCE,
10884            Keyword::ROW,
10885            Keyword::LEVEL,
10886            Keyword::SECURITY,
10887        ]) {
10888            AlterTableOperation::ForceRowLevelSecurity
10889        } else if self.parse_keywords(&[
10890            Keyword::NO,
10891            Keyword::FORCE,
10892            Keyword::ROW,
10893            Keyword::LEVEL,
10894            Keyword::SECURITY,
10895        ]) {
10896            AlterTableOperation::NoForceRowLevelSecurity
10897        } else if self.parse_keywords(&[Keyword::CLEAR, Keyword::PROJECTION])
10898            && dialect_of!(self is ClickHouseDialect|GenericDialect)
10899        {
10900            let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10901            let name = self.parse_identifier()?;
10902            let partition = if self.parse_keywords(&[Keyword::IN, Keyword::PARTITION]) {
10903                Some(self.parse_identifier()?)
10904            } else {
10905                None
10906            };
10907            AlterTableOperation::ClearProjection {
10908                if_exists,
10909                name,
10910                partition,
10911            }
10912        } else if self.parse_keywords(&[Keyword::MATERIALIZE, Keyword::PROJECTION])
10913            && dialect_of!(self is ClickHouseDialect|GenericDialect)
10914        {
10915            let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10916            let name = self.parse_identifier()?;
10917            let partition = if self.parse_keywords(&[Keyword::IN, Keyword::PARTITION]) {
10918                Some(self.parse_identifier()?)
10919            } else {
10920                None
10921            };
10922            AlterTableOperation::MaterializeProjection {
10923                if_exists,
10924                name,
10925                partition,
10926            }
10927        } else if self.parse_keyword(Keyword::DROP) {
10928            if self.parse_keywords(&[Keyword::IF, Keyword::EXISTS, Keyword::PARTITION]) {
10929                self.expect_token(&Token::LParen)?;
10930                let partitions = self.parse_comma_separated(Parser::parse_expr)?;
10931                self.expect_token(&Token::RParen)?;
10932                AlterTableOperation::DropPartitions {
10933                    partitions,
10934                    if_exists: true,
10935                }
10936            } else if self.parse_keyword(Keyword::PARTITION) {
10937                self.expect_token(&Token::LParen)?;
10938                let partitions = self.parse_comma_separated(Parser::parse_expr)?;
10939                self.expect_token(&Token::RParen)?;
10940                AlterTableOperation::DropPartitions {
10941                    partitions,
10942                    if_exists: false,
10943                }
10944            } else if self.parse_keyword(Keyword::CONSTRAINT) {
10945                let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10946                let name = self.parse_identifier()?;
10947                let drop_behavior = self.parse_optional_drop_behavior();
10948                AlterTableOperation::DropConstraint {
10949                    if_exists,
10950                    name,
10951                    drop_behavior,
10952                }
10953            } else if self.parse_keywords(&[Keyword::PRIMARY, Keyword::KEY]) {
10954                let drop_behavior = self.parse_optional_drop_behavior();
10955                AlterTableOperation::DropPrimaryKey { drop_behavior }
10956            } else if self.parse_keywords(&[Keyword::FOREIGN, Keyword::KEY]) {
10957                let name = self.parse_identifier()?;
10958                let drop_behavior = self.parse_optional_drop_behavior();
10959                AlterTableOperation::DropForeignKey {
10960                    name,
10961                    drop_behavior,
10962                }
10963            } else if self.parse_keyword(Keyword::INDEX) {
10964                let name = self.parse_identifier()?;
10965                AlterTableOperation::DropIndex { name }
10966            } else if self.parse_keyword(Keyword::PROJECTION)
10967                && dialect_of!(self is ClickHouseDialect|GenericDialect)
10968            {
10969                let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10970                let name = self.parse_identifier()?;
10971                AlterTableOperation::DropProjection { if_exists, name }
10972            } else if self.parse_keywords(&[Keyword::CLUSTERING, Keyword::KEY]) {
10973                AlterTableOperation::DropClusteringKey
10974            } else {
10975                let has_column_keyword = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
10976                let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10977                let column_names = if self.dialect.supports_comma_separated_drop_column_list() {
10978                    self.parse_comma_separated(Parser::parse_identifier)?
10979                } else {
10980                    vec![self.parse_identifier()?]
10981                };
10982                let drop_behavior = self.parse_optional_drop_behavior();
10983                AlterTableOperation::DropColumn {
10984                    has_column_keyword,
10985                    column_names,
10986                    if_exists,
10987                    drop_behavior,
10988                }
10989            }
10990        } else if self.parse_keyword(Keyword::PARTITION) {
10991            self.expect_token(&Token::LParen)?;
10992            let before = self.parse_comma_separated(Parser::parse_expr)?;
10993            self.expect_token(&Token::RParen)?;
10994            self.expect_keyword_is(Keyword::RENAME)?;
10995            self.expect_keywords(&[Keyword::TO, Keyword::PARTITION])?;
10996            self.expect_token(&Token::LParen)?;
10997            let renames = self.parse_comma_separated(Parser::parse_expr)?;
10998            self.expect_token(&Token::RParen)?;
10999            AlterTableOperation::RenamePartitions {
11000                old_partitions: before,
11001                new_partitions: renames,
11002            }
11003        } else if self.parse_keyword(Keyword::CHANGE) {
11004            let _ = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
11005            let old_name = self.parse_identifier()?;
11006            let new_name = self.parse_identifier()?;
11007            let data_type = self.parse_data_type()?;
11008            let mut options = vec![];
11009            while let Some(option) = self.parse_optional_column_option()? {
11010                options.push(option);
11011            }
11012
11013            let column_position = self.parse_column_position()?;
11014
11015            AlterTableOperation::ChangeColumn {
11016                old_name,
11017                new_name,
11018                data_type,
11019                options,
11020                column_position,
11021            }
11022        } else if self.parse_keywords(&[Keyword::MODIFY, Keyword::ORDER, Keyword::BY]) {
11023            AlterTableOperation::ModifyOrderBy {
11024                order_by: self.parse_sorting_key()?,
11025            }
11026        } else if self.parse_keyword(Keyword::MODIFY) {
11027            let _ = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
11028            let col_name = self.parse_identifier()?;
11029            let data_type = self.parse_data_type()?;
11030            let mut options = vec![];
11031            while let Some(option) = self.parse_optional_column_option()? {
11032                options.push(option);
11033            }
11034
11035            let column_position = self.parse_column_position()?;
11036
11037            AlterTableOperation::ModifyColumn {
11038                col_name,
11039                data_type,
11040                options,
11041                column_position,
11042            }
11043        } else if self.parse_keyword(Keyword::ALTER) {
11044            if self.peek_keyword(Keyword::SORTKEY) {
11045                self.prev_token();
11046                return self.parse_alter_sort_key();
11047            }
11048
11049            let _ = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
11050            let column_name = self.parse_identifier()?;
11051            let is_postgresql = dialect_of!(self is PostgreSqlDialect);
11052
11053            let op: AlterColumnOperation = if self.parse_keywords(&[
11054                Keyword::SET,
11055                Keyword::NOT,
11056                Keyword::NULL,
11057            ]) {
11058                AlterColumnOperation::SetNotNull {}
11059            } else if self.parse_keywords(&[Keyword::DROP, Keyword::NOT, Keyword::NULL]) {
11060                AlterColumnOperation::DropNotNull {}
11061            } else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
11062                AlterColumnOperation::SetDefault {
11063                    value: self.parse_expr()?,
11064                }
11065            } else if self.parse_keywords(&[Keyword::DROP, Keyword::DEFAULT]) {
11066                AlterColumnOperation::DropDefault {}
11067            } else if self.parse_keywords(&[Keyword::SET, Keyword::DATA, Keyword::TYPE]) {
11068                self.parse_set_data_type(true)?
11069            } else if self.parse_keyword(Keyword::TYPE) {
11070                self.parse_set_data_type(false)?
11071            } else if self.parse_keywords(&[Keyword::ADD, Keyword::GENERATED]) {
11072                let generated_as = if self.parse_keyword(Keyword::ALWAYS) {
11073                    Some(GeneratedAs::Always)
11074                } else if self.parse_keywords(&[Keyword::BY, Keyword::DEFAULT]) {
11075                    Some(GeneratedAs::ByDefault)
11076                } else {
11077                    None
11078                };
11079
11080                self.expect_keywords(&[Keyword::AS, Keyword::IDENTITY])?;
11081
11082                let mut sequence_options: Option<Vec<SequenceOptions>> = None;
11083
11084                if self.peek_token_ref().token == Token::LParen {
11085                    self.expect_token(&Token::LParen)?;
11086                    sequence_options = Some(self.parse_create_sequence_options()?);
11087                    self.expect_token(&Token::RParen)?;
11088                }
11089
11090                AlterColumnOperation::AddGenerated {
11091                    generated_as,
11092                    sequence_options,
11093                }
11094            } else {
11095                let message = if is_postgresql {
11096                    "SET/DROP NOT NULL, SET DEFAULT, SET DATA TYPE, or ADD GENERATED after ALTER COLUMN"
11097                } else {
11098                    "SET/DROP NOT NULL, SET DEFAULT, or SET DATA TYPE after ALTER COLUMN"
11099                };
11100
11101                return self.expected_ref(message, self.peek_token_ref());
11102            };
11103            AlterTableOperation::AlterColumn { column_name, op }
11104        } else if self.parse_keyword(Keyword::SWAP) {
11105            self.expect_keyword_is(Keyword::WITH)?;
11106            let table_name = self.parse_object_name(false)?;
11107            AlterTableOperation::SwapWith { table_name }
11108        } else if dialect_of!(self is PostgreSqlDialect | GenericDialect)
11109            && self.parse_keywords(&[Keyword::OWNER, Keyword::TO])
11110        {
11111            let new_owner = self.parse_owner()?;
11112            AlterTableOperation::OwnerTo { new_owner }
11113        } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
11114            && self.parse_keyword(Keyword::ATTACH)
11115        {
11116            AlterTableOperation::AttachPartition {
11117                partition: self.parse_part_or_partition()?,
11118            }
11119        } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
11120            && self.parse_keyword(Keyword::DETACH)
11121        {
11122            AlterTableOperation::DetachPartition {
11123                partition: self.parse_part_or_partition()?,
11124            }
11125        } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
11126            && self.parse_keyword(Keyword::FREEZE)
11127        {
11128            let partition = self.parse_part_or_partition()?;
11129            let with_name = if self.parse_keyword(Keyword::WITH) {
11130                self.expect_keyword_is(Keyword::NAME)?;
11131                Some(self.parse_identifier()?)
11132            } else {
11133                None
11134            };
11135            AlterTableOperation::FreezePartition {
11136                partition,
11137                with_name,
11138            }
11139        } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
11140            && self.parse_keyword(Keyword::UNFREEZE)
11141        {
11142            let partition = self.parse_part_or_partition()?;
11143            let with_name = if self.parse_keyword(Keyword::WITH) {
11144                self.expect_keyword_is(Keyword::NAME)?;
11145                Some(self.parse_identifier()?)
11146            } else {
11147                None
11148            };
11149            AlterTableOperation::UnfreezePartition {
11150                partition,
11151                with_name,
11152            }
11153        } else if self.parse_keywords(&[Keyword::CLUSTER, Keyword::BY]) {
11154            self.expect_token(&Token::LParen)?;
11155            let exprs = self.parse_comma_separated(|parser| parser.parse_expr())?;
11156            self.expect_token(&Token::RParen)?;
11157            AlterTableOperation::ClusterBy { exprs }
11158        } else if self.parse_keywords(&[Keyword::SUSPEND, Keyword::RECLUSTER]) {
11159            AlterTableOperation::SuspendRecluster
11160        } else if self.parse_keywords(&[Keyword::RESUME, Keyword::RECLUSTER]) {
11161            AlterTableOperation::ResumeRecluster
11162        } else if self.parse_keyword(Keyword::LOCK) {
11163            let equals = self.consume_token(&Token::Eq);
11164            let lock = match self.parse_one_of_keywords(&[
11165                Keyword::DEFAULT,
11166                Keyword::EXCLUSIVE,
11167                Keyword::NONE,
11168                Keyword::SHARED,
11169            ]) {
11170                Some(Keyword::DEFAULT) => AlterTableLock::Default,
11171                Some(Keyword::EXCLUSIVE) => AlterTableLock::Exclusive,
11172                Some(Keyword::NONE) => AlterTableLock::None,
11173                Some(Keyword::SHARED) => AlterTableLock::Shared,
11174                _ => self.expected_ref(
11175                    "DEFAULT, EXCLUSIVE, NONE or SHARED after LOCK [=]",
11176                    self.peek_token_ref(),
11177                )?,
11178            };
11179            AlterTableOperation::Lock { equals, lock }
11180        } else if self.parse_keyword(Keyword::ALGORITHM) {
11181            let equals = self.consume_token(&Token::Eq);
11182            let algorithm = match self.parse_one_of_keywords(&[
11183                Keyword::DEFAULT,
11184                Keyword::INSTANT,
11185                Keyword::INPLACE,
11186                Keyword::COPY,
11187            ]) {
11188                Some(Keyword::DEFAULT) => AlterTableAlgorithm::Default,
11189                Some(Keyword::INSTANT) => AlterTableAlgorithm::Instant,
11190                Some(Keyword::INPLACE) => AlterTableAlgorithm::Inplace,
11191                Some(Keyword::COPY) => AlterTableAlgorithm::Copy,
11192                _ => self.expected_ref(
11193                    "DEFAULT, INSTANT, INPLACE, or COPY after ALGORITHM [=]",
11194                    self.peek_token_ref(),
11195                )?,
11196            };
11197            AlterTableOperation::Algorithm { equals, algorithm }
11198        } else if self.parse_keyword(Keyword::AUTO_INCREMENT) {
11199            let equals = self.consume_token(&Token::Eq);
11200            let value = self.parse_number_value()?;
11201            AlterTableOperation::AutoIncrement { equals, value }
11202        } else if self.parse_keywords(&[Keyword::REPLICA, Keyword::IDENTITY]) {
11203            let identity = if self.parse_keyword(Keyword::NOTHING) {
11204                ReplicaIdentity::Nothing
11205            } else if self.parse_keyword(Keyword::FULL) {
11206                ReplicaIdentity::Full
11207            } else if self.parse_keyword(Keyword::DEFAULT) {
11208                ReplicaIdentity::Default
11209            } else if self.parse_keywords(&[Keyword::USING, Keyword::INDEX]) {
11210                ReplicaIdentity::Index(self.parse_identifier()?)
11211            } else {
11212                return self.expected_ref(
11213                    "NOTHING, FULL, DEFAULT, or USING INDEX index_name after REPLICA IDENTITY",
11214                    self.peek_token_ref(),
11215                );
11216            };
11217
11218            AlterTableOperation::ReplicaIdentity { identity }
11219        } else if self.parse_keywords(&[Keyword::VALIDATE, Keyword::CONSTRAINT]) {
11220            let name = self.parse_identifier()?;
11221            AlterTableOperation::ValidateConstraint { name }
11222        } else if self.parse_keywords(&[Keyword::SET, Keyword::LOGGED]) {
11223            AlterTableOperation::SetLogged
11224        } else if self.parse_keywords(&[Keyword::SET, Keyword::UNLOGGED]) {
11225            AlterTableOperation::SetUnlogged
11226        } else {
11227            let mut options =
11228                self.parse_options_with_keywords(&[Keyword::SET, Keyword::TBLPROPERTIES])?;
11229            if !options.is_empty() {
11230                AlterTableOperation::SetTblProperties {
11231                    table_properties: options,
11232                }
11233            } else {
11234                options = self.parse_options(Keyword::SET)?;
11235                if !options.is_empty() {
11236                    AlterTableOperation::SetOptionsParens { options }
11237                } else {
11238                    return self.expected_ref(
11239                    "ADD, RENAME, PARTITION, SWAP, DROP, REPLICA IDENTITY, SET, or SET TBLPROPERTIES after ALTER TABLE",
11240                    self.peek_token_ref(),
11241                  );
11242                }
11243            }
11244        };
11245        Ok(operation)
11246    }
11247
11248    fn parse_set_data_type(&mut self, had_set: bool) -> Result<AlterColumnOperation, ParserError> {
11249        let data_type = self.parse_data_type()?;
11250        let using = if self.dialect.supports_alter_column_type_using()
11251            && self.parse_keyword(Keyword::USING)
11252        {
11253            Some(self.parse_expr()?)
11254        } else {
11255            None
11256        };
11257        Ok(AlterColumnOperation::SetDataType {
11258            data_type,
11259            using,
11260            had_set,
11261        })
11262    }
11263
11264    fn parse_part_or_partition(&mut self) -> Result<Partition, ParserError> {
11265        let keyword = self.expect_one_of_keywords(&[Keyword::PART, Keyword::PARTITION])?;
11266        match keyword {
11267            Keyword::PART => Ok(Partition::Part(self.parse_expr()?)),
11268            Keyword::PARTITION => Ok(Partition::Expr(self.parse_expr()?)),
11269            // unreachable because expect_one_of_keywords used above
11270            unexpected_keyword => Err(ParserError::ParserError(
11271                format!("Internal parser error: expected any of {{PART, PARTITION}}, got {unexpected_keyword:?}"),
11272            )),
11273        }
11274    }
11275
11276    /// Parse an `ALTER <object>` statement and dispatch to the appropriate alter handler.
11277    pub fn parse_alter(&mut self) -> Result<Statement, ParserError> {
11278        if self.peek_keywords(&[Keyword::TEXT, Keyword::SEARCH]) {
11279            return self.parse_alter_text_search().map(Into::into);
11280        }
11281
11282        let object_type = self.expect_one_of_keywords(&[
11283            Keyword::VIEW,
11284            Keyword::TYPE,
11285            Keyword::COLLATION,
11286            Keyword::TABLE,
11287            Keyword::INDEX,
11288            Keyword::FUNCTION,
11289            Keyword::AGGREGATE,
11290            Keyword::ROLE,
11291            Keyword::POLICY,
11292            Keyword::CONNECTOR,
11293            Keyword::ICEBERG,
11294            Keyword::SCHEMA,
11295            Keyword::USER,
11296            Keyword::OPERATOR,
11297            Keyword::TRIGGER,
11298        ])?;
11299        match object_type {
11300            Keyword::SCHEMA => {
11301                self.prev_token();
11302                self.prev_token();
11303                self.parse_alter_schema()
11304            }
11305            Keyword::VIEW => self.parse_alter_view(),
11306            Keyword::TYPE => self.parse_alter_type(),
11307            Keyword::COLLATION => self.parse_alter_collation().map(Into::into),
11308            Keyword::TABLE => self.parse_alter_table(false),
11309            Keyword::ICEBERG => {
11310                self.expect_keyword(Keyword::TABLE)?;
11311                self.parse_alter_table(true)
11312            }
11313            Keyword::INDEX => {
11314                let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
11315                let index_name = self.parse_object_name(false)?;
11316                let operation = if self.parse_keyword(Keyword::RENAME) {
11317                    if self.parse_keyword(Keyword::TO) {
11318                        let index_name = self.parse_object_name(false)?;
11319                        AlterIndexOperation::RenameIndex { index_name }
11320                    } else {
11321                        return self.expected_ref("TO after RENAME", self.peek_token_ref());
11322                    }
11323                } else {
11324                    return self.expected_ref("RENAME after ALTER INDEX", self.peek_token_ref());
11325                };
11326
11327                Ok(Statement::AlterIndex {
11328                    if_exists,
11329                    name: index_name,
11330                    operation,
11331                })
11332            }
11333            Keyword::TRIGGER => {
11334                let name = self.parse_identifier()?;
11335                self.expect_keyword_is(Keyword::ON)?;
11336                let table_name = self.parse_object_name(false)?;
11337                self.expect_keywords(&[Keyword::RENAME, Keyword::TO])?;
11338                let new_name = self.parse_identifier()?;
11339                Ok(Statement::AlterTrigger {
11340                    name,
11341                    table_name,
11342                    new_name,
11343                })
11344            }
11345            Keyword::FUNCTION => self.parse_alter_function(AlterFunctionKind::Function),
11346            Keyword::AGGREGATE => self.parse_alter_function(AlterFunctionKind::Aggregate),
11347            Keyword::OPERATOR => {
11348                if self.parse_keyword(Keyword::FAMILY) {
11349                    self.parse_alter_operator_family().map(Into::into)
11350                } else if self.parse_keyword(Keyword::CLASS) {
11351                    self.parse_alter_operator_class().map(Into::into)
11352                } else {
11353                    self.parse_alter_operator().map(Into::into)
11354                }
11355            }
11356            Keyword::ROLE => self.parse_alter_role(),
11357            Keyword::POLICY => self.parse_alter_policy().map(Into::into),
11358            Keyword::CONNECTOR => self.parse_alter_connector(),
11359            Keyword::USER if self.dialect.supports_alter_user_as_alter_role() => {
11360                self.parse_alter_role()
11361            }
11362            Keyword::USER => self.parse_alter_user().map(Into::into),
11363            // unreachable because expect_one_of_keywords used above
11364            unexpected_keyword => Err(ParserError::ParserError(
11365                format!("Internal parser error: expected any of {{TEXT SEARCH, VIEW, TYPE, COLLATION, TABLE, INDEX, TRIGGER, FUNCTION, AGGREGATE, ROLE, POLICY, CONNECTOR, ICEBERG, SCHEMA, USER, OPERATOR}}, got {unexpected_keyword:?}"),
11366            )),
11367        }
11368    }
11369
11370    fn parse_alter_aggregate_signature(
11371        &mut self,
11372    ) -> Result<(FunctionDesc, bool, Option<Vec<OperateFunctionArg>>), ParserError> {
11373        let name = self.parse_object_name(false)?;
11374        self.expect_token(&Token::LParen)?;
11375
11376        if self.consume_token(&Token::Mul) {
11377            self.expect_token(&Token::RParen)?;
11378            return Ok((
11379                FunctionDesc {
11380                    name,
11381                    args: Some(vec![]),
11382                },
11383                true,
11384                None,
11385            ));
11386        }
11387
11388        let args =
11389            if self.peek_keyword(Keyword::ORDER) || self.peek_token_ref().token == Token::RParen {
11390                vec![]
11391            } else {
11392                self.parse_comma_separated(Parser::parse_aggregate_function_arg)?
11393            };
11394
11395        let aggregate_order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
11396            Some(self.parse_comma_separated(Parser::parse_aggregate_function_arg)?)
11397        } else {
11398            None
11399        };
11400
11401        self.expect_token(&Token::RParen)?;
11402        Ok((
11403            FunctionDesc {
11404                name,
11405                args: Some(args),
11406            },
11407            false,
11408            aggregate_order_by,
11409        ))
11410    }
11411
11412    fn parse_alter_function_action(&mut self) -> Result<Option<AlterFunctionAction>, ParserError> {
11413        let action = if self.parse_keywords(&[
11414            Keyword::CALLED,
11415            Keyword::ON,
11416            Keyword::NULL,
11417            Keyword::INPUT,
11418        ]) {
11419            Some(AlterFunctionAction::CalledOnNull(
11420                FunctionCalledOnNull::CalledOnNullInput,
11421            ))
11422        } else if self.parse_keywords(&[
11423            Keyword::RETURNS,
11424            Keyword::NULL,
11425            Keyword::ON,
11426            Keyword::NULL,
11427            Keyword::INPUT,
11428        ]) {
11429            Some(AlterFunctionAction::CalledOnNull(
11430                FunctionCalledOnNull::ReturnsNullOnNullInput,
11431            ))
11432        } else if self.parse_keyword(Keyword::STRICT) {
11433            Some(AlterFunctionAction::CalledOnNull(
11434                FunctionCalledOnNull::Strict,
11435            ))
11436        } else if self.parse_keyword(Keyword::IMMUTABLE) {
11437            Some(AlterFunctionAction::Behavior(FunctionBehavior::Immutable))
11438        } else if self.parse_keyword(Keyword::STABLE) {
11439            Some(AlterFunctionAction::Behavior(FunctionBehavior::Stable))
11440        } else if self.parse_keyword(Keyword::VOLATILE) {
11441            Some(AlterFunctionAction::Behavior(FunctionBehavior::Volatile))
11442        } else if self.parse_keyword(Keyword::NOT) {
11443            self.expect_keyword(Keyword::LEAKPROOF)?;
11444            Some(AlterFunctionAction::Leakproof(false))
11445        } else if self.parse_keyword(Keyword::LEAKPROOF) {
11446            Some(AlterFunctionAction::Leakproof(true))
11447        } else if self.parse_keyword(Keyword::EXTERNAL) {
11448            self.expect_keyword(Keyword::SECURITY)?;
11449            let security = if self.parse_keyword(Keyword::DEFINER) {
11450                FunctionSecurity::Definer
11451            } else if self.parse_keyword(Keyword::INVOKER) {
11452                FunctionSecurity::Invoker
11453            } else {
11454                return self.expected_ref("DEFINER or INVOKER", self.peek_token_ref());
11455            };
11456            Some(AlterFunctionAction::Security {
11457                external: true,
11458                security,
11459            })
11460        } else if self.parse_keyword(Keyword::SECURITY) {
11461            let security = if self.parse_keyword(Keyword::DEFINER) {
11462                FunctionSecurity::Definer
11463            } else if self.parse_keyword(Keyword::INVOKER) {
11464                FunctionSecurity::Invoker
11465            } else {
11466                return self.expected_ref("DEFINER or INVOKER", self.peek_token_ref());
11467            };
11468            Some(AlterFunctionAction::Security {
11469                external: false,
11470                security,
11471            })
11472        } else if self.parse_keyword(Keyword::PARALLEL) {
11473            let parallel = if self.parse_keyword(Keyword::UNSAFE) {
11474                FunctionParallel::Unsafe
11475            } else if self.parse_keyword(Keyword::RESTRICTED) {
11476                FunctionParallel::Restricted
11477            } else if self.parse_keyword(Keyword::SAFE) {
11478                FunctionParallel::Safe
11479            } else {
11480                return self
11481                    .expected_ref("one of UNSAFE | RESTRICTED | SAFE", self.peek_token_ref());
11482            };
11483            Some(AlterFunctionAction::Parallel(parallel))
11484        } else if self.parse_keyword(Keyword::COST) {
11485            Some(AlterFunctionAction::Cost(self.parse_number()?))
11486        } else if self.parse_keyword(Keyword::ROWS) {
11487            Some(AlterFunctionAction::Rows(self.parse_number()?))
11488        } else if self.parse_keyword(Keyword::SUPPORT) {
11489            Some(AlterFunctionAction::Support(self.parse_object_name(false)?))
11490        } else if self.parse_keyword(Keyword::SET) {
11491            let name = self.parse_object_name(false)?;
11492            let value = if self.parse_keywords(&[Keyword::FROM, Keyword::CURRENT]) {
11493                FunctionSetValue::FromCurrent
11494            } else {
11495                if !self.consume_token(&Token::Eq) && !self.parse_keyword(Keyword::TO) {
11496                    return self.expected_ref("= or TO", self.peek_token_ref());
11497                }
11498                if self.parse_keyword(Keyword::DEFAULT) {
11499                    FunctionSetValue::Default
11500                } else {
11501                    FunctionSetValue::Values(self.parse_comma_separated(Parser::parse_expr)?)
11502                }
11503            };
11504            Some(AlterFunctionAction::Set(FunctionDefinitionSetParam {
11505                name,
11506                value,
11507            }))
11508        } else if self.parse_keyword(Keyword::RESET) {
11509            let reset_config = if self.parse_keyword(Keyword::ALL) {
11510                ResetConfig::ALL
11511            } else {
11512                ResetConfig::ConfigName(self.parse_object_name(false)?)
11513            };
11514            Some(AlterFunctionAction::Reset(reset_config))
11515        } else {
11516            None
11517        };
11518
11519        Ok(action)
11520    }
11521
11522    fn parse_alter_function_actions(
11523        &mut self,
11524    ) -> Result<(Vec<AlterFunctionAction>, bool), ParserError> {
11525        let mut actions = vec![];
11526        while let Some(action) = self.parse_alter_function_action()? {
11527            actions.push(action);
11528        }
11529        if actions.is_empty() {
11530            return self.expected_ref("at least one ALTER FUNCTION action", self.peek_token_ref());
11531        }
11532        let restrict = self.parse_keyword(Keyword::RESTRICT);
11533        Ok((actions, restrict))
11534    }
11535
11536    /// Parse an `ALTER FUNCTION` or `ALTER AGGREGATE` statement.
11537    pub fn parse_alter_function(
11538        &mut self,
11539        kind: AlterFunctionKind,
11540    ) -> Result<Statement, ParserError> {
11541        let (function, aggregate_star, aggregate_order_by) = match kind {
11542            AlterFunctionKind::Function => (self.parse_function_desc()?, false, None),
11543            AlterFunctionKind::Aggregate => self.parse_alter_aggregate_signature()?,
11544        };
11545
11546        let operation = if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11547            let new_name = self.parse_identifier()?;
11548            AlterFunctionOperation::RenameTo { new_name }
11549        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11550            AlterFunctionOperation::OwnerTo(self.parse_owner()?)
11551        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11552            AlterFunctionOperation::SetSchema {
11553                schema_name: self.parse_object_name(false)?,
11554            }
11555        } else if matches!(kind, AlterFunctionKind::Function) && self.parse_keyword(Keyword::NO) {
11556            if !self.parse_keyword(Keyword::DEPENDS) {
11557                return self.expected_ref("DEPENDS after NO", self.peek_token_ref());
11558            }
11559            self.expect_keywords(&[Keyword::ON, Keyword::EXTENSION])?;
11560            AlterFunctionOperation::DependsOnExtension {
11561                no: true,
11562                extension_name: self.parse_object_name(false)?,
11563            }
11564        } else if matches!(kind, AlterFunctionKind::Function)
11565            && self.parse_keyword(Keyword::DEPENDS)
11566        {
11567            self.expect_keywords(&[Keyword::ON, Keyword::EXTENSION])?;
11568            AlterFunctionOperation::DependsOnExtension {
11569                no: false,
11570                extension_name: self.parse_object_name(false)?,
11571            }
11572        } else if matches!(kind, AlterFunctionKind::Function) {
11573            let (actions, restrict) = self.parse_alter_function_actions()?;
11574            AlterFunctionOperation::Actions { actions, restrict }
11575        } else {
11576            return self.expected_ref(
11577                "RENAME TO, OWNER TO, or SET SCHEMA after ALTER AGGREGATE",
11578                self.peek_token_ref(),
11579            );
11580        };
11581
11582        Ok(Statement::AlterFunction(AlterFunction {
11583            kind,
11584            function,
11585            aggregate_order_by,
11586            aggregate_star,
11587            operation,
11588        }))
11589    }
11590
11591    /// Parse a [Statement::AlterTable]
11592    pub fn parse_alter_table(&mut self, iceberg: bool) -> Result<Statement, ParserError> {
11593        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
11594        let only = self.parse_keyword(Keyword::ONLY); // [ ONLY ]
11595        let table_name = self.parse_object_name(false)?;
11596        let on_cluster = self.parse_optional_on_cluster()?;
11597        let operations = self.parse_comma_separated(Parser::parse_alter_table_operation)?;
11598
11599        let mut location = None;
11600        if self.parse_keyword(Keyword::LOCATION) {
11601            location = Some(HiveSetLocation {
11602                has_set: false,
11603                location: self.parse_identifier()?,
11604            });
11605        } else if self.parse_keywords(&[Keyword::SET, Keyword::LOCATION]) {
11606            location = Some(HiveSetLocation {
11607                has_set: true,
11608                location: self.parse_identifier()?,
11609            });
11610        }
11611
11612        let end_token = if self.peek_token_ref().token == Token::SemiColon {
11613            self.peek_token_ref().clone()
11614        } else {
11615            self.get_current_token().clone()
11616        };
11617
11618        Ok(AlterTable {
11619            name: table_name,
11620            if_exists,
11621            only,
11622            operations,
11623            location,
11624            on_cluster,
11625            table_type: if iceberg {
11626                Some(AlterTableType::Iceberg)
11627            } else {
11628                None
11629            },
11630            end_token: AttachedToken(end_token),
11631        }
11632        .into())
11633    }
11634
11635    /// Parse an `ALTER VIEW` statement.
11636    pub fn parse_alter_view(&mut self) -> Result<Statement, ParserError> {
11637        let name = self.parse_object_name(false)?;
11638        let columns = self.parse_parenthesized_column_list(Optional, false)?;
11639
11640        let with_options = self.parse_options(Keyword::WITH)?;
11641
11642        self.expect_keyword_is(Keyword::AS)?;
11643        let query = self.parse_query()?;
11644
11645        Ok(Statement::AlterView {
11646            name,
11647            columns,
11648            query,
11649            with_options,
11650        })
11651    }
11652
11653    /// Parse a [Statement::AlterType]
11654    pub fn parse_alter_type(&mut self) -> Result<Statement, ParserError> {
11655        let name = self.parse_object_name(false)?;
11656
11657        if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11658            let new_name = self.parse_identifier()?;
11659            Ok(Statement::AlterType(AlterType {
11660                name,
11661                operation: AlterTypeOperation::Rename(AlterTypeRename { new_name }),
11662            }))
11663        } else if self.parse_keywords(&[Keyword::ADD, Keyword::VALUE]) {
11664            let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
11665            let new_enum_value = self.parse_identifier()?;
11666            let position = if self.parse_keyword(Keyword::BEFORE) {
11667                Some(AlterTypeAddValuePosition::Before(self.parse_identifier()?))
11668            } else if self.parse_keyword(Keyword::AFTER) {
11669                Some(AlterTypeAddValuePosition::After(self.parse_identifier()?))
11670            } else {
11671                None
11672            };
11673
11674            Ok(Statement::AlterType(AlterType {
11675                name,
11676                operation: AlterTypeOperation::AddValue(AlterTypeAddValue {
11677                    if_not_exists,
11678                    value: new_enum_value,
11679                    position,
11680                }),
11681            }))
11682        } else if self.parse_keywords(&[Keyword::RENAME, Keyword::VALUE]) {
11683            let existing_enum_value = self.parse_identifier()?;
11684            self.expect_keyword(Keyword::TO)?;
11685            let new_enum_value = self.parse_identifier()?;
11686
11687            Ok(Statement::AlterType(AlterType {
11688                name,
11689                operation: AlterTypeOperation::RenameValue(AlterTypeRenameValue {
11690                    from: existing_enum_value,
11691                    to: new_enum_value,
11692                }),
11693            }))
11694        } else {
11695            self.expected_ref(
11696                "{RENAME TO | { RENAME | ADD } VALUE}",
11697                self.peek_token_ref(),
11698            )
11699        }
11700    }
11701
11702    /// Parse a [Statement::AlterCollation].
11703    ///
11704    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-altercollation.html)
11705    pub fn parse_alter_collation(&mut self) -> Result<AlterCollation, ParserError> {
11706        let name = self.parse_object_name(false)?;
11707        let operation = if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11708            AlterCollationOperation::RenameTo {
11709                new_name: self.parse_identifier()?,
11710            }
11711        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11712            AlterCollationOperation::OwnerTo(self.parse_owner()?)
11713        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11714            AlterCollationOperation::SetSchema {
11715                schema_name: self.parse_object_name(false)?,
11716            }
11717        } else if self.parse_keywords(&[Keyword::REFRESH, Keyword::VERSION]) {
11718            AlterCollationOperation::RefreshVersion
11719        } else {
11720            return self.expected_ref(
11721                "RENAME TO, OWNER TO, SET SCHEMA, or REFRESH VERSION after ALTER COLLATION",
11722                self.peek_token_ref(),
11723            );
11724        };
11725
11726        Ok(AlterCollation { name, operation })
11727    }
11728
11729    /// Parse a [Statement::AlterOperator]
11730    ///
11731    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-alteroperator.html)
11732    pub fn parse_alter_operator(&mut self) -> Result<AlterOperator, ParserError> {
11733        let name = self.parse_operator_name()?;
11734
11735        // Parse (left_type, right_type)
11736        self.expect_token(&Token::LParen)?;
11737
11738        let left_type = if self.parse_keyword(Keyword::NONE) {
11739            None
11740        } else {
11741            Some(self.parse_data_type()?)
11742        };
11743
11744        self.expect_token(&Token::Comma)?;
11745        let right_type = self.parse_data_type()?;
11746        self.expect_token(&Token::RParen)?;
11747
11748        // Parse the operation
11749        let operation = if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11750            let owner = if self.parse_keyword(Keyword::CURRENT_ROLE) {
11751                Owner::CurrentRole
11752            } else if self.parse_keyword(Keyword::CURRENT_USER) {
11753                Owner::CurrentUser
11754            } else if self.parse_keyword(Keyword::SESSION_USER) {
11755                Owner::SessionUser
11756            } else {
11757                Owner::Ident(self.parse_identifier()?)
11758            };
11759            AlterOperatorOperation::OwnerTo(owner)
11760        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11761            let schema_name = self.parse_object_name(false)?;
11762            AlterOperatorOperation::SetSchema { schema_name }
11763        } else if self.parse_keyword(Keyword::SET) {
11764            self.expect_token(&Token::LParen)?;
11765
11766            let mut options = Vec::new();
11767            loop {
11768                let keyword = self.expect_one_of_keywords(&[
11769                    Keyword::RESTRICT,
11770                    Keyword::JOIN,
11771                    Keyword::COMMUTATOR,
11772                    Keyword::NEGATOR,
11773                    Keyword::HASHES,
11774                    Keyword::MERGES,
11775                ])?;
11776
11777                match keyword {
11778                    Keyword::RESTRICT => {
11779                        self.expect_token(&Token::Eq)?;
11780                        let proc_name = if self.parse_keyword(Keyword::NONE) {
11781                            None
11782                        } else {
11783                            Some(self.parse_object_name(false)?)
11784                        };
11785                        options.push(OperatorOption::Restrict(proc_name));
11786                    }
11787                    Keyword::JOIN => {
11788                        self.expect_token(&Token::Eq)?;
11789                        let proc_name = if self.parse_keyword(Keyword::NONE) {
11790                            None
11791                        } else {
11792                            Some(self.parse_object_name(false)?)
11793                        };
11794                        options.push(OperatorOption::Join(proc_name));
11795                    }
11796                    Keyword::COMMUTATOR => {
11797                        self.expect_token(&Token::Eq)?;
11798                        let op_name = self.parse_operator_name()?;
11799                        options.push(OperatorOption::Commutator(op_name));
11800                    }
11801                    Keyword::NEGATOR => {
11802                        self.expect_token(&Token::Eq)?;
11803                        let op_name = self.parse_operator_name()?;
11804                        options.push(OperatorOption::Negator(op_name));
11805                    }
11806                    Keyword::HASHES => {
11807                        options.push(OperatorOption::Hashes);
11808                    }
11809                    Keyword::MERGES => {
11810                        options.push(OperatorOption::Merges);
11811                    }
11812                    unexpected_keyword => return Err(ParserError::ParserError(
11813                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in operator option"),
11814                    )),
11815                }
11816
11817                if !self.consume_token(&Token::Comma) {
11818                    break;
11819                }
11820            }
11821
11822            self.expect_token(&Token::RParen)?;
11823            AlterOperatorOperation::Set { options }
11824        } else {
11825            return self.expected_ref(
11826                "OWNER TO, SET SCHEMA, or SET after ALTER OPERATOR",
11827                self.peek_token_ref(),
11828            );
11829        };
11830
11831        Ok(AlterOperator {
11832            name,
11833            left_type,
11834            right_type,
11835            operation,
11836        })
11837    }
11838
11839    /// Parse an operator item for ALTER OPERATOR FAMILY ADD operations
11840    fn parse_operator_family_add_operator(&mut self) -> Result<OperatorFamilyItem, ParserError> {
11841        let strategy_number = self.parse_literal_uint()?;
11842        let operator_name = self.parse_operator_name()?;
11843
11844        // Operator argument types (required for ALTER OPERATOR FAMILY)
11845        self.expect_token(&Token::LParen)?;
11846        let op_types = self.parse_comma_separated(Parser::parse_data_type)?;
11847        self.expect_token(&Token::RParen)?;
11848
11849        // Optional purpose
11850        let purpose = if self.parse_keyword(Keyword::FOR) {
11851            if self.parse_keyword(Keyword::SEARCH) {
11852                Some(OperatorPurpose::ForSearch)
11853            } else if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
11854                let sort_family = self.parse_object_name(false)?;
11855                Some(OperatorPurpose::ForOrderBy { sort_family })
11856            } else {
11857                return self.expected_ref("SEARCH or ORDER BY after FOR", self.peek_token_ref());
11858            }
11859        } else {
11860            None
11861        };
11862
11863        Ok(OperatorFamilyItem::Operator {
11864            strategy_number,
11865            operator_name,
11866            op_types,
11867            purpose,
11868        })
11869    }
11870
11871    /// Parse a function item for ALTER OPERATOR FAMILY ADD operations
11872    fn parse_operator_family_add_function(&mut self) -> Result<OperatorFamilyItem, ParserError> {
11873        let support_number = self.parse_literal_uint()?;
11874
11875        // Optional operator types
11876        let op_types =
11877            if self.consume_token(&Token::LParen) && self.peek_token_ref().token != Token::RParen {
11878                let types = self.parse_comma_separated(Parser::parse_data_type)?;
11879                self.expect_token(&Token::RParen)?;
11880                Some(types)
11881            } else if self.consume_token(&Token::LParen) {
11882                self.expect_token(&Token::RParen)?;
11883                Some(vec![])
11884            } else {
11885                None
11886            };
11887
11888        let function_name = self.parse_object_name(false)?;
11889
11890        // Function argument types
11891        let argument_types = if self.consume_token(&Token::LParen) {
11892            if self.peek_token_ref().token == Token::RParen {
11893                self.expect_token(&Token::RParen)?;
11894                vec![]
11895            } else {
11896                let types = self.parse_comma_separated(Parser::parse_data_type)?;
11897                self.expect_token(&Token::RParen)?;
11898                types
11899            }
11900        } else {
11901            vec![]
11902        };
11903
11904        Ok(OperatorFamilyItem::Function {
11905            support_number,
11906            op_types,
11907            function_name,
11908            argument_types,
11909        })
11910    }
11911
11912    /// Parse an operator item for ALTER OPERATOR FAMILY DROP operations
11913    fn parse_operator_family_drop_operator(
11914        &mut self,
11915    ) -> Result<OperatorFamilyDropItem, ParserError> {
11916        let strategy_number = self.parse_literal_uint()?;
11917
11918        // Operator argument types (required for DROP)
11919        self.expect_token(&Token::LParen)?;
11920        let op_types = self.parse_comma_separated(Parser::parse_data_type)?;
11921        self.expect_token(&Token::RParen)?;
11922
11923        Ok(OperatorFamilyDropItem::Operator {
11924            strategy_number,
11925            op_types,
11926        })
11927    }
11928
11929    /// Parse a function item for ALTER OPERATOR FAMILY DROP operations
11930    fn parse_operator_family_drop_function(
11931        &mut self,
11932    ) -> Result<OperatorFamilyDropItem, ParserError> {
11933        let support_number = self.parse_literal_uint()?;
11934
11935        // Operator types (required for DROP)
11936        self.expect_token(&Token::LParen)?;
11937        let op_types = self.parse_comma_separated(Parser::parse_data_type)?;
11938        self.expect_token(&Token::RParen)?;
11939
11940        Ok(OperatorFamilyDropItem::Function {
11941            support_number,
11942            op_types,
11943        })
11944    }
11945
11946    /// Parse an operator family item for ADD operations (dispatches to operator or function parsing)
11947    fn parse_operator_family_add_item(&mut self) -> Result<OperatorFamilyItem, ParserError> {
11948        if self.parse_keyword(Keyword::OPERATOR) {
11949            self.parse_operator_family_add_operator()
11950        } else if self.parse_keyword(Keyword::FUNCTION) {
11951            self.parse_operator_family_add_function()
11952        } else {
11953            self.expected_ref("OPERATOR or FUNCTION", self.peek_token_ref())
11954        }
11955    }
11956
11957    /// Parse an operator family item for DROP operations (dispatches to operator or function parsing)
11958    fn parse_operator_family_drop_item(&mut self) -> Result<OperatorFamilyDropItem, ParserError> {
11959        if self.parse_keyword(Keyword::OPERATOR) {
11960            self.parse_operator_family_drop_operator()
11961        } else if self.parse_keyword(Keyword::FUNCTION) {
11962            self.parse_operator_family_drop_function()
11963        } else {
11964            self.expected_ref("OPERATOR or FUNCTION", self.peek_token_ref())
11965        }
11966    }
11967
11968    /// Parse a [Statement::AlterOperatorFamily]
11969    /// See <https://www.postgresql.org/docs/current/sql-alteropfamily.html>
11970    pub fn parse_alter_operator_family(&mut self) -> Result<AlterOperatorFamily, ParserError> {
11971        let name = self.parse_object_name(false)?;
11972        self.expect_keyword(Keyword::USING)?;
11973        let using = self.parse_identifier()?;
11974
11975        let operation = if self.parse_keyword(Keyword::ADD) {
11976            let items = self.parse_comma_separated(Parser::parse_operator_family_add_item)?;
11977            AlterOperatorFamilyOperation::Add { items }
11978        } else if self.parse_keyword(Keyword::DROP) {
11979            let items = self.parse_comma_separated(Parser::parse_operator_family_drop_item)?;
11980            AlterOperatorFamilyOperation::Drop { items }
11981        } else if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11982            let new_name = self.parse_object_name(false)?;
11983            AlterOperatorFamilyOperation::RenameTo { new_name }
11984        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11985            let owner = self.parse_owner()?;
11986            AlterOperatorFamilyOperation::OwnerTo(owner)
11987        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11988            let schema_name = self.parse_object_name(false)?;
11989            AlterOperatorFamilyOperation::SetSchema { schema_name }
11990        } else {
11991            return self.expected_ref(
11992                "ADD, DROP, RENAME TO, OWNER TO, or SET SCHEMA after ALTER OPERATOR FAMILY",
11993                self.peek_token_ref(),
11994            );
11995        };
11996
11997        Ok(AlterOperatorFamily {
11998            name,
11999            using,
12000            operation,
12001        })
12002    }
12003
12004    /// Parse an `ALTER OPERATOR CLASS` statement.
12005    ///
12006    /// Handles operations like `RENAME TO`, `OWNER TO`, and `SET SCHEMA`.
12007    pub fn parse_alter_operator_class(&mut self) -> Result<AlterOperatorClass, ParserError> {
12008        let name = self.parse_object_name(false)?;
12009        self.expect_keyword(Keyword::USING)?;
12010        let using = self.parse_identifier()?;
12011
12012        let operation = if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
12013            let new_name = self.parse_object_name(false)?;
12014            AlterOperatorClassOperation::RenameTo { new_name }
12015        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
12016            let owner = self.parse_owner()?;
12017            AlterOperatorClassOperation::OwnerTo(owner)
12018        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
12019            let schema_name = self.parse_object_name(false)?;
12020            AlterOperatorClassOperation::SetSchema { schema_name }
12021        } else {
12022            return self.expected_ref(
12023                "RENAME TO, OWNER TO, or SET SCHEMA after ALTER OPERATOR CLASS",
12024                self.peek_token_ref(),
12025            );
12026        };
12027
12028        Ok(AlterOperatorClass {
12029            name,
12030            using,
12031            operation,
12032        })
12033    }
12034
12035    /// Parse an `ALTER SCHEMA` statement.
12036    ///
12037    /// Supports operations such as setting options, renaming, adding/dropping replicas, and changing owner.
12038    pub fn parse_alter_schema(&mut self) -> Result<Statement, ParserError> {
12039        self.expect_keywords(&[Keyword::ALTER, Keyword::SCHEMA])?;
12040        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
12041        let name = self.parse_object_name(false)?;
12042        let operation = if self.parse_keywords(&[Keyword::SET, Keyword::OPTIONS]) {
12043            self.prev_token();
12044            let options = self.parse_options(Keyword::OPTIONS)?;
12045            AlterSchemaOperation::SetOptionsParens { options }
12046        } else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT, Keyword::COLLATE]) {
12047            let collate = self.parse_expr()?;
12048            AlterSchemaOperation::SetDefaultCollate { collate }
12049        } else if self.parse_keywords(&[Keyword::ADD, Keyword::REPLICA]) {
12050            let replica = self.parse_identifier()?;
12051            let options = if self.peek_keyword(Keyword::OPTIONS) {
12052                Some(self.parse_options(Keyword::OPTIONS)?)
12053            } else {
12054                None
12055            };
12056            AlterSchemaOperation::AddReplica { replica, options }
12057        } else if self.parse_keywords(&[Keyword::DROP, Keyword::REPLICA]) {
12058            let replica = self.parse_identifier()?;
12059            AlterSchemaOperation::DropReplica { replica }
12060        } else if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
12061            let new_name = self.parse_object_name(false)?;
12062            AlterSchemaOperation::Rename { name: new_name }
12063        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
12064            let owner = self.parse_owner()?;
12065            AlterSchemaOperation::OwnerTo { owner }
12066        } else {
12067            return self.expected_ref("ALTER SCHEMA operation", self.peek_token_ref());
12068        };
12069        Ok(Statement::AlterSchema(AlterSchema {
12070            name,
12071            if_exists,
12072            operations: vec![operation],
12073        }))
12074    }
12075
12076    /// Parse a `CALL procedure_name(arg1, arg2, ...)`
12077    /// or `CALL procedure_name` statement
12078    pub fn parse_call(&mut self) -> Result<Statement, ParserError> {
12079        let object_name = self.parse_object_name(false)?;
12080        if self.peek_token_ref().token == Token::LParen {
12081            match self.parse_function(object_name)? {
12082                Expr::Function(f) => Ok(Statement::Call(f)),
12083                other => parser_err!(
12084                    format!("Expected a simple procedure call but found: {other}"),
12085                    self.peek_token_ref().span.start
12086                ),
12087            }
12088        } else {
12089            Ok(Statement::Call(Function {
12090                name: object_name,
12091                uses_odbc_syntax: false,
12092                parameters: FunctionArguments::None,
12093                args: FunctionArguments::None,
12094                over: None,
12095                filter: None,
12096                null_treatment: None,
12097                within_group: vec![],
12098            }))
12099        }
12100    }
12101
12102    /// Parse a copy statement
12103    pub fn parse_copy(&mut self) -> Result<Statement, ParserError> {
12104        let source;
12105        if self.consume_token(&Token::LParen) {
12106            source = CopySource::Query(self.parse_query()?);
12107            self.expect_token(&Token::RParen)?;
12108        } else {
12109            let table_name = self.parse_object_name(false)?;
12110            let columns = self.parse_parenthesized_column_list(Optional, false)?;
12111            source = CopySource::Table {
12112                table_name,
12113                columns,
12114            };
12115        }
12116        let to = match self.parse_one_of_keywords(&[Keyword::FROM, Keyword::TO]) {
12117            Some(Keyword::FROM) => false,
12118            Some(Keyword::TO) => true,
12119            _ => self.expected_ref("FROM or TO", self.peek_token_ref())?,
12120        };
12121        if !to {
12122            // Use a separate if statement to prevent Rust compiler from complaining about
12123            // "if statement in this position is unstable: https://github.com/rust-lang/rust/issues/53667"
12124            if let CopySource::Query(_) = source {
12125                return Err(ParserError::ParserError(
12126                    "COPY ... FROM does not support query as a source".to_string(),
12127                ));
12128            }
12129        }
12130        let target = if self.parse_keyword(Keyword::STDIN) {
12131            CopyTarget::Stdin
12132        } else if self.parse_keyword(Keyword::STDOUT) {
12133            CopyTarget::Stdout
12134        } else if self.parse_keyword(Keyword::PROGRAM) {
12135            CopyTarget::Program {
12136                command: self.parse_literal_string()?,
12137            }
12138        } else {
12139            CopyTarget::File {
12140                filename: self.parse_literal_string()?,
12141            }
12142        };
12143        let _ = self.parse_keyword(Keyword::WITH); // [ WITH ]
12144        let mut options = vec![];
12145        if self.consume_token(&Token::LParen) {
12146            options = self.parse_comma_separated(Parser::parse_copy_option)?;
12147            self.expect_token(&Token::RParen)?;
12148        }
12149        let mut legacy_options = vec![];
12150        while let Some(opt) = self.maybe_parse(|parser| parser.parse_copy_legacy_option())? {
12151            legacy_options.push(opt);
12152        }
12153        let values =
12154            if matches!(target, CopyTarget::Stdin) && self.peek_token_ref().token != Token::EOF {
12155                self.expect_token(&Token::SemiColon)?;
12156                self.parse_tsv()
12157            } else {
12158                vec![]
12159            };
12160        Ok(Statement::Copy {
12161            source,
12162            to,
12163            target,
12164            options,
12165            legacy_options,
12166            values,
12167        })
12168    }
12169
12170    /// Parse [Statement::Open]
12171    fn parse_open(&mut self) -> Result<Statement, ParserError> {
12172        self.expect_keyword(Keyword::OPEN)?;
12173        Ok(Statement::Open(OpenStatement {
12174            cursor_name: self.parse_identifier()?,
12175        }))
12176    }
12177
12178    /// Parse a `CLOSE` cursor statement.
12179    pub fn parse_close(&mut self) -> Result<Statement, ParserError> {
12180        let cursor = if self.parse_keyword(Keyword::ALL) {
12181            CloseCursor::All
12182        } else {
12183            let name = self.parse_identifier()?;
12184
12185            CloseCursor::Specific { name }
12186        };
12187
12188        Ok(Statement::Close { cursor })
12189    }
12190
12191    fn parse_copy_option(&mut self) -> Result<CopyOption, ParserError> {
12192        let ret = match self.parse_one_of_keywords(&[
12193            Keyword::FORMAT,
12194            Keyword::FREEZE,
12195            Keyword::DELIMITER,
12196            Keyword::NULL,
12197            Keyword::HEADER,
12198            Keyword::QUOTE,
12199            Keyword::ESCAPE,
12200            Keyword::FORCE_QUOTE,
12201            Keyword::FORCE_NOT_NULL,
12202            Keyword::FORCE_NULL,
12203            Keyword::ENCODING,
12204        ]) {
12205            Some(Keyword::FORMAT) => CopyOption::Format(self.parse_identifier()?),
12206            Some(Keyword::FREEZE) => CopyOption::Freeze(!matches!(
12207                self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]),
12208                Some(Keyword::FALSE)
12209            )),
12210            Some(Keyword::DELIMITER) => CopyOption::Delimiter(self.parse_literal_char()?),
12211            Some(Keyword::NULL) => CopyOption::Null(self.parse_literal_string()?),
12212            Some(Keyword::HEADER) => CopyOption::Header(!matches!(
12213                self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]),
12214                Some(Keyword::FALSE)
12215            )),
12216            Some(Keyword::QUOTE) => CopyOption::Quote(self.parse_literal_char()?),
12217            Some(Keyword::ESCAPE) => CopyOption::Escape(self.parse_literal_char()?),
12218            Some(Keyword::FORCE_QUOTE) => {
12219                CopyOption::ForceQuote(self.parse_parenthesized_column_list(Mandatory, false)?)
12220            }
12221            Some(Keyword::FORCE_NOT_NULL) => {
12222                CopyOption::ForceNotNull(self.parse_parenthesized_column_list(Mandatory, false)?)
12223            }
12224            Some(Keyword::FORCE_NULL) => {
12225                CopyOption::ForceNull(self.parse_parenthesized_column_list(Mandatory, false)?)
12226            }
12227            Some(Keyword::ENCODING) => CopyOption::Encoding(self.parse_literal_string()?),
12228            _ => self.expected_ref("option", self.peek_token_ref())?,
12229        };
12230        Ok(ret)
12231    }
12232
12233    fn parse_copy_legacy_option(&mut self) -> Result<CopyLegacyOption, ParserError> {
12234        // FORMAT \[ AS \] is optional
12235        if self.parse_keyword(Keyword::FORMAT) {
12236            let _ = self.parse_keyword(Keyword::AS);
12237        }
12238
12239        let ret = match self.parse_one_of_keywords(&[
12240            Keyword::ACCEPTANYDATE,
12241            Keyword::ACCEPTINVCHARS,
12242            Keyword::ADDQUOTES,
12243            Keyword::ALLOWOVERWRITE,
12244            Keyword::BINARY,
12245            Keyword::BLANKSASNULL,
12246            Keyword::BZIP2,
12247            Keyword::CLEANPATH,
12248            Keyword::COMPUPDATE,
12249            Keyword::CREDENTIALS,
12250            Keyword::CSV,
12251            Keyword::DATEFORMAT,
12252            Keyword::DELIMITER,
12253            Keyword::EMPTYASNULL,
12254            Keyword::ENCRYPTED,
12255            Keyword::ESCAPE,
12256            Keyword::EXTENSION,
12257            Keyword::FIXEDWIDTH,
12258            Keyword::GZIP,
12259            Keyword::HEADER,
12260            Keyword::IAM_ROLE,
12261            Keyword::IGNOREHEADER,
12262            Keyword::JSON,
12263            Keyword::MANIFEST,
12264            Keyword::MAXFILESIZE,
12265            Keyword::NULL,
12266            Keyword::PARALLEL,
12267            Keyword::PARQUET,
12268            Keyword::PARTITION,
12269            Keyword::REGION,
12270            Keyword::REMOVEQUOTES,
12271            Keyword::ROWGROUPSIZE,
12272            Keyword::STATUPDATE,
12273            Keyword::TIMEFORMAT,
12274            Keyword::TRUNCATECOLUMNS,
12275            Keyword::ZSTD,
12276        ]) {
12277            Some(Keyword::ACCEPTANYDATE) => CopyLegacyOption::AcceptAnyDate,
12278            Some(Keyword::ACCEPTINVCHARS) => {
12279                let _ = self.parse_keyword(Keyword::AS); // [ AS ]
12280                let ch = if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
12281                    Some(self.parse_literal_string()?)
12282                } else {
12283                    None
12284                };
12285                CopyLegacyOption::AcceptInvChars(ch)
12286            }
12287            Some(Keyword::ADDQUOTES) => CopyLegacyOption::AddQuotes,
12288            Some(Keyword::ALLOWOVERWRITE) => CopyLegacyOption::AllowOverwrite,
12289            Some(Keyword::BINARY) => CopyLegacyOption::Binary,
12290            Some(Keyword::BLANKSASNULL) => CopyLegacyOption::BlankAsNull,
12291            Some(Keyword::BZIP2) => CopyLegacyOption::Bzip2,
12292            Some(Keyword::CLEANPATH) => CopyLegacyOption::CleanPath,
12293            Some(Keyword::COMPUPDATE) => {
12294                let preset = self.parse_keyword(Keyword::PRESET);
12295                let enabled = match self.parse_one_of_keywords(&[
12296                    Keyword::TRUE,
12297                    Keyword::FALSE,
12298                    Keyword::ON,
12299                    Keyword::OFF,
12300                ]) {
12301                    Some(Keyword::TRUE) | Some(Keyword::ON) => Some(true),
12302                    Some(Keyword::FALSE) | Some(Keyword::OFF) => Some(false),
12303                    _ => None,
12304                };
12305                CopyLegacyOption::CompUpdate { preset, enabled }
12306            }
12307            Some(Keyword::CREDENTIALS) => {
12308                CopyLegacyOption::Credentials(self.parse_literal_string()?)
12309            }
12310            Some(Keyword::CSV) => CopyLegacyOption::Csv({
12311                let mut opts = vec![];
12312                while let Some(opt) =
12313                    self.maybe_parse(|parser| parser.parse_copy_legacy_csv_option())?
12314                {
12315                    opts.push(opt);
12316                }
12317                opts
12318            }),
12319            Some(Keyword::DATEFORMAT) => {
12320                let _ = self.parse_keyword(Keyword::AS);
12321                let fmt = if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
12322                    Some(self.parse_literal_string()?)
12323                } else {
12324                    None
12325                };
12326                CopyLegacyOption::DateFormat(fmt)
12327            }
12328            Some(Keyword::DELIMITER) => {
12329                let _ = self.parse_keyword(Keyword::AS);
12330                CopyLegacyOption::Delimiter(self.parse_literal_char()?)
12331            }
12332            Some(Keyword::EMPTYASNULL) => CopyLegacyOption::EmptyAsNull,
12333            Some(Keyword::ENCRYPTED) => {
12334                let auto = self.parse_keyword(Keyword::AUTO);
12335                CopyLegacyOption::Encrypted { auto }
12336            }
12337            Some(Keyword::ESCAPE) => CopyLegacyOption::Escape,
12338            Some(Keyword::EXTENSION) => {
12339                let ext = self.parse_literal_string()?;
12340                CopyLegacyOption::Extension(ext)
12341            }
12342            Some(Keyword::FIXEDWIDTH) => {
12343                let spec = self.parse_literal_string()?;
12344                CopyLegacyOption::FixedWidth(spec)
12345            }
12346            Some(Keyword::GZIP) => CopyLegacyOption::Gzip,
12347            Some(Keyword::HEADER) => CopyLegacyOption::Header,
12348            Some(Keyword::IAM_ROLE) => CopyLegacyOption::IamRole(self.parse_iam_role_kind()?),
12349            Some(Keyword::IGNOREHEADER) => {
12350                let _ = self.parse_keyword(Keyword::AS);
12351                let num_rows = self.parse_literal_uint()?;
12352                CopyLegacyOption::IgnoreHeader(num_rows)
12353            }
12354            Some(Keyword::JSON) => {
12355                let _ = self.parse_keyword(Keyword::AS);
12356                let fmt = if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
12357                    Some(self.parse_literal_string()?)
12358                } else {
12359                    None
12360                };
12361                CopyLegacyOption::Json(fmt)
12362            }
12363            Some(Keyword::MANIFEST) => {
12364                let verbose = self.parse_keyword(Keyword::VERBOSE);
12365                CopyLegacyOption::Manifest { verbose }
12366            }
12367            Some(Keyword::MAXFILESIZE) => {
12368                let _ = self.parse_keyword(Keyword::AS);
12369                let size = self.parse_number_value()?;
12370                let unit = match self.parse_one_of_keywords(&[Keyword::MB, Keyword::GB]) {
12371                    Some(Keyword::MB) => Some(FileSizeUnit::MB),
12372                    Some(Keyword::GB) => Some(FileSizeUnit::GB),
12373                    _ => None,
12374                };
12375                CopyLegacyOption::MaxFileSize(FileSize { size, unit })
12376            }
12377            Some(Keyword::NULL) => {
12378                let _ = self.parse_keyword(Keyword::AS);
12379                CopyLegacyOption::Null(self.parse_literal_string()?)
12380            }
12381            Some(Keyword::PARALLEL) => {
12382                let enabled = match self.parse_one_of_keywords(&[
12383                    Keyword::TRUE,
12384                    Keyword::FALSE,
12385                    Keyword::ON,
12386                    Keyword::OFF,
12387                ]) {
12388                    Some(Keyword::TRUE) | Some(Keyword::ON) => Some(true),
12389                    Some(Keyword::FALSE) | Some(Keyword::OFF) => Some(false),
12390                    _ => None,
12391                };
12392                CopyLegacyOption::Parallel(enabled)
12393            }
12394            Some(Keyword::PARQUET) => CopyLegacyOption::Parquet,
12395            Some(Keyword::PARTITION) => {
12396                self.expect_keyword(Keyword::BY)?;
12397                let columns = self.parse_parenthesized_column_list(IsOptional::Mandatory, false)?;
12398                let include = self.parse_keyword(Keyword::INCLUDE);
12399                CopyLegacyOption::PartitionBy(UnloadPartitionBy { columns, include })
12400            }
12401            Some(Keyword::REGION) => {
12402                let _ = self.parse_keyword(Keyword::AS);
12403                let region = self.parse_literal_string()?;
12404                CopyLegacyOption::Region(region)
12405            }
12406            Some(Keyword::REMOVEQUOTES) => CopyLegacyOption::RemoveQuotes,
12407            Some(Keyword::ROWGROUPSIZE) => {
12408                let _ = self.parse_keyword(Keyword::AS);
12409                let file_size = self.parse_file_size()?;
12410                CopyLegacyOption::RowGroupSize(file_size)
12411            }
12412            Some(Keyword::STATUPDATE) => {
12413                let enabled = match self.parse_one_of_keywords(&[
12414                    Keyword::TRUE,
12415                    Keyword::FALSE,
12416                    Keyword::ON,
12417                    Keyword::OFF,
12418                ]) {
12419                    Some(Keyword::TRUE) | Some(Keyword::ON) => Some(true),
12420                    Some(Keyword::FALSE) | Some(Keyword::OFF) => Some(false),
12421                    _ => None,
12422                };
12423                CopyLegacyOption::StatUpdate(enabled)
12424            }
12425            Some(Keyword::TIMEFORMAT) => {
12426                let _ = self.parse_keyword(Keyword::AS);
12427                let fmt = if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
12428                    Some(self.parse_literal_string()?)
12429                } else {
12430                    None
12431                };
12432                CopyLegacyOption::TimeFormat(fmt)
12433            }
12434            Some(Keyword::TRUNCATECOLUMNS) => CopyLegacyOption::TruncateColumns,
12435            Some(Keyword::ZSTD) => CopyLegacyOption::Zstd,
12436            _ => self.expected_ref("option", self.peek_token_ref())?,
12437        };
12438        Ok(ret)
12439    }
12440
12441    fn parse_file_size(&mut self) -> Result<FileSize, ParserError> {
12442        let size = self.parse_number_value()?;
12443        let unit = self.maybe_parse_file_size_unit();
12444        Ok(FileSize { size, unit })
12445    }
12446
12447    fn maybe_parse_file_size_unit(&mut self) -> Option<FileSizeUnit> {
12448        match self.parse_one_of_keywords(&[Keyword::MB, Keyword::GB]) {
12449            Some(Keyword::MB) => Some(FileSizeUnit::MB),
12450            Some(Keyword::GB) => Some(FileSizeUnit::GB),
12451            _ => None,
12452        }
12453    }
12454
12455    fn parse_iam_role_kind(&mut self) -> Result<IamRoleKind, ParserError> {
12456        if self.parse_keyword(Keyword::DEFAULT) {
12457            Ok(IamRoleKind::Default)
12458        } else {
12459            let arn = self.parse_literal_string()?;
12460            Ok(IamRoleKind::Arn(arn))
12461        }
12462    }
12463
12464    fn parse_copy_legacy_csv_option(&mut self) -> Result<CopyLegacyCsvOption, ParserError> {
12465        let ret = match self.parse_one_of_keywords(&[
12466            Keyword::HEADER,
12467            Keyword::QUOTE,
12468            Keyword::ESCAPE,
12469            Keyword::FORCE,
12470        ]) {
12471            Some(Keyword::HEADER) => CopyLegacyCsvOption::Header,
12472            Some(Keyword::QUOTE) => {
12473                let _ = self.parse_keyword(Keyword::AS); // [ AS ]
12474                CopyLegacyCsvOption::Quote(self.parse_literal_char()?)
12475            }
12476            Some(Keyword::ESCAPE) => {
12477                let _ = self.parse_keyword(Keyword::AS); // [ AS ]
12478                CopyLegacyCsvOption::Escape(self.parse_literal_char()?)
12479            }
12480            Some(Keyword::FORCE) if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) => {
12481                CopyLegacyCsvOption::ForceNotNull(
12482                    self.parse_comma_separated(|p| p.parse_identifier())?,
12483                )
12484            }
12485            Some(Keyword::FORCE) if self.parse_keywords(&[Keyword::QUOTE]) => {
12486                CopyLegacyCsvOption::ForceQuote(
12487                    self.parse_comma_separated(|p| p.parse_identifier())?,
12488                )
12489            }
12490            _ => self.expected_ref("csv option", self.peek_token_ref())?,
12491        };
12492        Ok(ret)
12493    }
12494
12495    fn parse_literal_char(&mut self) -> Result<char, ParserError> {
12496        let s = self.parse_literal_string()?;
12497        if s.len() != 1 {
12498            let loc = self
12499                .tokens
12500                .get(self.index - 1)
12501                .map_or(Location { line: 0, column: 0 }, |t| t.span.start);
12502            return parser_err!(format!("Expect a char, found {s:?}"), loc);
12503        }
12504        Ok(s.chars().next().unwrap())
12505    }
12506
12507    /// Parse a tab separated values in
12508    /// COPY payload
12509    pub fn parse_tsv(&mut self) -> Vec<Option<String>> {
12510        self.parse_tab_value()
12511    }
12512
12513    /// Parse a single tab-separated value row used by `COPY` payload parsing.
12514    pub fn parse_tab_value(&mut self) -> Vec<Option<String>> {
12515        let mut values = vec![];
12516        let mut content = String::new();
12517        while let Some(t) = self.next_token_no_skip().map(|t| &t.token) {
12518            match t {
12519                Token::Whitespace(Whitespace::Tab) => {
12520                    values.push(Some(core::mem::take(&mut content)));
12521                }
12522                Token::Whitespace(Whitespace::Newline) => {
12523                    values.push(Some(core::mem::take(&mut content)));
12524                }
12525                Token::Backslash => {
12526                    if self.consume_token(&Token::Period) {
12527                        return values;
12528                    }
12529                    if let Token::Word(w) = self.next_token().token {
12530                        if w.value == "N" {
12531                            values.push(None);
12532                        }
12533                    }
12534                }
12535                _ => {
12536                    content.push_str(&t.to_string());
12537                }
12538            }
12539        }
12540        values
12541    }
12542
12543    /// Parse a literal value (numbers, strings, date/time, booleans)
12544    pub fn parse_value(&mut self) -> Result<ValueWithSpan, ParserError> {
12545        let next_token = self.next_token();
12546        let span = next_token.span;
12547        let ok_value = |value: Value| Ok(value.with_span(span));
12548        match next_token.token {
12549            Token::Word(w) => match w.keyword {
12550                Keyword::TRUE if self.dialect.supports_boolean_literals() => {
12551                    ok_value(Value::Boolean(true))
12552                }
12553                Keyword::FALSE if self.dialect.supports_boolean_literals() => {
12554                    ok_value(Value::Boolean(false))
12555                }
12556                Keyword::NULL => ok_value(Value::Null),
12557                Keyword::NoKeyword if w.quote_style.is_some() => match w.quote_style {
12558                    Some('"') => ok_value(Value::DoubleQuotedString(w.value)),
12559                    Some('\'') => ok_value(Value::SingleQuotedString(w.value)),
12560                    _ => self.expected(
12561                        "A value?",
12562                        TokenWithSpan {
12563                            token: Token::Word(w),
12564                            span,
12565                        },
12566                    )?,
12567                },
12568                _ => self.expected(
12569                    "a concrete value",
12570                    TokenWithSpan {
12571                        token: Token::Word(w),
12572                        span,
12573                    },
12574                ),
12575            },
12576            // The call to n.parse() returns a bigdecimal when the
12577            // bigdecimal feature is enabled, and is otherwise a no-op
12578            // (i.e., it returns the input string).
12579            Token::Number(n, l) => ok_value(Value::Number(Self::parse(n, span.start)?, l)),
12580            Token::SingleQuotedString(ref s) => ok_value(Value::SingleQuotedString(
12581                self.maybe_concat_string_literal(s.to_string()),
12582            )),
12583            Token::DoubleQuotedString(ref s) => ok_value(Value::DoubleQuotedString(
12584                self.maybe_concat_string_literal(s.to_string()),
12585            )),
12586            Token::TripleSingleQuotedString(ref s) => {
12587                ok_value(Value::TripleSingleQuotedString(s.to_string()))
12588            }
12589            Token::TripleDoubleQuotedString(ref s) => {
12590                ok_value(Value::TripleDoubleQuotedString(s.to_string()))
12591            }
12592            Token::DollarQuotedString(ref s) => ok_value(Value::DollarQuotedString(s.clone())),
12593            Token::SingleQuotedByteStringLiteral(ref s) => {
12594                ok_value(Value::SingleQuotedByteStringLiteral(s.clone()))
12595            }
12596            Token::DoubleQuotedByteStringLiteral(ref s) => {
12597                ok_value(Value::DoubleQuotedByteStringLiteral(s.clone()))
12598            }
12599            Token::TripleSingleQuotedByteStringLiteral(ref s) => {
12600                ok_value(Value::TripleSingleQuotedByteStringLiteral(s.clone()))
12601            }
12602            Token::TripleDoubleQuotedByteStringLiteral(ref s) => {
12603                ok_value(Value::TripleDoubleQuotedByteStringLiteral(s.clone()))
12604            }
12605            Token::SingleQuotedRawStringLiteral(ref s) => {
12606                ok_value(Value::SingleQuotedRawStringLiteral(s.clone()))
12607            }
12608            Token::DoubleQuotedRawStringLiteral(ref s) => {
12609                ok_value(Value::DoubleQuotedRawStringLiteral(s.clone()))
12610            }
12611            Token::TripleSingleQuotedRawStringLiteral(ref s) => {
12612                ok_value(Value::TripleSingleQuotedRawStringLiteral(s.clone()))
12613            }
12614            Token::TripleDoubleQuotedRawStringLiteral(ref s) => {
12615                ok_value(Value::TripleDoubleQuotedRawStringLiteral(s.clone()))
12616            }
12617            Token::NationalStringLiteral(ref s) => {
12618                ok_value(Value::NationalStringLiteral(s.to_string()))
12619            }
12620            Token::QuoteDelimitedStringLiteral(v) => {
12621                ok_value(Value::QuoteDelimitedStringLiteral(v))
12622            }
12623            Token::NationalQuoteDelimitedStringLiteral(v) => {
12624                ok_value(Value::NationalQuoteDelimitedStringLiteral(v))
12625            }
12626            Token::EscapedStringLiteral(ref s) => {
12627                ok_value(Value::EscapedStringLiteral(s.to_string()))
12628            }
12629            Token::UnicodeStringLiteral(ref s) => {
12630                ok_value(Value::UnicodeStringLiteral(s.to_string()))
12631            }
12632            Token::HexStringLiteral(ref s) => ok_value(Value::HexStringLiteral(s.to_string())),
12633            Token::Placeholder(ref s) => ok_value(Value::Placeholder(s.to_string())),
12634            tok @ Token::Colon | tok @ Token::AtSign => {
12635                // 1. Not calling self.parse_identifier(false)?
12636                //    because only in placeholder we want to check
12637                //    numbers as idfentifies.  This because snowflake
12638                //    allows numbers as placeholders
12639                // 2. Not calling self.next_token() to enforce `tok`
12640                //    be followed immediately by a word/number, ie.
12641                //    without any whitespace in between
12642                let next_token = self.next_token_no_skip().unwrap_or(&EOF_TOKEN).clone();
12643                let ident = match next_token.token {
12644                    Token::Word(w) if w.quote_style.is_none() => Ok(w.into_ident(next_token.span)),
12645                    Token::Number(w, false) => Ok(Ident::with_span(next_token.span, w)),
12646                    _ => self.expected("placeholder", next_token),
12647                }?;
12648                Ok(Value::Placeholder(format!("{tok}{}", ident.value))
12649                    .with_span(Span::new(span.start, ident.span.end)))
12650            }
12651            unexpected => self.expected(
12652                "a value",
12653                TokenWithSpan {
12654                    token: unexpected,
12655                    span,
12656                },
12657            ),
12658        }
12659    }
12660
12661    fn maybe_concat_string_literal(&mut self, mut str: String) -> String {
12662        if self.dialect.supports_string_literal_concatenation() {
12663            while let Token::SingleQuotedString(ref s) | Token::DoubleQuotedString(ref s) =
12664                self.peek_token_ref().token
12665            {
12666                str.push_str(s);
12667                self.advance_token();
12668            }
12669        } else if self
12670            .dialect
12671            .supports_string_literal_concatenation_with_newline()
12672        {
12673            // We are iterating over tokens including whitespaces, to identify
12674            // string literals separated by newlines so we can concatenate them.
12675            let mut after_newline = false;
12676            loop {
12677                match self.peek_token_no_skip().token {
12678                    Token::Whitespace(Whitespace::Newline) => {
12679                        after_newline = true;
12680                        self.next_token_no_skip();
12681                    }
12682                    Token::Whitespace(_) => {
12683                        self.next_token_no_skip();
12684                    }
12685                    Token::SingleQuotedString(ref s) | Token::DoubleQuotedString(ref s)
12686                        if after_newline =>
12687                    {
12688                        str.push_str(s.clone().as_str());
12689                        self.next_token_no_skip();
12690                        after_newline = false;
12691                    }
12692                    _ => break,
12693                }
12694            }
12695        }
12696
12697        str
12698    }
12699
12700    /// Parse an unsigned numeric literal
12701    pub fn parse_number_value(&mut self) -> Result<ValueWithSpan, ParserError> {
12702        let value_wrapper = self.parse_value()?;
12703        match &value_wrapper.value {
12704            Value::Number(_, _) => Ok(value_wrapper),
12705            Value::Placeholder(_) => Ok(value_wrapper),
12706            _ => {
12707                self.prev_token();
12708                self.expected_ref("literal number", self.peek_token_ref())
12709            }
12710        }
12711    }
12712
12713    /// Parse a numeric literal as an expression. Returns a [`Expr::UnaryOp`] if the number is signed,
12714    /// otherwise returns a [`Expr::Value`]
12715    pub fn parse_number(&mut self) -> Result<Expr, ParserError> {
12716        let next_token = self.next_token();
12717        match next_token.token {
12718            Token::Plus => Ok(Expr::UnaryOp {
12719                op: UnaryOperator::Plus,
12720                expr: Box::new(Expr::Value(self.parse_number_value()?)),
12721            }),
12722            Token::Minus => Ok(Expr::UnaryOp {
12723                op: UnaryOperator::Minus,
12724                expr: Box::new(Expr::Value(self.parse_number_value()?)),
12725            }),
12726            _ => {
12727                self.prev_token();
12728                Ok(Expr::Value(self.parse_number_value()?))
12729            }
12730        }
12731    }
12732
12733    fn parse_introduced_string_expr(&mut self) -> Result<Expr, ParserError> {
12734        let next_token = self.next_token();
12735        let span = next_token.span;
12736        match next_token.token {
12737            Token::SingleQuotedString(ref s) => Ok(Expr::Value(
12738                Value::SingleQuotedString(s.to_string()).with_span(span),
12739            )),
12740            Token::DoubleQuotedString(ref s) => Ok(Expr::Value(
12741                Value::DoubleQuotedString(s.to_string()).with_span(span),
12742            )),
12743            Token::HexStringLiteral(ref s) => Ok(Expr::Value(
12744                Value::HexStringLiteral(s.to_string()).with_span(span),
12745            )),
12746            unexpected => self.expected(
12747                "a string value",
12748                TokenWithSpan {
12749                    token: unexpected,
12750                    span,
12751                },
12752            ),
12753        }
12754    }
12755
12756    /// Parse an unsigned literal integer/long
12757    pub fn parse_literal_uint(&mut self) -> Result<u64, ParserError> {
12758        let next_token = self.next_token();
12759        match next_token.token {
12760            Token::Number(s, _) => Self::parse::<u64>(s, next_token.span.start),
12761            _ => self.expected("literal int", next_token),
12762        }
12763    }
12764
12765    /// Parse the body of a `CREATE FUNCTION` specified as a string.
12766    /// e.g. `CREATE FUNCTION ... AS $$ body $$`.
12767    fn parse_create_function_body_string(&mut self) -> Result<CreateFunctionBody, ParserError> {
12768        let parse_string_expr = |parser: &mut Parser| -> Result<Expr, ParserError> {
12769            let peek_token = parser.peek_token();
12770            let span = peek_token.span;
12771            match peek_token.token {
12772                Token::DollarQuotedString(s) if dialect_of!(parser is PostgreSqlDialect | GenericDialect) =>
12773                {
12774                    parser.next_token();
12775                    Ok(Expr::Value(Value::DollarQuotedString(s).with_span(span)))
12776                }
12777                _ => Ok(Expr::Value(
12778                    Value::SingleQuotedString(parser.parse_literal_string()?).with_span(span),
12779                )),
12780            }
12781        };
12782
12783        Ok(CreateFunctionBody::AsBeforeOptions {
12784            body: parse_string_expr(self)?,
12785            link_symbol: if self.consume_token(&Token::Comma) {
12786                Some(parse_string_expr(self)?)
12787            } else {
12788                None
12789            },
12790        })
12791    }
12792
12793    /// Parse a literal string
12794    pub fn parse_literal_string(&mut self) -> Result<String, ParserError> {
12795        let next_token = self.next_token();
12796        match next_token.token {
12797            Token::Word(Word {
12798                value,
12799                keyword: Keyword::NoKeyword,
12800                ..
12801            }) => Ok(value),
12802            Token::SingleQuotedString(s) => Ok(s),
12803            Token::DoubleQuotedString(s) => Ok(s),
12804            Token::EscapedStringLiteral(s) if dialect_of!(self is PostgreSqlDialect | GenericDialect) => {
12805                Ok(s)
12806            }
12807            Token::UnicodeStringLiteral(s) => Ok(s),
12808            _ => self.expected("literal string", next_token),
12809        }
12810    }
12811
12812    /// Parse a boolean string
12813    pub(crate) fn parse_boolean_string(&mut self) -> Result<bool, ParserError> {
12814        match self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]) {
12815            Some(Keyword::TRUE) => Ok(true),
12816            Some(Keyword::FALSE) => Ok(false),
12817            _ => self.expected_ref("TRUE or FALSE", self.peek_token_ref()),
12818        }
12819    }
12820
12821    /// Parse the `IS [NOT] JSON` predicate after `JSON` (and optional `NOT`) was consumed.
12822    fn parse_is_json_predicate(&mut self, expr: Expr, negated: bool) -> Result<Expr, ParserError> {
12823        let kind = match self.parse_one_of_keywords(&[
12824            Keyword::VALUE,
12825            Keyword::SCALAR,
12826            Keyword::ARRAY,
12827            Keyword::OBJECT,
12828        ]) {
12829            Some(Keyword::VALUE) => Some(JsonPredicateType::Value),
12830            Some(Keyword::SCALAR) => Some(JsonPredicateType::Scalar),
12831            Some(Keyword::ARRAY) => Some(JsonPredicateType::Array),
12832            Some(Keyword::OBJECT) => Some(JsonPredicateType::Object),
12833            _ => None,
12834        };
12835
12836        let unique_keys = match self.parse_one_of_keywords(&[Keyword::WITH, Keyword::WITHOUT]) {
12837            Some(Keyword::WITH) => {
12838                self.expect_keyword_is(Keyword::UNIQUE)?;
12839                let _ = self.parse_keyword(Keyword::KEYS);
12840                Some(JsonKeyUniqueness::WithUniqueKeys)
12841            }
12842            Some(Keyword::WITHOUT) => {
12843                self.expect_keyword_is(Keyword::UNIQUE)?;
12844                let _ = self.parse_keyword(Keyword::KEYS);
12845                Some(JsonKeyUniqueness::WithoutUniqueKeys)
12846            }
12847            _ => None,
12848        };
12849
12850        Ok(Expr::IsJson {
12851            expr: Box::new(expr),
12852            kind,
12853            unique_keys,
12854            negated,
12855        })
12856    }
12857
12858    /// Parse a literal unicode normalization clause
12859    pub fn parse_unicode_is_normalized(&mut self, expr: Expr) -> Result<Expr, ParserError> {
12860        let neg = self.parse_keyword(Keyword::NOT);
12861        let normalized_form = self.maybe_parse(|parser| {
12862            match parser.parse_one_of_keywords(&[
12863                Keyword::NFC,
12864                Keyword::NFD,
12865                Keyword::NFKC,
12866                Keyword::NFKD,
12867            ]) {
12868                Some(Keyword::NFC) => Ok(NormalizationForm::NFC),
12869                Some(Keyword::NFD) => Ok(NormalizationForm::NFD),
12870                Some(Keyword::NFKC) => Ok(NormalizationForm::NFKC),
12871                Some(Keyword::NFKD) => Ok(NormalizationForm::NFKD),
12872                _ => parser.expected_ref("unicode normalization form", parser.peek_token_ref()),
12873            }
12874        })?;
12875        if self.parse_keyword(Keyword::NORMALIZED) {
12876            return Ok(Expr::IsNormalized {
12877                expr: Box::new(expr),
12878                form: normalized_form,
12879                negated: neg,
12880            });
12881        }
12882        self.expected_ref("unicode normalization form", self.peek_token_ref())
12883    }
12884
12885    /// Parse parenthesized enum members, used with `ENUM(...)` type definitions.
12886    pub fn parse_enum_values(&mut self) -> Result<Vec<EnumMember>, ParserError> {
12887        self.expect_token(&Token::LParen)?;
12888        let values = self.parse_comma_separated(|parser| {
12889            let name = parser.parse_literal_string()?;
12890            let e = if parser.consume_token(&Token::Eq) {
12891                let value = parser.parse_number()?;
12892                EnumMember::NamedValue(name, value)
12893            } else {
12894                EnumMember::Name(name)
12895            };
12896            Ok(e)
12897        })?;
12898        self.expect_token(&Token::RParen)?;
12899
12900        Ok(values)
12901    }
12902
12903    /// Parse a SQL datatype (in the context of a CREATE TABLE statement for example)
12904    pub fn parse_data_type(&mut self) -> Result<DataType, ParserError> {
12905        let (ty, trailing_bracket) = self.parse_data_type_helper()?;
12906        if trailing_bracket.0 {
12907            return parser_err!(
12908                format!("unmatched > after parsing data type {ty}"),
12909                self.peek_token_ref()
12910            );
12911        }
12912
12913        Ok(ty)
12914    }
12915
12916    #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
12917    fn parse_data_type_helper(
12918        &mut self,
12919    ) -> Result<(DataType, MatchedTrailingBracket), ParserError> {
12920        let _guard = self.recursion_counter.try_decrease()?;
12921
12922        let dialect = self.dialect;
12923        self.advance_token();
12924        let next_token = self.get_current_token();
12925        let next_token_index = self.get_current_index();
12926
12927        let mut trailing_bracket: MatchedTrailingBracket = false.into();
12928        let mut data = match &next_token.token {
12929            Token::Word(w) => match w.keyword {
12930                Keyword::BOOLEAN => Ok(DataType::Boolean),
12931                Keyword::BOOL => Ok(DataType::Bool),
12932                Keyword::FLOAT => {
12933                    let precision = self.parse_exact_number_optional_precision_scale()?;
12934
12935                    if self.parse_keyword(Keyword::UNSIGNED) {
12936                        Ok(DataType::FloatUnsigned(precision))
12937                    } else {
12938                        Ok(DataType::Float(precision))
12939                    }
12940                }
12941                Keyword::REAL => {
12942                    if self.parse_keyword(Keyword::UNSIGNED) {
12943                        Ok(DataType::RealUnsigned)
12944                    } else {
12945                        Ok(DataType::Real)
12946                    }
12947                }
12948                Keyword::FLOAT4 => Ok(DataType::Float4),
12949                Keyword::FLOAT32 => Ok(DataType::Float32),
12950                Keyword::FLOAT64 => Ok(DataType::Float64),
12951                Keyword::FLOAT8 => Ok(DataType::Float8),
12952                Keyword::DOUBLE => {
12953                    if self.parse_keyword(Keyword::PRECISION) {
12954                        if self.parse_keyword(Keyword::UNSIGNED) {
12955                            Ok(DataType::DoublePrecisionUnsigned)
12956                        } else {
12957                            Ok(DataType::DoublePrecision)
12958                        }
12959                    } else {
12960                        let precision = self.parse_exact_number_optional_precision_scale()?;
12961
12962                        if self.parse_keyword(Keyword::UNSIGNED) {
12963                            Ok(DataType::DoubleUnsigned(precision))
12964                        } else {
12965                            Ok(DataType::Double(precision))
12966                        }
12967                    }
12968                }
12969                Keyword::TINYINT => {
12970                    let optional_precision = self.parse_optional_precision();
12971                    if self.parse_keyword(Keyword::UNSIGNED) {
12972                        Ok(DataType::TinyIntUnsigned(optional_precision?))
12973                    } else {
12974                        if dialect.supports_data_type_signed_suffix() {
12975                            let _ = self.parse_keyword(Keyword::SIGNED);
12976                        }
12977                        Ok(DataType::TinyInt(optional_precision?))
12978                    }
12979                }
12980                Keyword::INT2 => {
12981                    let optional_precision = self.parse_optional_precision();
12982                    if self.parse_keyword(Keyword::UNSIGNED) {
12983                        Ok(DataType::Int2Unsigned(optional_precision?))
12984                    } else {
12985                        Ok(DataType::Int2(optional_precision?))
12986                    }
12987                }
12988                Keyword::SMALLINT => {
12989                    let optional_precision = self.parse_optional_precision();
12990                    if self.parse_keyword(Keyword::UNSIGNED) {
12991                        Ok(DataType::SmallIntUnsigned(optional_precision?))
12992                    } else {
12993                        if dialect.supports_data_type_signed_suffix() {
12994                            let _ = self.parse_keyword(Keyword::SIGNED);
12995                        }
12996                        Ok(DataType::SmallInt(optional_precision?))
12997                    }
12998                }
12999                Keyword::MEDIUMINT => {
13000                    let optional_precision = self.parse_optional_precision();
13001                    if self.parse_keyword(Keyword::UNSIGNED) {
13002                        Ok(DataType::MediumIntUnsigned(optional_precision?))
13003                    } else {
13004                        if dialect.supports_data_type_signed_suffix() {
13005                            let _ = self.parse_keyword(Keyword::SIGNED);
13006                        }
13007                        Ok(DataType::MediumInt(optional_precision?))
13008                    }
13009                }
13010                Keyword::INT => {
13011                    let optional_precision = self.parse_optional_precision();
13012                    if self.parse_keyword(Keyword::UNSIGNED) {
13013                        Ok(DataType::IntUnsigned(optional_precision?))
13014                    } else {
13015                        if dialect.supports_data_type_signed_suffix() {
13016                            let _ = self.parse_keyword(Keyword::SIGNED);
13017                        }
13018                        Ok(DataType::Int(optional_precision?))
13019                    }
13020                }
13021                Keyword::INT4 => {
13022                    let optional_precision = self.parse_optional_precision();
13023                    if self.parse_keyword(Keyword::UNSIGNED) {
13024                        Ok(DataType::Int4Unsigned(optional_precision?))
13025                    } else {
13026                        Ok(DataType::Int4(optional_precision?))
13027                    }
13028                }
13029                Keyword::INT8 => {
13030                    let optional_precision = self.parse_optional_precision();
13031                    if self.parse_keyword(Keyword::UNSIGNED) {
13032                        Ok(DataType::Int8Unsigned(optional_precision?))
13033                    } else {
13034                        Ok(DataType::Int8(optional_precision?))
13035                    }
13036                }
13037                Keyword::INT16 => Ok(DataType::Int16),
13038                Keyword::INT32 => Ok(DataType::Int32),
13039                Keyword::INT64 => Ok(DataType::Int64),
13040                Keyword::INT128 => Ok(DataType::Int128),
13041                Keyword::INT256 => Ok(DataType::Int256),
13042                Keyword::INTEGER => {
13043                    let optional_precision = self.parse_optional_precision();
13044                    if self.parse_keyword(Keyword::UNSIGNED) {
13045                        Ok(DataType::IntegerUnsigned(optional_precision?))
13046                    } else {
13047                        if dialect.supports_data_type_signed_suffix() {
13048                            let _ = self.parse_keyword(Keyword::SIGNED);
13049                        }
13050                        Ok(DataType::Integer(optional_precision?))
13051                    }
13052                }
13053                Keyword::BIGINT => {
13054                    let optional_precision = self.parse_optional_precision();
13055                    if self.parse_keyword(Keyword::UNSIGNED) {
13056                        Ok(DataType::BigIntUnsigned(optional_precision?))
13057                    } else {
13058                        if dialect.supports_data_type_signed_suffix() {
13059                            let _ = self.parse_keyword(Keyword::SIGNED);
13060                        }
13061                        Ok(DataType::BigInt(optional_precision?))
13062                    }
13063                }
13064                Keyword::HUGEINT => Ok(DataType::HugeInt),
13065                Keyword::UBIGINT => Ok(DataType::UBigInt),
13066                Keyword::UHUGEINT => Ok(DataType::UHugeInt),
13067                Keyword::USMALLINT => Ok(DataType::USmallInt),
13068                Keyword::UTINYINT => Ok(DataType::UTinyInt),
13069                Keyword::UINT8 => Ok(DataType::UInt8),
13070                Keyword::UINT16 => Ok(DataType::UInt16),
13071                Keyword::UINT32 => Ok(DataType::UInt32),
13072                Keyword::UINT64 => Ok(DataType::UInt64),
13073                Keyword::UINT128 => Ok(DataType::UInt128),
13074                Keyword::UINT256 => Ok(DataType::UInt256),
13075                Keyword::VARCHAR => Ok(DataType::Varchar(self.parse_optional_character_length()?)),
13076                Keyword::NVARCHAR => {
13077                    Ok(DataType::Nvarchar(self.parse_optional_character_length()?))
13078                }
13079                Keyword::CHARACTER => {
13080                    if self.parse_keyword(Keyword::VARYING) {
13081                        Ok(DataType::CharacterVarying(
13082                            self.parse_optional_character_length()?,
13083                        ))
13084                    } else if self.parse_keywords(&[Keyword::LARGE, Keyword::OBJECT]) {
13085                        Ok(DataType::CharacterLargeObject(
13086                            self.parse_optional_precision()?,
13087                        ))
13088                    } else {
13089                        Ok(DataType::Character(self.parse_optional_character_length()?))
13090                    }
13091                }
13092                Keyword::CHAR => {
13093                    if self.parse_keyword(Keyword::VARYING) {
13094                        Ok(DataType::CharVarying(
13095                            self.parse_optional_character_length()?,
13096                        ))
13097                    } else if self.parse_keywords(&[Keyword::LARGE, Keyword::OBJECT]) {
13098                        Ok(DataType::CharLargeObject(self.parse_optional_precision()?))
13099                    } else {
13100                        Ok(DataType::Char(self.parse_optional_character_length()?))
13101                    }
13102                }
13103                Keyword::CLOB => Ok(DataType::Clob(self.parse_optional_precision()?)),
13104                Keyword::BINARY => Ok(DataType::Binary(self.parse_optional_precision()?)),
13105                Keyword::VARBINARY => Ok(DataType::Varbinary(self.parse_optional_binary_length()?)),
13106                Keyword::BLOB => Ok(DataType::Blob(self.parse_optional_precision()?)),
13107                Keyword::TINYBLOB => Ok(DataType::TinyBlob),
13108                Keyword::MEDIUMBLOB => Ok(DataType::MediumBlob),
13109                Keyword::LONGBLOB => Ok(DataType::LongBlob),
13110                Keyword::LONG if self.dialect.supports_long_type_as_bigint() => {
13111                    Ok(DataType::BigInt(None))
13112                }
13113                Keyword::BYTES => Ok(DataType::Bytes(self.parse_optional_precision()?)),
13114                Keyword::BIT => {
13115                    if self.parse_keyword(Keyword::VARYING) {
13116                        Ok(DataType::BitVarying(self.parse_optional_precision()?))
13117                    } else {
13118                        Ok(DataType::Bit(self.parse_optional_precision()?))
13119                    }
13120                }
13121                Keyword::VARBIT => Ok(DataType::VarBit(self.parse_optional_precision()?)),
13122                Keyword::UUID => Ok(DataType::Uuid),
13123                Keyword::DATE => Ok(DataType::Date),
13124                Keyword::DATE32 => Ok(DataType::Date32),
13125                Keyword::DATETIME => Ok(DataType::Datetime(self.parse_optional_precision()?)),
13126                Keyword::DATETIME64 => {
13127                    self.prev_token();
13128                    let (precision, time_zone) = self.parse_datetime_64()?;
13129                    Ok(DataType::Datetime64(precision, time_zone))
13130                }
13131                Keyword::TIMESTAMP => {
13132                    let precision = self.parse_optional_precision()?;
13133                    let tz = if self.parse_keyword(Keyword::WITH) {
13134                        self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
13135                        TimezoneInfo::WithTimeZone
13136                    } else if self.parse_keyword(Keyword::WITHOUT) {
13137                        self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
13138                        TimezoneInfo::WithoutTimeZone
13139                    } else {
13140                        TimezoneInfo::None
13141                    };
13142                    Ok(DataType::Timestamp(precision, tz))
13143                }
13144                Keyword::TIMESTAMPTZ => Ok(DataType::Timestamp(
13145                    self.parse_optional_precision()?,
13146                    TimezoneInfo::Tz,
13147                )),
13148                Keyword::TIMESTAMP_NTZ => {
13149                    Ok(DataType::TimestampNtz(self.parse_optional_precision()?))
13150                }
13151                Keyword::TIME => {
13152                    let precision = self.parse_optional_precision()?;
13153                    let tz = if self.parse_keyword(Keyword::WITH) {
13154                        self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
13155                        TimezoneInfo::WithTimeZone
13156                    } else if self.parse_keyword(Keyword::WITHOUT) {
13157                        self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
13158                        TimezoneInfo::WithoutTimeZone
13159                    } else {
13160                        TimezoneInfo::None
13161                    };
13162                    Ok(DataType::Time(precision, tz))
13163                }
13164                Keyword::TIMETZ => Ok(DataType::Time(
13165                    self.parse_optional_precision()?,
13166                    TimezoneInfo::Tz,
13167                )),
13168                Keyword::INTERVAL => {
13169                    if self.dialect.supports_interval_options() {
13170                        let fields = self.maybe_parse_optional_interval_fields()?;
13171                        let precision = self.parse_optional_precision()?;
13172                        Ok(DataType::Interval { fields, precision })
13173                    } else {
13174                        Ok(DataType::Interval {
13175                            fields: None,
13176                            precision: None,
13177                        })
13178                    }
13179                }
13180                Keyword::JSON => Ok(DataType::JSON),
13181                Keyword::JSONB => Ok(DataType::JSONB),
13182                Keyword::REGCLASS => Ok(DataType::Regclass),
13183                Keyword::STRING => Ok(DataType::String(self.parse_optional_precision()?)),
13184                Keyword::FIXEDSTRING => {
13185                    self.expect_token(&Token::LParen)?;
13186                    let character_length = self.parse_literal_uint()?;
13187                    self.expect_token(&Token::RParen)?;
13188                    Ok(DataType::FixedString(character_length))
13189                }
13190                Keyword::TEXT => {
13191                    if let Some(modifiers) = self.parse_optional_type_modifiers()? {
13192                        Ok(DataType::Custom(
13193                            ObjectName::from(vec![Ident::new("TEXT")]),
13194                            modifiers,
13195                        ))
13196                    } else {
13197                        Ok(DataType::Text)
13198                    }
13199                }
13200                Keyword::TINYTEXT => Ok(DataType::TinyText),
13201                Keyword::MEDIUMTEXT => Ok(DataType::MediumText),
13202                Keyword::LONGTEXT => Ok(DataType::LongText),
13203                Keyword::BYTEA => Ok(DataType::Bytea),
13204                Keyword::NUMERIC => Ok(DataType::Numeric(
13205                    self.parse_exact_number_optional_precision_scale()?,
13206                )),
13207                Keyword::DECIMAL => {
13208                    let precision = self.parse_exact_number_optional_precision_scale()?;
13209
13210                    if self.parse_keyword(Keyword::UNSIGNED) {
13211                        Ok(DataType::DecimalUnsigned(precision))
13212                    } else {
13213                        Ok(DataType::Decimal(precision))
13214                    }
13215                }
13216                Keyword::DEC => {
13217                    let precision = self.parse_exact_number_optional_precision_scale()?;
13218
13219                    if self.parse_keyword(Keyword::UNSIGNED) {
13220                        Ok(DataType::DecUnsigned(precision))
13221                    } else {
13222                        Ok(DataType::Dec(precision))
13223                    }
13224                }
13225                Keyword::BIGNUMERIC => Ok(DataType::BigNumeric(
13226                    self.parse_exact_number_optional_precision_scale()?,
13227                )),
13228                Keyword::BIGDECIMAL => Ok(DataType::BigDecimal(
13229                    self.parse_exact_number_optional_precision_scale()?,
13230                )),
13231                Keyword::ENUM => Ok(DataType::Enum(self.parse_enum_values()?, None)),
13232                Keyword::ENUM8 => Ok(DataType::Enum(self.parse_enum_values()?, Some(8))),
13233                Keyword::ENUM16 => Ok(DataType::Enum(self.parse_enum_values()?, Some(16))),
13234                Keyword::SET => Ok(DataType::Set(self.parse_string_values()?)),
13235                Keyword::ARRAY => {
13236                    if self.dialect.supports_array_typedef_with_parentheses() {
13237                        if self.peek_token_ref().token == Token::LParen {
13238                            self.expect_token(&Token::LParen)?;
13239                            let internal_type = self.parse_data_type()?;
13240                            let not_null = self.dialect.supports_array_element_not_null()
13241                                && self.parse_keywords(&[Keyword::NOT, Keyword::NULL]);
13242                            self.expect_token(&Token::RParen)?;
13243
13244                            if not_null {
13245                                Ok(DataType::Array(ArrayElemTypeDef::ParenthesisNotNull(
13246                                    Box::new(internal_type),
13247                                )))
13248                            } else {
13249                                Ok(DataType::Array(ArrayElemTypeDef::Parenthesis(Box::new(
13250                                    internal_type,
13251                                ))))
13252                            }
13253                        } else if self.dialect.supports_array_typedef_without_element_type() {
13254                            Ok(DataType::Array(ArrayElemTypeDef::None))
13255                        } else {
13256                            self.expected("(", self.peek_token())
13257                        }
13258                    } else if self.dialect.supports_array_typedef_without_element_type() {
13259                        Ok(DataType::Array(ArrayElemTypeDef::None))
13260                    } else {
13261                        self.expect_token(&Token::Lt)?;
13262                        let (inside_type, _trailing_bracket) =
13263                            self.parse_data_type_with_optional_collation()?;
13264                        trailing_bracket = self.expect_closing_angle_bracket(_trailing_bracket)?;
13265                        Ok(DataType::Array(ArrayElemTypeDef::AngleBracket(Box::new(
13266                            inside_type,
13267                        ))))
13268                    }
13269                }
13270                Keyword::OBJECT if self.peek_token_ref().token == Token::LParen => {
13271                    if let Some(fields) =
13272                        self.maybe_parse(|parser| parser.parse_structured_object_type_def())?
13273                    {
13274                        Ok(DataType::Object(fields))
13275                    } else {
13276                        self.prev_token();
13277                        let type_name = self.parse_object_name(false)?;
13278                        let modifiers = self.parse_optional_type_modifiers()?.unwrap_or_default();
13279                        Ok(DataType::Custom(type_name, modifiers))
13280                    }
13281                }
13282                Keyword::STRUCT if dialect_is!(dialect is DuckDbDialect) => {
13283                    self.prev_token();
13284                    let field_defs = self.parse_duckdb_struct_type_def()?;
13285                    Ok(DataType::Struct(field_defs, StructBracketKind::Parentheses))
13286                }
13287                Keyword::STRUCT if self.dialect.supports_struct_literal() => {
13288                    self.prev_token();
13289                    let (field_defs, _trailing_bracket) =
13290                        self.parse_struct_type_def(Self::parse_struct_field_def)?;
13291                    trailing_bracket = _trailing_bracket;
13292                    Ok(DataType::Struct(
13293                        field_defs,
13294                        StructBracketKind::AngleBrackets,
13295                    ))
13296                }
13297                Keyword::UNION if dialect_is!(dialect is DuckDbDialect | GenericDialect) => {
13298                    self.prev_token();
13299                    let fields = self.parse_union_type_def()?;
13300                    Ok(DataType::Union(fields))
13301                }
13302                Keyword::NULLABLE if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13303                    Ok(self.parse_sub_type(DataType::Nullable)?)
13304                }
13305                Keyword::LOWCARDINALITY if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13306                    Ok(self.parse_sub_type(DataType::LowCardinality)?)
13307                }
13308                Keyword::MAP if self.dialect.supports_map_literal_with_angle_brackets() => {
13309                    self.expect_token(&Token::Lt)?;
13310                    let (key_data_type, key_trailing_bracket) =
13311                        self.parse_data_type_with_optional_collation()?;
13312                    if key_trailing_bracket.0 {
13313                        return parser_err!(
13314                            format!("unmatched > after parsing data type {key_data_type}"),
13315                            self.peek_token_ref()
13316                        );
13317                    }
13318                    self.expect_token(&Token::Comma)?;
13319                    let (value_data_type, _trailing_bracket) =
13320                        self.parse_data_type_with_optional_collation()?;
13321                    trailing_bracket = self.expect_closing_angle_bracket(_trailing_bracket)?;
13322                    Ok(DataType::Map(
13323                        Box::new(key_data_type),
13324                        Box::new(value_data_type),
13325                        MapBracketKind::AngleBrackets,
13326                    ))
13327                }
13328                Keyword::MAP if self.dialect.supports_map_typedef_with_parentheses() => {
13329                    self.prev_token();
13330                    let (key_data_type, value_data_type, value_not_null) =
13331                        self.parse_parenthesized_map_type_def()?;
13332                    let bracket = if value_not_null {
13333                        MapBracketKind::ParenthesesNotNull
13334                    } else {
13335                        MapBracketKind::Parentheses
13336                    };
13337                    Ok(DataType::Map(
13338                        Box::new(key_data_type),
13339                        Box::new(value_data_type),
13340                        bracket,
13341                    ))
13342                }
13343                Keyword::NESTED if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13344                    self.expect_token(&Token::LParen)?;
13345                    let field_defs = self.parse_comma_separated(Parser::parse_column_def)?;
13346                    self.expect_token(&Token::RParen)?;
13347                    Ok(DataType::Nested(field_defs))
13348                }
13349                Keyword::TUPLE if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13350                    self.prev_token();
13351                    let field_defs = self.parse_click_house_tuple_def()?;
13352                    Ok(DataType::Tuple(field_defs))
13353                }
13354                Keyword::TRIGGER => Ok(DataType::Trigger),
13355                Keyword::ANY if self.peek_keyword(Keyword::TYPE) => {
13356                    let _ = self.parse_keyword(Keyword::TYPE);
13357                    Ok(DataType::AnyType)
13358                }
13359                Keyword::TABLE => {
13360                    // an LParen after the TABLE keyword indicates that table columns are being defined
13361                    // whereas no LParen indicates an anonymous table expression will be returned
13362                    if self.peek_token_ref().token == Token::LParen {
13363                        let columns = self.parse_returns_table_columns()?;
13364                        Ok(DataType::Table(Some(columns)))
13365                    } else {
13366                        Ok(DataType::Table(None))
13367                    }
13368                }
13369                Keyword::SIGNED => {
13370                    if self.parse_keyword(Keyword::INTEGER) {
13371                        Ok(DataType::SignedInteger)
13372                    } else {
13373                        Ok(DataType::Signed)
13374                    }
13375                }
13376                Keyword::UNSIGNED => {
13377                    if self.parse_keyword(Keyword::INTEGER) {
13378                        Ok(DataType::UnsignedInteger)
13379                    } else {
13380                        Ok(DataType::Unsigned)
13381                    }
13382                }
13383                Keyword::TSVECTOR if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) => {
13384                    Ok(DataType::TsVector)
13385                }
13386                Keyword::TSQUERY if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) => {
13387                    Ok(DataType::TsQuery)
13388                }
13389                _ => {
13390                    self.prev_token();
13391                    let type_name = self.parse_object_name(false)?;
13392                    if let Some(modifiers) = self.parse_optional_type_modifiers()? {
13393                        Ok(DataType::Custom(type_name, modifiers))
13394                    } else {
13395                        Ok(DataType::Custom(type_name, vec![]))
13396                    }
13397                }
13398            },
13399            _ => self.expected_at("a data type name", next_token_index),
13400        }?;
13401
13402        if self.dialect.supports_array_typedef_with_brackets() {
13403            while self.consume_token(&Token::LBracket) {
13404                // Parse optional array data type size
13405                let size = self.maybe_parse(|p| p.parse_literal_uint())?;
13406                self.expect_token(&Token::RBracket)?;
13407                data = DataType::Array(ArrayElemTypeDef::SquareBracket(Box::new(data), size))
13408            }
13409        }
13410
13411        // Type-qualified array, e.g. `INT ARRAY` or `INT ARRAY[3]`. One-dimensional
13412        // with a single optional size. The `ARRAY` keyword is unambiguous everywhere.
13413        if self.parse_keyword(Keyword::ARRAY) {
13414            let size = if self.consume_token(&Token::LBracket) {
13415                let size = self.maybe_parse(|p| p.parse_literal_uint())?;
13416                self.expect_token(&Token::RBracket)?;
13417                size
13418            } else {
13419                None
13420            };
13421            data = DataType::Array(ArrayElemTypeDef::Qualified(Box::new(data), size));
13422        }
13423
13424        Ok((data, trailing_bracket))
13425    }
13426
13427    fn parse_data_type_with_optional_collation(
13428        &mut self,
13429    ) -> Result<(DataType, MatchedTrailingBracket), ParserError> {
13430        let (mut data_type, trailing_bracket) = self.parse_data_type_helper()?;
13431        if !trailing_bracket.0
13432            && self.dialect.supports_data_type_collation()
13433            && self.parse_keyword(Keyword::COLLATE)
13434        {
13435            data_type = DataType::Collate(Box::new(data_type), self.parse_object_name(false)?);
13436        }
13437        Ok((data_type, trailing_bracket))
13438    }
13439
13440    fn parse_returns_table_column(&mut self) -> Result<ColumnDef, ParserError> {
13441        self.parse_column_def()
13442    }
13443
13444    fn parse_returns_table_columns(&mut self) -> Result<Vec<ColumnDef>, ParserError> {
13445        self.expect_token(&Token::LParen)?;
13446        let columns = self.parse_comma_separated(Parser::parse_returns_table_column)?;
13447        self.expect_token(&Token::RParen)?;
13448        Ok(columns)
13449    }
13450
13451    /// Parse a parenthesized, comma-separated list of single-quoted strings.
13452    pub fn parse_string_values(&mut self) -> Result<Vec<String>, ParserError> {
13453        self.expect_token(&Token::LParen)?;
13454        let mut values = Vec::new();
13455        loop {
13456            let next_token = self.next_token();
13457            match next_token.token {
13458                Token::SingleQuotedString(value) => values.push(value),
13459                _ => self.expected("a string", next_token)?,
13460            }
13461            let next_token = self.next_token();
13462            match next_token.token {
13463                Token::Comma => (),
13464                Token::RParen => break,
13465                _ => self.expected(", or }", next_token)?,
13466            }
13467        }
13468        Ok(values)
13469    }
13470
13471    /// Strictly parse `identifier AS identifier`
13472    pub fn parse_identifier_with_alias(&mut self) -> Result<IdentWithAlias, ParserError> {
13473        let ident = self.parse_identifier()?;
13474        self.expect_keyword_is(Keyword::AS)?;
13475        let alias = self.parse_identifier()?;
13476        Ok(IdentWithAlias { ident, alias })
13477    }
13478
13479    /// Parse `identifier [AS] identifier` where the AS keyword is optional
13480    fn parse_identifier_with_optional_alias(&mut self) -> Result<IdentWithAlias, ParserError> {
13481        let ident = self.parse_identifier()?;
13482        let _after_as = self.parse_keyword(Keyword::AS);
13483        let alias = self.parse_identifier()?;
13484        Ok(IdentWithAlias { ident, alias })
13485    }
13486
13487    /// Parse comma-separated list of parenthesized queries for pipe operators
13488    fn parse_pipe_operator_queries(&mut self) -> Result<Vec<Query>, ParserError> {
13489        self.parse_comma_separated(|parser| {
13490            parser.expect_token(&Token::LParen)?;
13491            let query = parser.parse_query()?;
13492            parser.expect_token(&Token::RParen)?;
13493            Ok(*query)
13494        })
13495    }
13496
13497    /// Parse set quantifier for pipe operators that require DISTINCT. E.g. INTERSECT and EXCEPT
13498    fn parse_distinct_required_set_quantifier(
13499        &mut self,
13500        operator_name: &str,
13501    ) -> Result<SetQuantifier, ParserError> {
13502        let quantifier = self.parse_set_quantifier(&Some(SetOperator::Intersect));
13503        match quantifier {
13504            SetQuantifier::Distinct | SetQuantifier::DistinctByName => Ok(quantifier),
13505            _ => Err(ParserError::ParserError(format!(
13506                "{operator_name} pipe operator requires DISTINCT modifier",
13507            ))),
13508        }
13509    }
13510
13511    /// Parse optional identifier alias (with or without AS keyword)
13512    fn parse_identifier_optional_alias(&mut self) -> Result<Option<Ident>, ParserError> {
13513        if self.parse_keyword(Keyword::AS) {
13514            Ok(Some(self.parse_identifier()?))
13515        } else {
13516            // Check if the next token is an identifier (implicit alias)
13517            self.maybe_parse(|parser| parser.parse_identifier())
13518        }
13519    }
13520
13521    /// Optionally parses an alias for a select list item
13522    fn maybe_parse_select_item_alias(&mut self) -> Result<Option<Ident>, ParserError> {
13523        fn validator(explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
13524            parser.dialect.is_select_item_alias(explicit, kw, parser)
13525        }
13526        self.parse_optional_alias_inner(None, validator)
13527    }
13528
13529    /// Optionally parses an alias for a table like in `... FROM generate_series(1, 10) AS t (col)`.
13530    /// In this case, the alias is allowed to optionally name the columns in the table, in
13531    /// addition to the table itself.
13532    pub fn maybe_parse_table_alias(&mut self) -> Result<Option<TableAlias>, ParserError> {
13533        fn validator(explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
13534            parser.dialect.is_table_factor_alias(explicit, kw, parser)
13535        }
13536        let explicit = self.peek_keyword(Keyword::AS);
13537        match self.parse_optional_alias_inner(None, validator)? {
13538            Some(name) => {
13539                let columns = self.parse_table_alias_column_defs()?;
13540                let at = if self.dialect.supports_partiql() && self.parse_keyword(Keyword::AT) {
13541                    Some(self.parse_identifier()?)
13542                } else {
13543                    None
13544                };
13545                Ok(Some(TableAlias {
13546                    explicit,
13547                    name,
13548                    columns,
13549                    at,
13550                }))
13551            }
13552            None => Ok(None),
13553        }
13554    }
13555
13556    fn parse_table_index_hints(&mut self) -> Result<Vec<TableIndexHints>, ParserError> {
13557        let mut hints = vec![];
13558        while let Some(hint_type) =
13559            self.parse_one_of_keywords(&[Keyword::USE, Keyword::IGNORE, Keyword::FORCE])
13560        {
13561            let hint_type = match hint_type {
13562                Keyword::USE => TableIndexHintType::Use,
13563                Keyword::IGNORE => TableIndexHintType::Ignore,
13564                Keyword::FORCE => TableIndexHintType::Force,
13565                _ => {
13566                    return self.expected_ref(
13567                        "expected to match USE/IGNORE/FORCE keyword",
13568                        self.peek_token_ref(),
13569                    )
13570                }
13571            };
13572            let index_type = match self.parse_one_of_keywords(&[Keyword::INDEX, Keyword::KEY]) {
13573                Some(Keyword::INDEX) => TableIndexType::Index,
13574                Some(Keyword::KEY) => TableIndexType::Key,
13575                _ => {
13576                    return self
13577                        .expected_ref("expected to match INDEX/KEY keyword", self.peek_token_ref())
13578                }
13579            };
13580            let for_clause = if self.parse_keyword(Keyword::FOR) {
13581                let clause = if self.parse_keyword(Keyword::JOIN) {
13582                    TableIndexHintForClause::Join
13583                } else if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
13584                    TableIndexHintForClause::OrderBy
13585                } else if self.parse_keywords(&[Keyword::GROUP, Keyword::BY]) {
13586                    TableIndexHintForClause::GroupBy
13587                } else {
13588                    return self.expected_ref(
13589                        "expected to match FOR/ORDER BY/GROUP BY table hint in for clause",
13590                        self.peek_token_ref(),
13591                    );
13592                };
13593                Some(clause)
13594            } else {
13595                None
13596            };
13597
13598            self.expect_token(&Token::LParen)?;
13599            let index_names = if self.peek_token_ref().token != Token::RParen {
13600                self.parse_comma_separated(Parser::parse_identifier)?
13601            } else {
13602                vec![]
13603            };
13604            self.expect_token(&Token::RParen)?;
13605            hints.push(TableIndexHints {
13606                hint_type,
13607                index_type,
13608                for_clause,
13609                index_names,
13610            });
13611        }
13612        Ok(hints)
13613    }
13614
13615    /// Wrapper for parse_optional_alias_inner, left for backwards-compatibility
13616    /// but new flows should use the context-specific methods such as `maybe_parse_select_item_alias`
13617    /// and `maybe_parse_table_alias`.
13618    pub fn parse_optional_alias(
13619        &mut self,
13620        reserved_kwds: &[Keyword],
13621    ) -> Result<Option<Ident>, ParserError> {
13622        fn validator(_explicit: bool, _kw: &Keyword, _parser: &mut Parser) -> bool {
13623            false
13624        }
13625        self.parse_optional_alias_inner(Some(reserved_kwds), validator)
13626    }
13627
13628    /// Parses an optional alias after a SQL element such as a select list item
13629    /// or a table name.
13630    ///
13631    /// This method accepts an optional list of reserved keywords or a function
13632    /// to call to validate if a keyword should be parsed as an alias, to allow
13633    /// callers to customize the parsing logic based on their context.
13634    fn parse_optional_alias_inner<F>(
13635        &mut self,
13636        reserved_kwds: Option<&[Keyword]>,
13637        validator: F,
13638    ) -> Result<Option<Ident>, ParserError>
13639    where
13640        F: Fn(bool, &Keyword, &mut Parser) -> bool,
13641    {
13642        let after_as = self.parse_keyword(Keyword::AS);
13643
13644        let next_token = self.next_token();
13645        match next_token.token {
13646            // Accepts a keyword as an alias if the AS keyword explicitly indicate an alias or if the
13647            // caller provided a list of reserved keywords and the keyword is not on that list.
13648            Token::Word(w)
13649                if reserved_kwds.is_some()
13650                    && (after_as || reserved_kwds.is_some_and(|x| !x.contains(&w.keyword))) =>
13651            {
13652                Ok(Some(w.into_ident(next_token.span)))
13653            }
13654            // Accepts a keyword as alias based on the caller's context, such as to what SQL element
13655            // this word is a potential alias of using the validator call-back. This allows for
13656            // dialect-specific logic.
13657            Token::Word(w) if validator(after_as, &w.keyword, self) => {
13658                Ok(Some(w.into_ident(next_token.span)))
13659            }
13660            // For backwards-compatibility, we accept quoted strings as aliases regardless of the context.
13661            Token::SingleQuotedString(s) => Ok(Some(Ident::with_quote('\'', s))),
13662            Token::DoubleQuotedString(s) => Ok(Some(Ident::with_quote('\"', s))),
13663            _ => {
13664                if after_as {
13665                    return self.expected("an identifier after AS", next_token);
13666                }
13667                self.prev_token();
13668                Ok(None) // no alias found
13669            }
13670        }
13671    }
13672
13673    /// Parse an optional `GROUP BY` clause, returning `Some(GroupByExpr)` when present.
13674    pub fn parse_optional_group_by(&mut self) -> Result<Option<GroupByExpr>, ParserError> {
13675        if self.parse_keywords(&[Keyword::GROUP, Keyword::BY]) {
13676            let expressions = if self.parse_keyword(Keyword::ALL) {
13677                None
13678            } else {
13679                Some(self.parse_comma_separated(Parser::parse_group_by_expr)?)
13680            };
13681
13682            let mut modifiers = vec![];
13683            if self.dialect.supports_group_by_with_modifier() {
13684                loop {
13685                    if !self.parse_keyword(Keyword::WITH) {
13686                        break;
13687                    }
13688                    let keyword = self.expect_one_of_keywords(&[
13689                        Keyword::ROLLUP,
13690                        Keyword::CUBE,
13691                        Keyword::TOTALS,
13692                    ])?;
13693                    modifiers.push(match keyword {
13694                        Keyword::ROLLUP => GroupByWithModifier::Rollup,
13695                        Keyword::CUBE => GroupByWithModifier::Cube,
13696                        Keyword::TOTALS => GroupByWithModifier::Totals,
13697                        _ => {
13698                            return parser_err!(
13699                                "BUG: expected to match GroupBy modifier keyword",
13700                                self.peek_token_ref().span.start
13701                            )
13702                        }
13703                    });
13704                }
13705            }
13706            if self.parse_keywords(&[Keyword::GROUPING, Keyword::SETS]) {
13707                self.expect_token(&Token::LParen)?;
13708                let result = self.parse_comma_separated(|p| {
13709                    if p.peek_token_ref().token == Token::LParen {
13710                        p.parse_tuple(true, true)
13711                    } else {
13712                        Ok(vec![p.parse_expr()?])
13713                    }
13714                })?;
13715                self.expect_token(&Token::RParen)?;
13716                modifiers.push(GroupByWithModifier::GroupingSets(Expr::GroupingSets(
13717                    result,
13718                )));
13719            };
13720            let group_by = match expressions {
13721                None => GroupByExpr::All(modifiers),
13722                Some(exprs) => GroupByExpr::Expressions(exprs, modifiers),
13723            };
13724            Ok(Some(group_by))
13725        } else {
13726            Ok(None)
13727        }
13728    }
13729
13730    /// Parse an optional `ORDER BY` clause, returning `Some(OrderBy)` when present.
13731    pub fn parse_optional_order_by(&mut self) -> Result<Option<OrderBy>, ParserError> {
13732        if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
13733            let order_by =
13734                if self.dialect.supports_order_by_all() && self.parse_keyword(Keyword::ALL) {
13735                    let order_by_options = self.parse_order_by_options()?;
13736                    OrderBy {
13737                        kind: OrderByKind::All(order_by_options),
13738                        interpolate: None,
13739                    }
13740                } else {
13741                    let exprs = self.parse_comma_separated(Parser::parse_order_by_expr)?;
13742                    let interpolate = if self.dialect.supports_interpolate() {
13743                        self.parse_interpolations()?
13744                    } else {
13745                        None
13746                    };
13747                    OrderBy {
13748                        kind: OrderByKind::Expressions(exprs),
13749                        interpolate,
13750                    }
13751                };
13752            Ok(Some(order_by))
13753        } else {
13754            Ok(None)
13755        }
13756    }
13757
13758    fn parse_optional_limit_clause(&mut self) -> Result<Option<LimitClause>, ParserError> {
13759        let mut offset = if self.parse_keyword(Keyword::OFFSET) {
13760            Some(self.parse_offset()?)
13761        } else {
13762            None
13763        };
13764
13765        let (limit, limit_by) = if self.parse_keyword(Keyword::LIMIT) {
13766            let expr = self.parse_limit()?;
13767
13768            if self.dialect.supports_limit_comma()
13769                && offset.is_none()
13770                && expr.is_some() // ALL not supported with comma
13771                && self.consume_token(&Token::Comma)
13772            {
13773                let offset = expr.ok_or_else(|| {
13774                    ParserError::ParserError(
13775                        "Missing offset for LIMIT <offset>, <limit>".to_string(),
13776                    )
13777                })?;
13778                return Ok(Some(LimitClause::OffsetCommaLimit {
13779                    offset,
13780                    limit: self.parse_expr()?,
13781                }));
13782            }
13783
13784            let limit_by = if self.dialect.supports_limit_by() && self.parse_keyword(Keyword::BY) {
13785                Some(self.parse_comma_separated(Parser::parse_expr)?)
13786            } else {
13787                None
13788            };
13789
13790            (Some(expr), limit_by)
13791        } else {
13792            (None, None)
13793        };
13794
13795        if offset.is_none() && limit.is_some() && self.parse_keyword(Keyword::OFFSET) {
13796            offset = Some(self.parse_offset()?);
13797        }
13798
13799        if offset.is_some() || (limit.is_some() && limit != Some(None)) || limit_by.is_some() {
13800            Ok(Some(LimitClause::LimitOffset {
13801                limit: limit.unwrap_or_default(),
13802                offset,
13803                limit_by: limit_by.unwrap_or_default(),
13804            }))
13805        } else {
13806            Ok(None)
13807        }
13808    }
13809
13810    /// Parse a table object for insertion
13811    /// e.g. `some_database.some_table` or `FUNCTION some_table_func(...)`
13812    pub fn parse_table_object(&mut self) -> Result<TableObject, ParserError> {
13813        if self.dialect.supports_insert_table_function() && self.parse_keyword(Keyword::FUNCTION) {
13814            let fn_name = self.parse_object_name(false)?;
13815            self.parse_function_call(fn_name)
13816                .map(TableObject::TableFunction)
13817        } else if self.dialect.supports_insert_table_query() && self.peek_subquery_or_cte_start() {
13818            self.parse_parenthesized(|p| p.parse_query())
13819                .map(TableObject::TableQuery)
13820        } else {
13821            self.parse_object_name(false).map(TableObject::TableName)
13822        }
13823    }
13824
13825    /// Parse a possibly qualified, possibly quoted identifier, e.g.
13826    /// `foo` or `myschema."table"
13827    ///
13828    /// The `in_table_clause` parameter indicates whether the object name is a table in a FROM, JOIN,
13829    /// or similar table clause. Currently, this is used only to support unquoted hyphenated identifiers
13830    /// in this context on BigQuery.
13831    pub fn parse_object_name(&mut self, in_table_clause: bool) -> Result<ObjectName, ParserError> {
13832        self.parse_object_name_inner(in_table_clause, false)
13833    }
13834
13835    /// Parse a possibly qualified, possibly quoted identifier, e.g.
13836    /// `foo` or `myschema."table"
13837    ///
13838    /// The `in_table_clause` parameter indicates whether the object name is a table in a FROM, JOIN,
13839    /// or similar table clause. Currently, this is used only to support unquoted hyphenated identifiers
13840    /// in this context on BigQuery.
13841    ///
13842    /// The `allow_wildcards` parameter indicates whether to allow for wildcards in the object name
13843    /// e.g. *, *.*, `foo`.*, or "foo"."bar"
13844    fn parse_object_name_inner(
13845        &mut self,
13846        in_table_clause: bool,
13847        allow_wildcards: bool,
13848    ) -> Result<ObjectName, ParserError> {
13849        let mut parts = vec![];
13850        if dialect_of!(self is BigQueryDialect) && in_table_clause {
13851            loop {
13852                let (ident, end_with_period) = self.parse_unquoted_hyphenated_identifier()?;
13853                parts.push(ObjectNamePart::Identifier(ident));
13854                if !self.consume_token(&Token::Period) && !end_with_period {
13855                    break;
13856                }
13857            }
13858        } else {
13859            loop {
13860                if allow_wildcards && self.peek_token_ref().token == Token::Mul {
13861                    let span = self.next_token().span;
13862                    parts.push(ObjectNamePart::Identifier(Ident {
13863                        value: Token::Mul.to_string(),
13864                        quote_style: None,
13865                        span,
13866                    }));
13867                } else if dialect_of!(self is BigQueryDialect) && in_table_clause {
13868                    let (ident, end_with_period) = self.parse_unquoted_hyphenated_identifier()?;
13869                    parts.push(ObjectNamePart::Identifier(ident));
13870                    if !self.consume_token(&Token::Period) && !end_with_period {
13871                        break;
13872                    }
13873                } else if self.dialect.supports_object_name_double_dot_notation()
13874                    && parts.len() == 1
13875                    && matches!(self.peek_token_ref().token, Token::Period)
13876                {
13877                    // Empty string here means default schema
13878                    parts.push(ObjectNamePart::Identifier(Ident::new("")));
13879                } else {
13880                    let ident = self.parse_identifier()?;
13881                    let part = if self
13882                        .dialect
13883                        .is_identifier_generating_function_name(&ident, &parts)
13884                    {
13885                        self.expect_token(&Token::LParen)?;
13886                        let args: Vec<FunctionArg> =
13887                            self.parse_comma_separated0(Self::parse_function_args, Token::RParen)?;
13888                        self.expect_token(&Token::RParen)?;
13889                        ObjectNamePart::Function(ObjectNamePartFunction { name: ident, args })
13890                    } else {
13891                        ObjectNamePart::Identifier(ident)
13892                    };
13893                    parts.push(part);
13894                }
13895
13896                if !self.consume_token(&Token::Period) {
13897                    break;
13898                }
13899            }
13900        }
13901
13902        // BigQuery accepts any number of quoted identifiers of a table name.
13903        // https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_identifiers
13904        if dialect_of!(self is BigQueryDialect)
13905            && parts.iter().any(|part| {
13906                part.as_ident()
13907                    .is_some_and(|ident| ident.value.contains('.'))
13908            })
13909        {
13910            parts = parts
13911                .into_iter()
13912                .flat_map(|part| match part.as_ident() {
13913                    Some(ident) => ident
13914                        .value
13915                        .split('.')
13916                        .map(|value| {
13917                            ObjectNamePart::Identifier(Ident {
13918                                value: value.into(),
13919                                quote_style: ident.quote_style,
13920                                span: ident.span,
13921                            })
13922                        })
13923                        .collect::<Vec<_>>(),
13924                    None => vec![part],
13925                })
13926                .collect()
13927        }
13928
13929        Ok(ObjectName(parts))
13930    }
13931
13932    /// Parse identifiers
13933    pub fn parse_identifiers(&mut self) -> Result<Vec<Ident>, ParserError> {
13934        let mut idents = vec![];
13935        loop {
13936            let token = self.peek_token_ref();
13937            match &token.token {
13938                Token::Word(w) => {
13939                    idents.push(w.to_ident(token.span));
13940                }
13941                Token::EOF | Token::Eq | Token::SemiColon | Token::VerticalBarRightAngleBracket => {
13942                    break
13943                }
13944                _ => {}
13945            }
13946            self.advance_token();
13947        }
13948        Ok(idents)
13949    }
13950
13951    /// Parse identifiers of form ident1[.identN]*
13952    ///
13953    /// Similar in functionality to [parse_identifiers], with difference
13954    /// being this function is much more strict about parsing a valid multipart identifier, not
13955    /// allowing extraneous tokens to be parsed, otherwise it fails.
13956    ///
13957    /// For example:
13958    ///
13959    /// ```rust
13960    /// use sqlparser::ast::Ident;
13961    /// use sqlparser::dialect::GenericDialect;
13962    /// use sqlparser::parser::Parser;
13963    ///
13964    /// let dialect = GenericDialect {};
13965    /// let expected = vec![Ident::new("one"), Ident::new("two")];
13966    ///
13967    /// // expected usage
13968    /// let sql = "one.two";
13969    /// let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
13970    /// let actual = parser.parse_multipart_identifier().unwrap();
13971    /// assert_eq!(&actual, &expected);
13972    ///
13973    /// // parse_identifiers is more loose on what it allows, parsing successfully
13974    /// let sql = "one + two";
13975    /// let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
13976    /// let actual = parser.parse_identifiers().unwrap();
13977    /// assert_eq!(&actual, &expected);
13978    ///
13979    /// // expected to strictly fail due to + separator
13980    /// let sql = "one + two";
13981    /// let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
13982    /// let actual = parser.parse_multipart_identifier().unwrap_err();
13983    /// assert_eq!(
13984    ///     actual.to_string(),
13985    ///     "sql parser error: Unexpected token in identifier: +"
13986    /// );
13987    /// ```
13988    ///
13989    /// [parse_identifiers]: Parser::parse_identifiers
13990    pub fn parse_multipart_identifier(&mut self) -> Result<Vec<Ident>, ParserError> {
13991        let mut idents = vec![];
13992
13993        // expecting at least one word for identifier
13994        let next_token = self.next_token();
13995        match next_token.token {
13996            Token::Word(w) => idents.push(w.into_ident(next_token.span)),
13997            Token::EOF => {
13998                return Err(ParserError::ParserError(
13999                    "Empty input when parsing identifier".to_string(),
14000                ))?
14001            }
14002            token => {
14003                return Err(ParserError::ParserError(format!(
14004                    "Unexpected token in identifier: {token}"
14005                )))?
14006            }
14007        };
14008
14009        // parse optional next parts if exist
14010        loop {
14011            match self.next_token().token {
14012                // ensure that optional period is succeeded by another identifier
14013                Token::Period => {
14014                    let next_token = self.next_token();
14015                    match next_token.token {
14016                        Token::Word(w) => idents.push(w.into_ident(next_token.span)),
14017                        Token::EOF => {
14018                            return Err(ParserError::ParserError(
14019                                "Trailing period in identifier".to_string(),
14020                            ))?
14021                        }
14022                        token => {
14023                            return Err(ParserError::ParserError(format!(
14024                                "Unexpected token following period in identifier: {token}"
14025                            )))?
14026                        }
14027                    }
14028                }
14029                Token::EOF => break,
14030                token => {
14031                    Err(ParserError::ParserError(format!(
14032                        "Unexpected token in identifier: {token}"
14033                    )))?;
14034                }
14035            }
14036        }
14037
14038        Ok(idents)
14039    }
14040
14041    /// Parse a simple one-word identifier (possibly quoted, possibly a keyword)
14042    pub fn parse_identifier(&mut self) -> Result<Ident, ParserError> {
14043        let next_token = self.next_token();
14044        match next_token.token {
14045            Token::Word(w) => Ok(w.into_ident(next_token.span)),
14046            Token::SingleQuotedString(s) => {
14047                Ok(Ident::with_quote_and_span('\'', next_token.span, s))
14048            }
14049            Token::DoubleQuotedString(s) => {
14050                Ok(Ident::with_quote_and_span('\"', next_token.span, s))
14051            }
14052            _ => self.expected("identifier", next_token),
14053        }
14054    }
14055
14056    /// On BigQuery, hyphens are permitted in unquoted identifiers inside of a FROM or
14057    /// TABLE clause.
14058    ///
14059    /// The first segment must be an ordinary unquoted identifier, e.g. it must not start
14060    /// with a digit. Subsequent segments are either must either be valid identifiers or
14061    /// integers, e.g. foo-123 is allowed, but foo-123a is not.
14062    ///
14063    /// [BigQuery-lexical](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical)
14064    ///
14065    /// Return a tuple of the identifier and a boolean indicating it ends with a period.
14066    fn parse_unquoted_hyphenated_identifier(&mut self) -> Result<(Ident, bool), ParserError> {
14067        match self.peek_token().token {
14068            Token::Word(w) => {
14069                let quote_style_is_none = w.quote_style.is_none();
14070                let mut requires_whitespace = false;
14071                let mut ident = w.into_ident(self.next_token().span);
14072                if quote_style_is_none {
14073                    while matches!(self.peek_token_no_skip().token, Token::Minus) {
14074                        self.next_token();
14075                        ident.value.push('-');
14076
14077                        let token = self
14078                            .next_token_no_skip()
14079                            .cloned()
14080                            .unwrap_or(TokenWithSpan::wrap(Token::EOF));
14081                        requires_whitespace = match token.token {
14082                            Token::Word(next_word) if next_word.quote_style.is_none() => {
14083                                ident.value.push_str(&next_word.value);
14084                                false
14085                            }
14086                            Token::Number(s, false) => {
14087                                // A number token can represent a decimal value ending with a period, e.g., `Number('123.')`.
14088                                // However, for an [ObjectName], it is part of a hyphenated identifier, e.g., `foo-123.bar`.
14089                                //
14090                                // If a number token is followed by a period, it is part of an [ObjectName].
14091                                // Return the identifier with `true` if the number token is followed by a period, indicating that
14092                                // parsing should continue for the next part of the hyphenated identifier.
14093                                if s.ends_with('.') {
14094                                    let Some(s) = s.split('.').next().filter(|s| {
14095                                        !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
14096                                    }) else {
14097                                        return self.expected(
14098                                            "continuation of hyphenated identifier",
14099                                            TokenWithSpan::new(Token::Number(s, false), token.span),
14100                                        );
14101                                    };
14102                                    ident.value.push_str(s);
14103                                    return Ok((ident, true));
14104                                } else {
14105                                    ident.value.push_str(&s);
14106                                }
14107                                // If next token is period, then it is part of an ObjectName and we don't expect whitespace
14108                                // after the number.
14109                                !matches!(self.peek_token_ref().token, Token::Period)
14110                            }
14111                            _ => {
14112                                return self
14113                                    .expected("continuation of hyphenated identifier", token);
14114                            }
14115                        }
14116                    }
14117
14118                    // If the last segment was a number, we must check that it's followed by whitespace,
14119                    // otherwise foo-123a will be parsed as `foo-123` with the alias `a`.
14120                    if requires_whitespace {
14121                        let token = self.next_token();
14122                        if !matches!(token.token, Token::EOF | Token::Whitespace(_)) {
14123                            return self
14124                                .expected("whitespace following hyphenated identifier", token);
14125                        }
14126                    }
14127                }
14128                Ok((ident, false))
14129            }
14130            _ => Ok((self.parse_identifier()?, false)),
14131        }
14132    }
14133
14134    /// Parses a parenthesized, comma-separated list of column definitions within a view.
14135    fn parse_view_columns(&mut self) -> Result<Vec<ViewColumnDef>, ParserError> {
14136        if self.consume_token(&Token::LParen) {
14137            if self.peek_token_ref().token == Token::RParen {
14138                self.next_token();
14139                Ok(vec![])
14140            } else {
14141                let cols = self.parse_comma_separated_with_trailing_commas(
14142                    Parser::parse_view_column,
14143                    self.dialect.supports_column_definition_trailing_commas(),
14144                    Self::is_reserved_for_column_alias,
14145                )?;
14146                self.expect_token(&Token::RParen)?;
14147                Ok(cols)
14148            }
14149        } else {
14150            Ok(vec![])
14151        }
14152    }
14153
14154    /// Parses a column definition within a view.
14155    fn parse_view_column(&mut self) -> Result<ViewColumnDef, ParserError> {
14156        let name = self.parse_identifier()?;
14157        let options = self.parse_view_column_options()?;
14158        let data_type = if dialect_of!(self is ClickHouseDialect) {
14159            Some(self.parse_data_type()?)
14160        } else {
14161            None
14162        };
14163        Ok(ViewColumnDef {
14164            name,
14165            data_type,
14166            options,
14167        })
14168    }
14169
14170    fn parse_view_column_options(&mut self) -> Result<Option<ColumnOptions>, ParserError> {
14171        let mut options = Vec::new();
14172        loop {
14173            let option = self.parse_optional_column_option()?;
14174            if let Some(option) = option {
14175                options.push(option);
14176            } else {
14177                break;
14178            }
14179        }
14180        if options.is_empty() {
14181            Ok(None)
14182        } else if self.dialect.supports_space_separated_column_options() {
14183            Ok(Some(ColumnOptions::SpaceSeparated(options)))
14184        } else {
14185            Ok(Some(ColumnOptions::CommaSeparated(options)))
14186        }
14187    }
14188
14189    /// Parses a parenthesized comma-separated list of unqualified, possibly quoted identifiers.
14190    /// For example: `(col1, "col 2", ...)`
14191    pub fn parse_parenthesized_column_list(
14192        &mut self,
14193        optional: IsOptional,
14194        allow_empty: bool,
14195    ) -> Result<Vec<Ident>, ParserError> {
14196        self.parse_parenthesized_column_list_inner(optional, allow_empty, |p| p.parse_identifier())
14197    }
14198
14199    /// Parse a parenthesized list of compound identifiers as expressions.
14200    pub fn parse_parenthesized_compound_identifier_list(
14201        &mut self,
14202        optional: IsOptional,
14203        allow_empty: bool,
14204    ) -> Result<Vec<Expr>, ParserError> {
14205        self.parse_parenthesized_column_list_inner(optional, allow_empty, |p| {
14206            Ok(Expr::CompoundIdentifier(
14207                p.parse_period_separated(|p| p.parse_identifier())?,
14208            ))
14209        })
14210    }
14211
14212    /// Parses a parenthesized comma-separated list of index columns, which can be arbitrary
14213    /// expressions with ordering information (and an opclass in some dialects).
14214    fn parse_parenthesized_index_column_list(&mut self) -> Result<Vec<IndexColumn>, ParserError> {
14215        self.parse_parenthesized_column_list_inner(Mandatory, false, |p| {
14216            p.parse_create_index_expr()
14217        })
14218    }
14219
14220    /// Parses a parenthesized comma-separated list of qualified, possibly quoted identifiers.
14221    /// For example: `(db1.sc1.tbl1.col1, db1.sc1.tbl1."col 2", ...)`
14222    pub fn parse_parenthesized_qualified_column_list(
14223        &mut self,
14224        optional: IsOptional,
14225        allow_empty: bool,
14226    ) -> Result<Vec<ObjectName>, ParserError> {
14227        self.parse_parenthesized_column_list_inner(optional, allow_empty, |p| {
14228            p.parse_object_name(true)
14229        })
14230    }
14231
14232    /// Parses a parenthesized comma-separated list of columns using
14233    /// the provided function to parse each element.
14234    fn parse_parenthesized_column_list_inner<F, T>(
14235        &mut self,
14236        optional: IsOptional,
14237        allow_empty: bool,
14238        mut f: F,
14239    ) -> Result<Vec<T>, ParserError>
14240    where
14241        F: FnMut(&mut Parser) -> Result<T, ParserError>,
14242    {
14243        if self.consume_token(&Token::LParen) {
14244            if allow_empty && self.peek_token_ref().token == Token::RParen {
14245                self.next_token();
14246                Ok(vec![])
14247            } else {
14248                let cols = self.parse_comma_separated(|p| f(p))?;
14249                self.expect_token(&Token::RParen)?;
14250                Ok(cols)
14251            }
14252        } else if optional == Optional {
14253            Ok(vec![])
14254        } else {
14255            self.expected_ref("a list of columns in parentheses", self.peek_token_ref())
14256        }
14257    }
14258
14259    /// Parses a parenthesized comma-separated list of table alias column definitions.
14260    fn parse_table_alias_column_defs(&mut self) -> Result<Vec<TableAliasColumnDef>, ParserError> {
14261        if self.consume_token(&Token::LParen) {
14262            let cols = self.parse_comma_separated(|p| {
14263                let name = p.parse_identifier()?;
14264                let data_type = p.maybe_parse(|p| p.parse_data_type())?;
14265                Ok(TableAliasColumnDef { name, data_type })
14266            })?;
14267            self.expect_token(&Token::RParen)?;
14268            Ok(cols)
14269        } else {
14270            Ok(vec![])
14271        }
14272    }
14273
14274    /// Parse an unsigned precision value enclosed in parentheses, e.g. `(10)`.
14275    pub fn parse_precision(&mut self) -> Result<u64, ParserError> {
14276        self.expect_token(&Token::LParen)?;
14277        let n = self.parse_literal_uint()?;
14278        self.expect_token(&Token::RParen)?;
14279        Ok(n)
14280    }
14281
14282    /// Parse an optional precision `(n)` and return it as `Some(n)` when present.
14283    pub fn parse_optional_precision(&mut self) -> Result<Option<u64>, ParserError> {
14284        if self.consume_token(&Token::LParen) {
14285            let n = self.parse_literal_uint()?;
14286            self.expect_token(&Token::RParen)?;
14287            Ok(Some(n))
14288        } else {
14289            Ok(None)
14290        }
14291    }
14292
14293    fn maybe_parse_optional_interval_fields(
14294        &mut self,
14295    ) -> Result<Option<IntervalFields>, ParserError> {
14296        match self.parse_one_of_keywords(&[
14297            // Can be followed by `TO` option
14298            Keyword::YEAR,
14299            Keyword::DAY,
14300            Keyword::HOUR,
14301            Keyword::MINUTE,
14302            // No `TO` option
14303            Keyword::MONTH,
14304            Keyword::SECOND,
14305        ]) {
14306            Some(Keyword::YEAR) => {
14307                if self.peek_keyword(Keyword::TO) {
14308                    self.expect_keyword(Keyword::TO)?;
14309                    self.expect_keyword(Keyword::MONTH)?;
14310                    Ok(Some(IntervalFields::YearToMonth))
14311                } else {
14312                    Ok(Some(IntervalFields::Year))
14313                }
14314            }
14315            Some(Keyword::DAY) => {
14316                if self.peek_keyword(Keyword::TO) {
14317                    self.expect_keyword(Keyword::TO)?;
14318                    match self.expect_one_of_keywords(&[
14319                        Keyword::HOUR,
14320                        Keyword::MINUTE,
14321                        Keyword::SECOND,
14322                    ])? {
14323                        Keyword::HOUR => Ok(Some(IntervalFields::DayToHour)),
14324                        Keyword::MINUTE => Ok(Some(IntervalFields::DayToMinute)),
14325                        Keyword::SECOND => Ok(Some(IntervalFields::DayToSecond)),
14326                        _ => {
14327                            self.prev_token();
14328                            self.expected_ref("HOUR, MINUTE, or SECOND", self.peek_token_ref())
14329                        }
14330                    }
14331                } else {
14332                    Ok(Some(IntervalFields::Day))
14333                }
14334            }
14335            Some(Keyword::HOUR) => {
14336                if self.peek_keyword(Keyword::TO) {
14337                    self.expect_keyword(Keyword::TO)?;
14338                    match self.expect_one_of_keywords(&[Keyword::MINUTE, Keyword::SECOND])? {
14339                        Keyword::MINUTE => Ok(Some(IntervalFields::HourToMinute)),
14340                        Keyword::SECOND => Ok(Some(IntervalFields::HourToSecond)),
14341                        _ => {
14342                            self.prev_token();
14343                            self.expected_ref("MINUTE or SECOND", self.peek_token_ref())
14344                        }
14345                    }
14346                } else {
14347                    Ok(Some(IntervalFields::Hour))
14348                }
14349            }
14350            Some(Keyword::MINUTE) => {
14351                if self.peek_keyword(Keyword::TO) {
14352                    self.expect_keyword(Keyword::TO)?;
14353                    self.expect_keyword(Keyword::SECOND)?;
14354                    Ok(Some(IntervalFields::MinuteToSecond))
14355                } else {
14356                    Ok(Some(IntervalFields::Minute))
14357                }
14358            }
14359            Some(Keyword::MONTH) => Ok(Some(IntervalFields::Month)),
14360            Some(Keyword::SECOND) => Ok(Some(IntervalFields::Second)),
14361            Some(_) => {
14362                self.prev_token();
14363                self.expected_ref(
14364                    "YEAR, MONTH, DAY, HOUR, MINUTE, or SECOND",
14365                    self.peek_token_ref(),
14366                )
14367            }
14368            None => Ok(None),
14369        }
14370    }
14371
14372    /// Parse datetime64 [1]
14373    /// Syntax
14374    /// ```sql
14375    /// DateTime64(precision[, timezone])
14376    /// ```
14377    ///
14378    /// [1]: https://clickhouse.com/docs/en/sql-reference/data-types/datetime64
14379    pub fn parse_datetime_64(&mut self) -> Result<(u64, Option<String>), ParserError> {
14380        self.expect_keyword_is(Keyword::DATETIME64)?;
14381        self.expect_token(&Token::LParen)?;
14382        let precision = self.parse_literal_uint()?;
14383        let time_zone = if self.consume_token(&Token::Comma) {
14384            Some(self.parse_literal_string()?)
14385        } else {
14386            None
14387        };
14388        self.expect_token(&Token::RParen)?;
14389        Ok((precision, time_zone))
14390    }
14391
14392    /// Parse an optional character length specification `(n | MAX [CHARACTERS|OCTETS])`.
14393    pub fn parse_optional_character_length(
14394        &mut self,
14395    ) -> Result<Option<CharacterLength>, ParserError> {
14396        if self.consume_token(&Token::LParen) {
14397            let character_length = self.parse_character_length()?;
14398            self.expect_token(&Token::RParen)?;
14399            Ok(Some(character_length))
14400        } else {
14401            Ok(None)
14402        }
14403    }
14404
14405    /// Parse an optional binary length specification like `(n)`.
14406    pub fn parse_optional_binary_length(&mut self) -> Result<Option<BinaryLength>, ParserError> {
14407        if self.consume_token(&Token::LParen) {
14408            let binary_length = self.parse_binary_length()?;
14409            self.expect_token(&Token::RParen)?;
14410            Ok(Some(binary_length))
14411        } else {
14412            Ok(None)
14413        }
14414    }
14415
14416    /// Parse a character length, handling `MAX` or integer lengths with optional units.
14417    pub fn parse_character_length(&mut self) -> Result<CharacterLength, ParserError> {
14418        if self.parse_keyword(Keyword::MAX) {
14419            return Ok(CharacterLength::Max);
14420        }
14421        let length = self.parse_literal_uint()?;
14422        let unit = if self.parse_keyword(Keyword::CHARACTERS) {
14423            Some(CharLengthUnits::Characters)
14424        } else if self.parse_keyword(Keyword::OCTETS) {
14425            Some(CharLengthUnits::Octets)
14426        } else {
14427            None
14428        };
14429        Ok(CharacterLength::IntegerLength { length, unit })
14430    }
14431
14432    /// Parse a binary length specification, returning `BinaryLength`.
14433    pub fn parse_binary_length(&mut self) -> Result<BinaryLength, ParserError> {
14434        if self.parse_keyword(Keyword::MAX) {
14435            return Ok(BinaryLength::Max);
14436        }
14437        let length = self.parse_literal_uint()?;
14438        Ok(BinaryLength::IntegerLength { length })
14439    }
14440
14441    /// Parse an optional `(precision[, scale])` and return `(Option<precision>, Option<scale>)`.
14442    pub fn parse_optional_precision_scale(
14443        &mut self,
14444    ) -> Result<(Option<u64>, Option<u64>), ParserError> {
14445        if self.consume_token(&Token::LParen) {
14446            let n = self.parse_literal_uint()?;
14447            let scale = if self.consume_token(&Token::Comma) {
14448                Some(self.parse_literal_uint()?)
14449            } else {
14450                None
14451            };
14452            self.expect_token(&Token::RParen)?;
14453            Ok((Some(n), scale))
14454        } else {
14455            Ok((None, None))
14456        }
14457    }
14458
14459    /// Parse exact-number precision/scale info like `(precision[, scale])` for decimal types.
14460    pub fn parse_exact_number_optional_precision_scale(
14461        &mut self,
14462    ) -> Result<ExactNumberInfo, ParserError> {
14463        if self.consume_token(&Token::LParen) {
14464            let precision = self.parse_literal_uint()?;
14465            let scale = if self.consume_token(&Token::Comma) {
14466                Some(self.parse_signed_integer()?)
14467            } else {
14468                None
14469            };
14470
14471            self.expect_token(&Token::RParen)?;
14472
14473            match scale {
14474                None => Ok(ExactNumberInfo::Precision(precision)),
14475                Some(scale) => Ok(ExactNumberInfo::PrecisionAndScale(precision, scale)),
14476            }
14477        } else {
14478            Ok(ExactNumberInfo::None)
14479        }
14480    }
14481
14482    /// Parse an optionally signed integer literal.
14483    fn parse_signed_integer(&mut self) -> Result<i64, ParserError> {
14484        let is_negative = self.consume_token(&Token::Minus);
14485
14486        if !is_negative {
14487            let _ = self.consume_token(&Token::Plus);
14488        }
14489
14490        let current_token = self.peek_token_ref();
14491        match &current_token.token {
14492            Token::Number(s, _) => {
14493                let s = s.clone();
14494                let span_start = current_token.span.start;
14495                self.advance_token();
14496                let value = Self::parse::<i64>(s, span_start)?;
14497                Ok(if is_negative { -value } else { value })
14498            }
14499            _ => self.expected_ref("number", current_token),
14500        }
14501    }
14502
14503    /// Parse optional type modifiers appearing in parentheses e.g. `(UNSIGNED, ZEROFILL)`.
14504    pub fn parse_optional_type_modifiers(&mut self) -> Result<Option<Vec<String>>, ParserError> {
14505        if self.consume_token(&Token::LParen) {
14506            let mut modifiers = Vec::new();
14507            loop {
14508                let next_token = self.next_token();
14509                match next_token.token {
14510                    Token::Word(w) => modifiers.push(w.to_string()),
14511                    Token::Number(n, _) => modifiers.push(n),
14512                    Token::SingleQuotedString(s) => modifiers.push(s),
14513
14514                    Token::Comma => {
14515                        continue;
14516                    }
14517                    Token::RParen => {
14518                        break;
14519                    }
14520                    _ => self.expected("type modifiers", next_token)?,
14521                }
14522            }
14523
14524            Ok(Some(modifiers))
14525        } else {
14526            Ok(None)
14527        }
14528    }
14529
14530    fn parse_structured_object_type_def(&mut self) -> Result<Vec<ColumnDef>, ParserError> {
14531        self.expect_token(&Token::LParen)?;
14532        if self.consume_token(&Token::RParen) {
14533            return Ok(vec![]);
14534        }
14535        let fields = self.parse_comma_separated(|parser| {
14536            if matches!(parser.peek_token_ref().token, Token::SingleQuotedString(_)) {
14537                return parser.expected("an object field identifier", parser.peek_token());
14538            }
14539            let name = parser.parse_identifier()?;
14540            let data_type = parser.parse_data_type()?;
14541            let options = if parser.parse_keywords(&[Keyword::NOT, Keyword::NULL]) {
14542                vec![ColumnOptionDef {
14543                    name: None,
14544                    option: ColumnOption::NotNull,
14545                }]
14546            } else {
14547                vec![]
14548            };
14549            Ok(ColumnDef {
14550                name,
14551                data_type,
14552                options,
14553            })
14554        })?;
14555        self.expect_token(&Token::RParen)?;
14556        Ok(fields)
14557    }
14558
14559    /// Parse a parenthesized sub data type
14560    fn parse_sub_type<F>(&mut self, parent_type: F) -> Result<DataType, ParserError>
14561    where
14562        F: FnOnce(Box<DataType>) -> DataType,
14563    {
14564        self.expect_token(&Token::LParen)?;
14565        let inside_type = self.parse_data_type()?;
14566        self.expect_token(&Token::RParen)?;
14567        Ok(parent_type(inside_type.into()))
14568    }
14569
14570    /// Parse a DELETE statement, returning a `Box`ed SetExpr
14571    ///
14572    /// This is used to reduce the size of the stack frames in debug builds
14573    fn parse_delete_setexpr_boxed(
14574        &mut self,
14575        delete_token: TokenWithSpan,
14576    ) -> Result<Box<SetExpr>, ParserError> {
14577        Ok(Box::new(SetExpr::Delete(self.parse_delete(delete_token)?)))
14578    }
14579
14580    /// Parse a `DELETE` statement and return `Statement::Delete`.
14581    pub fn parse_delete(&mut self, delete_token: TokenWithSpan) -> Result<Statement, ParserError> {
14582        let optimizer_hints = self.maybe_parse_optimizer_hints()?;
14583        let (tables, with_from_keyword) = if !self.parse_keyword(Keyword::FROM) {
14584            // `FROM` keyword is optional in BigQuery SQL.
14585            // https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#delete_statement
14586            if dialect_of!(self is BigQueryDialect | OracleDialect | GenericDialect) {
14587                (vec![], false)
14588            } else {
14589                let tables = self.parse_comma_separated(|p| p.parse_object_name(false))?;
14590                self.expect_keyword_is(Keyword::FROM)?;
14591                (tables, true)
14592            }
14593        } else {
14594            (vec![], true)
14595        };
14596
14597        let from = self.parse_comma_separated(Parser::parse_table_and_joins)?;
14598
14599        let output = self.maybe_parse_output_clause()?;
14600
14601        let using = if self.parse_keyword(Keyword::USING) {
14602            Some(self.parse_comma_separated(Parser::parse_table_and_joins)?)
14603        } else {
14604            None
14605        };
14606        let selection = if self.parse_keyword(Keyword::WHERE) {
14607            Some(self.parse_expr()?)
14608        } else {
14609            None
14610        };
14611        let returning = if self.parse_keyword(Keyword::RETURNING) {
14612            Some(self.parse_comma_separated(Parser::parse_select_item)?)
14613        } else {
14614            None
14615        };
14616        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
14617            self.parse_comma_separated(Parser::parse_order_by_expr)?
14618        } else {
14619            vec![]
14620        };
14621        let limit = if self.parse_keyword(Keyword::LIMIT) {
14622            self.parse_limit()?
14623        } else {
14624            None
14625        };
14626
14627        Ok(Statement::Delete(Delete {
14628            delete_token: delete_token.into(),
14629            optimizer_hints,
14630            tables,
14631            from: if with_from_keyword {
14632                FromTable::WithFromKeyword(from)
14633            } else {
14634                FromTable::WithoutKeyword(from)
14635            },
14636            using,
14637            selection,
14638            returning,
14639            output,
14640            order_by,
14641            limit,
14642        }))
14643    }
14644
14645    /// Parse a `KILL` statement, optionally specifying `CONNECTION`, `QUERY`, or `MUTATION`.
14646    /// KILL [CONNECTION | QUERY | MUTATION] processlist_id
14647    pub fn parse_kill(&mut self) -> Result<Statement, ParserError> {
14648        let modifier_keyword =
14649            self.parse_one_of_keywords(&[Keyword::CONNECTION, Keyword::QUERY, Keyword::MUTATION]);
14650
14651        let id = self.parse_literal_uint()?;
14652
14653        let modifier = match modifier_keyword {
14654            Some(Keyword::CONNECTION) => Some(KillType::Connection),
14655            Some(Keyword::QUERY) => Some(KillType::Query),
14656            Some(Keyword::MUTATION) => {
14657                if dialect_of!(self is ClickHouseDialect | GenericDialect) {
14658                    Some(KillType::Mutation)
14659                } else {
14660                    self.expected_ref(
14661                        "Unsupported type for KILL, allowed: CONNECTION | QUERY",
14662                        self.peek_token_ref(),
14663                    )?
14664                }
14665            }
14666            _ => None,
14667        };
14668
14669        Ok(Statement::Kill { modifier, id })
14670    }
14671
14672    /// Parse an `EXPLAIN` statement, handling dialect-specific options and modifiers.
14673    pub fn parse_explain(
14674        &mut self,
14675        describe_alias: DescribeAlias,
14676    ) -> Result<Statement, ParserError> {
14677        let mut analyze = false;
14678        let mut verbose = false;
14679        let mut query_plan = false;
14680        let mut estimate = false;
14681        let mut format = None;
14682        let mut options = None;
14683
14684        // Note: DuckDB is compatible with PostgreSQL syntax for this statement,
14685        // although not all features may be implemented.
14686        if describe_alias == DescribeAlias::Explain
14687            && self.dialect.supports_explain_with_utility_options()
14688            && self.peek_token_ref().token == Token::LParen
14689        {
14690            options = Some(self.parse_utility_options()?)
14691        } else if self.parse_keywords(&[Keyword::QUERY, Keyword::PLAN]) {
14692            query_plan = true;
14693        } else if self.parse_keyword(Keyword::ESTIMATE) {
14694            estimate = true;
14695        } else {
14696            analyze = self.parse_keyword(Keyword::ANALYZE);
14697            verbose = self.parse_keyword(Keyword::VERBOSE);
14698            if self.parse_keyword(Keyword::FORMAT) {
14699                format = Some(self.parse_analyze_format_kind()?);
14700            }
14701        }
14702
14703        match self.maybe_parse(|parser| parser.parse_statement())? {
14704            Some(Statement::Explain { .. }) | Some(Statement::ExplainTable { .. }) => Err(
14705                ParserError::ParserError("Explain must be root of the plan".to_string()),
14706            ),
14707            Some(statement) => Ok(Statement::Explain {
14708                describe_alias,
14709                analyze,
14710                verbose,
14711                query_plan,
14712                estimate,
14713                statement: Box::new(statement),
14714                format,
14715                options,
14716            }),
14717            _ => {
14718                let hive_format =
14719                    match self.parse_one_of_keywords(&[Keyword::EXTENDED, Keyword::FORMATTED]) {
14720                        Some(Keyword::EXTENDED) => Some(HiveDescribeFormat::Extended),
14721                        Some(Keyword::FORMATTED) => Some(HiveDescribeFormat::Formatted),
14722                        _ => None,
14723                    };
14724
14725                let has_table_keyword = if self.dialect.describe_requires_table_keyword() {
14726                    // only allow to use TABLE keyword for DESC|DESCRIBE statement
14727                    self.parse_keyword(Keyword::TABLE)
14728                } else {
14729                    false
14730                };
14731
14732                let table_name = self.parse_object_name(false)?;
14733                Ok(Statement::ExplainTable {
14734                    describe_alias,
14735                    hive_format,
14736                    has_table_keyword,
14737                    table_name,
14738                })
14739            }
14740        }
14741    }
14742
14743    /// Parse a query expression, i.e. a `SELECT` statement optionally
14744    /// preceded with some `WITH` CTE declarations and optionally followed
14745    /// by `ORDER BY`. Unlike some other parse_... methods, this one doesn't
14746    /// expect the initial keyword to be already consumed
14747    #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
14748    pub fn parse_query(&mut self) -> Result<Box<Query>, ParserError> {
14749        let _guard = self.recursion_counter.try_decrease()?;
14750        let with = if self.parse_keyword(Keyword::WITH) {
14751            let with_token = self.get_current_token();
14752            Some(With {
14753                with_token: with_token.clone().into(),
14754                recursive: self.parse_keyword(Keyword::RECURSIVE),
14755                cte_tables: self.parse_comma_separated(Parser::parse_cte)?,
14756            })
14757        } else {
14758            None
14759        };
14760        if self.parse_keyword(Keyword::INSERT) {
14761            Ok(Query {
14762                with,
14763                body: self.parse_insert_setexpr_boxed(self.get_current_token().clone())?,
14764                order_by: None,
14765                limit_clause: None,
14766                fetch: None,
14767                locks: vec![],
14768                for_clause: None,
14769                settings: None,
14770                format_clause: None,
14771                pipe_operators: vec![],
14772            }
14773            .into())
14774        } else if self.parse_keyword(Keyword::UPDATE) {
14775            Ok(Query {
14776                with,
14777                body: self.parse_update_setexpr_boxed(self.get_current_token().clone())?,
14778                order_by: None,
14779                limit_clause: None,
14780                fetch: None,
14781                locks: vec![],
14782                for_clause: None,
14783                settings: None,
14784                format_clause: None,
14785                pipe_operators: vec![],
14786            }
14787            .into())
14788        } else if self.parse_keyword(Keyword::DELETE) {
14789            Ok(Query {
14790                with,
14791                body: self.parse_delete_setexpr_boxed(self.get_current_token().clone())?,
14792                limit_clause: None,
14793                order_by: None,
14794                fetch: None,
14795                locks: vec![],
14796                for_clause: None,
14797                settings: None,
14798                format_clause: None,
14799                pipe_operators: vec![],
14800            }
14801            .into())
14802        } else if self.parse_keyword(Keyword::MERGE) {
14803            Ok(Query {
14804                with,
14805                body: self.parse_merge_setexpr_boxed(self.get_current_token().clone())?,
14806                limit_clause: None,
14807                order_by: None,
14808                fetch: None,
14809                locks: vec![],
14810                for_clause: None,
14811                settings: None,
14812                format_clause: None,
14813                pipe_operators: vec![],
14814            }
14815            .into())
14816        } else {
14817            let body = self.parse_query_body(self.dialect.prec_unknown())?;
14818
14819            let order_by = self.parse_optional_order_by()?;
14820
14821            let mut limit_clause = self.parse_optional_limit_clause()?;
14822
14823            let settings = self.parse_settings()?;
14824
14825            let fetch = if self.parse_keyword(Keyword::FETCH) {
14826                Some(self.parse_fetch()?)
14827            } else {
14828                None
14829            };
14830
14831            let mut for_clause = None;
14832            let mut locks = Vec::new();
14833            while self.parse_keyword(Keyword::FOR) {
14834                if let Some(parsed_for_clause) = self.parse_for_clause()? {
14835                    for_clause = Some(parsed_for_clause);
14836                    break;
14837                } else {
14838                    locks.push(self.parse_lock()?);
14839                }
14840            }
14841
14842            // Some databases (e.g. PostgreSQL) accept `LIMIT`/`OFFSET` after the
14843            // row-locking clause (`... FOR UPDATE SKIP LOCKED LIMIT 5`) as well
14844            // as before it. The locking clause above is parsed for every
14845            // dialect, so accept a trailing limit here too rather than gating it
14846            // behind a dialect flag.
14847            if limit_clause.is_none() {
14848                limit_clause = self.parse_optional_limit_clause()?;
14849            }
14850
14851            let format_clause =
14852                if self.dialect.supports_select_format() && self.parse_keyword(Keyword::FORMAT) {
14853                    if self.parse_keyword(Keyword::NULL) {
14854                        Some(FormatClause::Null)
14855                    } else {
14856                        let ident = self.parse_identifier()?;
14857                        Some(FormatClause::Identifier(ident))
14858                    }
14859                } else {
14860                    None
14861                };
14862
14863            let pipe_operators = if self.dialect.supports_pipe_operator() {
14864                self.parse_pipe_operators()?
14865            } else {
14866                Vec::new()
14867            };
14868
14869            Ok(Query {
14870                with,
14871                body,
14872                order_by,
14873                limit_clause,
14874                fetch,
14875                locks,
14876                for_clause,
14877                settings,
14878                format_clause,
14879                pipe_operators,
14880            }
14881            .into())
14882        }
14883    }
14884
14885    fn parse_pipe_operators(&mut self) -> Result<Vec<PipeOperator>, ParserError> {
14886        let mut pipe_operators = Vec::new();
14887
14888        while self.consume_token(&Token::VerticalBarRightAngleBracket) {
14889            let kw = self.expect_one_of_keywords(&[
14890                Keyword::SELECT,
14891                Keyword::EXTEND,
14892                Keyword::SET,
14893                Keyword::DROP,
14894                Keyword::AS,
14895                Keyword::WHERE,
14896                Keyword::LIMIT,
14897                Keyword::AGGREGATE,
14898                Keyword::ORDER,
14899                Keyword::TABLESAMPLE,
14900                Keyword::RENAME,
14901                Keyword::UNION,
14902                Keyword::INTERSECT,
14903                Keyword::EXCEPT,
14904                Keyword::CALL,
14905                Keyword::PIVOT,
14906                Keyword::UNPIVOT,
14907                Keyword::JOIN,
14908                Keyword::INNER,
14909                Keyword::LEFT,
14910                Keyword::RIGHT,
14911                Keyword::FULL,
14912                Keyword::CROSS,
14913            ])?;
14914            match kw {
14915                Keyword::SELECT => {
14916                    let exprs = self.parse_comma_separated(Parser::parse_select_item)?;
14917                    pipe_operators.push(PipeOperator::Select { exprs })
14918                }
14919                Keyword::EXTEND => {
14920                    let exprs = self.parse_comma_separated(Parser::parse_select_item)?;
14921                    pipe_operators.push(PipeOperator::Extend { exprs })
14922                }
14923                Keyword::SET => {
14924                    let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
14925                    pipe_operators.push(PipeOperator::Set { assignments })
14926                }
14927                Keyword::DROP => {
14928                    let columns = self.parse_identifiers()?;
14929                    pipe_operators.push(PipeOperator::Drop { columns })
14930                }
14931                Keyword::AS => {
14932                    let alias = self.parse_identifier()?;
14933                    pipe_operators.push(PipeOperator::As { alias })
14934                }
14935                Keyword::WHERE => {
14936                    let expr = self.parse_expr()?;
14937                    pipe_operators.push(PipeOperator::Where { expr })
14938                }
14939                Keyword::LIMIT => {
14940                    let expr = self.parse_expr()?;
14941                    let offset = if self.parse_keyword(Keyword::OFFSET) {
14942                        Some(self.parse_expr()?)
14943                    } else {
14944                        None
14945                    };
14946                    pipe_operators.push(PipeOperator::Limit { expr, offset })
14947                }
14948                Keyword::AGGREGATE => {
14949                    let full_table_exprs = if self.peek_keyword(Keyword::GROUP) {
14950                        vec![]
14951                    } else {
14952                        self.parse_comma_separated(|parser| {
14953                            parser.parse_expr_with_alias_and_order_by()
14954                        })?
14955                    };
14956
14957                    let group_by_expr = if self.parse_keywords(&[Keyword::GROUP, Keyword::BY]) {
14958                        self.parse_comma_separated(|parser| {
14959                            parser.parse_expr_with_alias_and_order_by()
14960                        })?
14961                    } else {
14962                        vec![]
14963                    };
14964
14965                    pipe_operators.push(PipeOperator::Aggregate {
14966                        full_table_exprs,
14967                        group_by_expr,
14968                    })
14969                }
14970                Keyword::ORDER => {
14971                    self.expect_one_of_keywords(&[Keyword::BY])?;
14972                    let exprs = self.parse_comma_separated(Parser::parse_order_by_expr)?;
14973                    pipe_operators.push(PipeOperator::OrderBy { exprs })
14974                }
14975                Keyword::TABLESAMPLE => {
14976                    let sample = self.parse_table_sample(TableSampleModifier::TableSample)?;
14977                    pipe_operators.push(PipeOperator::TableSample { sample });
14978                }
14979                Keyword::RENAME => {
14980                    let mappings =
14981                        self.parse_comma_separated(Parser::parse_identifier_with_optional_alias)?;
14982                    pipe_operators.push(PipeOperator::Rename { mappings });
14983                }
14984                Keyword::UNION => {
14985                    let set_quantifier = self.parse_set_quantifier(&Some(SetOperator::Union));
14986                    let queries = self.parse_pipe_operator_queries()?;
14987                    pipe_operators.push(PipeOperator::Union {
14988                        set_quantifier,
14989                        queries,
14990                    });
14991                }
14992                Keyword::INTERSECT => {
14993                    let set_quantifier =
14994                        self.parse_distinct_required_set_quantifier("INTERSECT")?;
14995                    let queries = self.parse_pipe_operator_queries()?;
14996                    pipe_operators.push(PipeOperator::Intersect {
14997                        set_quantifier,
14998                        queries,
14999                    });
15000                }
15001                Keyword::EXCEPT => {
15002                    let set_quantifier = self.parse_distinct_required_set_quantifier("EXCEPT")?;
15003                    let queries = self.parse_pipe_operator_queries()?;
15004                    pipe_operators.push(PipeOperator::Except {
15005                        set_quantifier,
15006                        queries,
15007                    });
15008                }
15009                Keyword::CALL => {
15010                    let function_name = self.parse_object_name(false)?;
15011                    let function_expr = self.parse_function(function_name)?;
15012                    if let Expr::Function(function) = function_expr {
15013                        let alias = self.parse_identifier_optional_alias()?;
15014                        pipe_operators.push(PipeOperator::Call { function, alias });
15015                    } else {
15016                        return Err(ParserError::ParserError(
15017                            "Expected function call after CALL".to_string(),
15018                        ));
15019                    }
15020                }
15021                Keyword::PIVOT => {
15022                    self.expect_token(&Token::LParen)?;
15023                    let aggregate_functions =
15024                        self.parse_comma_separated(Self::parse_pivot_aggregate_function)?;
15025                    self.expect_keyword_is(Keyword::FOR)?;
15026                    let value_column = self.parse_period_separated(|p| p.parse_identifier())?;
15027                    self.expect_keyword_is(Keyword::IN)?;
15028
15029                    self.expect_token(&Token::LParen)?;
15030                    let value_source = if self.parse_keyword(Keyword::ANY) {
15031                        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
15032                            self.parse_comma_separated(Parser::parse_order_by_expr)?
15033                        } else {
15034                            vec![]
15035                        };
15036                        PivotValueSource::Any(order_by)
15037                    } else if self.peek_sub_query() {
15038                        PivotValueSource::Subquery(self.parse_query()?)
15039                    } else {
15040                        PivotValueSource::List(
15041                            self.parse_comma_separated(Self::parse_expr_with_alias)?,
15042                        )
15043                    };
15044                    self.expect_token(&Token::RParen)?;
15045                    self.expect_token(&Token::RParen)?;
15046
15047                    let alias = self.parse_identifier_optional_alias()?;
15048
15049                    pipe_operators.push(PipeOperator::Pivot {
15050                        aggregate_functions,
15051                        value_column,
15052                        value_source,
15053                        alias,
15054                    });
15055                }
15056                Keyword::UNPIVOT => {
15057                    self.expect_token(&Token::LParen)?;
15058                    let value_column = self.parse_identifier()?;
15059                    self.expect_keyword(Keyword::FOR)?;
15060                    let name_column = self.parse_identifier()?;
15061                    self.expect_keyword(Keyword::IN)?;
15062
15063                    self.expect_token(&Token::LParen)?;
15064                    let unpivot_columns = self.parse_comma_separated(Parser::parse_identifier)?;
15065                    self.expect_token(&Token::RParen)?;
15066
15067                    self.expect_token(&Token::RParen)?;
15068
15069                    let alias = self.parse_identifier_optional_alias()?;
15070
15071                    pipe_operators.push(PipeOperator::Unpivot {
15072                        value_column,
15073                        name_column,
15074                        unpivot_columns,
15075                        alias,
15076                    });
15077                }
15078                Keyword::JOIN
15079                | Keyword::INNER
15080                | Keyword::LEFT
15081                | Keyword::RIGHT
15082                | Keyword::FULL
15083                | Keyword::CROSS => {
15084                    self.prev_token();
15085                    let mut joins = self.parse_joins()?;
15086                    if joins.len() != 1 {
15087                        return Err(ParserError::ParserError(
15088                            "Join pipe operator must have a single join".to_string(),
15089                        ));
15090                    }
15091                    let join = joins.swap_remove(0);
15092                    pipe_operators.push(PipeOperator::Join(join))
15093                }
15094                unhandled => {
15095                    return Err(ParserError::ParserError(format!(
15096                    "`expect_one_of_keywords` further up allowed unhandled keyword: {unhandled:?}"
15097                )))
15098                }
15099            }
15100        }
15101        Ok(pipe_operators)
15102    }
15103
15104    fn parse_settings(&mut self) -> Result<Option<Vec<Setting>>, ParserError> {
15105        let settings = if self.dialect.supports_settings() && self.parse_keyword(Keyword::SETTINGS)
15106        {
15107            let key_values = self.parse_comma_separated(|p| {
15108                let key = p.parse_identifier()?;
15109                p.expect_token(&Token::Eq)?;
15110                let value = p.parse_expr()?;
15111                Ok(Setting { key, value })
15112            })?;
15113            Some(key_values)
15114        } else {
15115            None
15116        };
15117        Ok(settings)
15118    }
15119
15120    /// Parse a mssql `FOR [XML | JSON | BROWSE]` clause
15121    pub fn parse_for_clause(&mut self) -> Result<Option<ForClause>, ParserError> {
15122        if self.parse_keyword(Keyword::XML) {
15123            Ok(Some(self.parse_for_xml()?))
15124        } else if self.parse_keyword(Keyword::JSON) {
15125            Ok(Some(self.parse_for_json()?))
15126        } else if self.parse_keyword(Keyword::BROWSE) {
15127            Ok(Some(ForClause::Browse))
15128        } else {
15129            Ok(None)
15130        }
15131    }
15132
15133    /// Parse a mssql `FOR XML` clause
15134    pub fn parse_for_xml(&mut self) -> Result<ForClause, ParserError> {
15135        let for_xml = if self.parse_keyword(Keyword::RAW) {
15136            let mut element_name = None;
15137            if self.peek_token_ref().token == Token::LParen {
15138                self.expect_token(&Token::LParen)?;
15139                element_name = Some(self.parse_literal_string()?);
15140                self.expect_token(&Token::RParen)?;
15141            }
15142            ForXml::Raw(element_name)
15143        } else if self.parse_keyword(Keyword::AUTO) {
15144            ForXml::Auto
15145        } else if self.parse_keyword(Keyword::EXPLICIT) {
15146            ForXml::Explicit
15147        } else if self.parse_keyword(Keyword::PATH) {
15148            let mut element_name = None;
15149            if self.peek_token_ref().token == Token::LParen {
15150                self.expect_token(&Token::LParen)?;
15151                element_name = Some(self.parse_literal_string()?);
15152                self.expect_token(&Token::RParen)?;
15153            }
15154            ForXml::Path(element_name)
15155        } else {
15156            return Err(ParserError::ParserError(
15157                "Expected FOR XML [RAW | AUTO | EXPLICIT | PATH ]".to_string(),
15158            ));
15159        };
15160        let mut elements = false;
15161        let mut binary_base64 = false;
15162        let mut root = None;
15163        let mut r#type = false;
15164        while self.peek_token_ref().token == Token::Comma {
15165            self.next_token();
15166            if self.parse_keyword(Keyword::ELEMENTS) {
15167                elements = true;
15168            } else if self.parse_keyword(Keyword::BINARY) {
15169                self.expect_keyword_is(Keyword::BASE64)?;
15170                binary_base64 = true;
15171            } else if self.parse_keyword(Keyword::ROOT) {
15172                self.expect_token(&Token::LParen)?;
15173                root = Some(self.parse_literal_string()?);
15174                self.expect_token(&Token::RParen)?;
15175            } else if self.parse_keyword(Keyword::TYPE) {
15176                r#type = true;
15177            }
15178        }
15179        Ok(ForClause::Xml {
15180            for_xml,
15181            elements,
15182            binary_base64,
15183            root,
15184            r#type,
15185        })
15186    }
15187
15188    /// Parse a mssql `FOR JSON` clause
15189    pub fn parse_for_json(&mut self) -> Result<ForClause, ParserError> {
15190        let for_json = if self.parse_keyword(Keyword::AUTO) {
15191            ForJson::Auto
15192        } else if self.parse_keyword(Keyword::PATH) {
15193            ForJson::Path
15194        } else {
15195            return Err(ParserError::ParserError(
15196                "Expected FOR JSON [AUTO | PATH ]".to_string(),
15197            ));
15198        };
15199        let mut root = None;
15200        let mut include_null_values = false;
15201        let mut without_array_wrapper = false;
15202        while self.peek_token_ref().token == Token::Comma {
15203            self.next_token();
15204            if self.parse_keyword(Keyword::ROOT) {
15205                self.expect_token(&Token::LParen)?;
15206                root = Some(self.parse_literal_string()?);
15207                self.expect_token(&Token::RParen)?;
15208            } else if self.parse_keyword(Keyword::INCLUDE_NULL_VALUES) {
15209                include_null_values = true;
15210            } else if self.parse_keyword(Keyword::WITHOUT_ARRAY_WRAPPER) {
15211                without_array_wrapper = true;
15212            }
15213        }
15214        Ok(ForClause::Json {
15215            for_json,
15216            root,
15217            include_null_values,
15218            without_array_wrapper,
15219        })
15220    }
15221
15222    /// Parse a CTE (`alias [( col1, col2, ... )] [AS] (subquery)`)
15223    pub fn parse_cte(&mut self) -> Result<Cte, ParserError> {
15224        let name = self.parse_identifier()?;
15225
15226        let as_optional = self.dialect.supports_cte_without_as();
15227
15228        // If AS is optional, first try to parse `name (query)` directly
15229        if as_optional && !self.peek_keyword(Keyword::AS) {
15230            if let Some((query, closing_paren_token)) = self.maybe_parse(|p| {
15231                p.expect_token(&Token::LParen)?;
15232                let query = p.parse_query()?;
15233                let closing_paren_token = p.expect_token(&Token::RParen)?;
15234                Ok((query, closing_paren_token))
15235            })? {
15236                let mut cte = Cte {
15237                    alias: TableAlias {
15238                        explicit: false,
15239                        name,
15240                        columns: vec![],
15241                        at: None,
15242                    },
15243                    query,
15244                    from: None,
15245                    materialized: None,
15246                    closing_paren_token: closing_paren_token.into(),
15247                };
15248                if self.parse_keyword(Keyword::FROM) {
15249                    cte.from = Some(self.parse_identifier()?);
15250                }
15251                return Ok(cte);
15252            }
15253        }
15254
15255        // Determine column definitions and consume AS
15256        let columns = if self.parse_keyword(Keyword::AS) {
15257            vec![]
15258        } else {
15259            let columns = self.parse_table_alias_column_defs()?;
15260            if as_optional {
15261                let _ = self.parse_keyword(Keyword::AS);
15262            } else {
15263                self.expect_keyword_is(Keyword::AS)?;
15264            }
15265            columns
15266        };
15267
15268        let mut is_materialized = None;
15269        if dialect_of!(self is PostgreSqlDialect) {
15270            if self.parse_keyword(Keyword::MATERIALIZED) {
15271                is_materialized = Some(CteAsMaterialized::Materialized);
15272            } else if self.parse_keywords(&[Keyword::NOT, Keyword::MATERIALIZED]) {
15273                is_materialized = Some(CteAsMaterialized::NotMaterialized);
15274            }
15275        }
15276
15277        self.expect_token(&Token::LParen)?;
15278        let query = self.parse_query()?;
15279        let closing_paren_token = self.expect_token(&Token::RParen)?;
15280
15281        let mut cte = Cte {
15282            alias: TableAlias {
15283                explicit: false,
15284                name,
15285                columns,
15286                at: None,
15287            },
15288            query,
15289            from: None,
15290            materialized: is_materialized,
15291            closing_paren_token: closing_paren_token.into(),
15292        };
15293        if self.dialect.supports_from_first_insert() && self.parse_keyword(Keyword::FROM) {
15294            cte.from = Some(self.parse_identifier()?);
15295        }
15296        Ok(cte)
15297    }
15298
15299    /// Parse a "query body", which is an expression with roughly the
15300    /// following grammar:
15301    /// ```sql
15302    ///   query_body ::= restricted_select | '(' subquery ')' | set_operation
15303    ///   restricted_select ::= 'SELECT' [expr_list] [ from ] [ where ] [ groupby_having ]
15304    ///   subquery ::= query_body [ order_by_limit ]
15305    ///   set_operation ::= query_body { 'UNION' | 'EXCEPT' | 'INTERSECT' } [ 'ALL' ] query_body
15306    /// ```
15307    pub fn parse_query_body(&mut self, precedence: u8) -> Result<Box<SetExpr>, ParserError> {
15308        // We parse the expression using a Pratt parser, as in `parse_expr()`.
15309        // Start by parsing a restricted SELECT or a `(subquery)`:
15310        let expr = if self.peek_keyword(Keyword::SELECT)
15311            || (self.peek_keyword(Keyword::FROM) && self.dialect.supports_from_first_select())
15312        {
15313            SetExpr::Select(self.parse_select().map(Box::new)?)
15314        } else if self.consume_token(&Token::LParen) {
15315            // CTEs are not allowed here, but the parser currently accepts them
15316            let subquery = self.parse_query()?;
15317            self.expect_token(&Token::RParen)?;
15318            SetExpr::Query(subquery)
15319        } else if self.parse_keyword(Keyword::VALUES) {
15320            let is_mysql = dialect_of!(self is MySqlDialect);
15321            SetExpr::Values(self.parse_values(is_mysql, false)?)
15322        } else if self.parse_keyword(Keyword::VALUE) {
15323            let is_mysql = dialect_of!(self is MySqlDialect);
15324            SetExpr::Values(self.parse_values(is_mysql, true)?)
15325        } else if self.parse_keyword(Keyword::TABLE) {
15326            SetExpr::Table(Box::new(self.parse_as_table()?))
15327        } else {
15328            return self.expected_ref(
15329                "SELECT, VALUES, or a subquery in the query body",
15330                self.peek_token_ref(),
15331            );
15332        };
15333
15334        self.parse_remaining_set_exprs(expr, precedence)
15335    }
15336
15337    /// Parse any extra set expressions that may be present in a query body
15338    ///
15339    /// (this is its own function to reduce required stack size in debug builds)
15340    fn parse_remaining_set_exprs(
15341        &mut self,
15342        mut expr: SetExpr,
15343        precedence: u8,
15344    ) -> Result<Box<SetExpr>, ParserError> {
15345        loop {
15346            // The query can be optionally followed by a set operator:
15347            let op = self.parse_set_operator(&self.peek_token().token);
15348            let next_precedence = match op {
15349                // UNION and EXCEPT have the same binding power and evaluate left-to-right
15350                Some(SetOperator::Union) | Some(SetOperator::Except) | Some(SetOperator::Minus) => {
15351                    10
15352                }
15353                // INTERSECT has higher precedence than UNION/EXCEPT
15354                Some(SetOperator::Intersect) => 20,
15355                // Unexpected token or EOF => stop parsing the query body
15356                None => break,
15357            };
15358            if precedence >= next_precedence {
15359                break;
15360            }
15361            self.next_token(); // skip past the set operator
15362            let set_quantifier = self.parse_set_quantifier(&op);
15363            expr = SetExpr::SetOperation {
15364                left: Box::new(expr),
15365                op: op.unwrap(),
15366                set_quantifier,
15367                right: self.parse_query_body(next_precedence)?,
15368            };
15369        }
15370
15371        Ok(expr.into())
15372    }
15373
15374    /// Parse a set operator token into its `SetOperator` variant.
15375    pub fn parse_set_operator(&mut self, token: &Token) -> Option<SetOperator> {
15376        match token {
15377            Token::Word(w) if w.keyword == Keyword::UNION => Some(SetOperator::Union),
15378            Token::Word(w) if w.keyword == Keyword::EXCEPT => Some(SetOperator::Except),
15379            Token::Word(w) if w.keyword == Keyword::INTERSECT => Some(SetOperator::Intersect),
15380            Token::Word(w) if w.keyword == Keyword::MINUS => Some(SetOperator::Minus),
15381            _ => None,
15382        }
15383    }
15384
15385    /// Parse a set quantifier (e.g., `ALL`, `DISTINCT BY NAME`) for the given set operator.
15386    pub fn parse_set_quantifier(&mut self, op: &Option<SetOperator>) -> SetQuantifier {
15387        match op {
15388            Some(
15389                SetOperator::Except
15390                | SetOperator::Intersect
15391                | SetOperator::Union
15392                | SetOperator::Minus,
15393            ) => {
15394                if self.parse_keywords(&[Keyword::DISTINCT, Keyword::BY, Keyword::NAME]) {
15395                    SetQuantifier::DistinctByName
15396                } else if self.parse_keywords(&[Keyword::BY, Keyword::NAME]) {
15397                    SetQuantifier::ByName
15398                } else if self.parse_keyword(Keyword::ALL) {
15399                    if self.parse_keywords(&[Keyword::BY, Keyword::NAME]) {
15400                        SetQuantifier::AllByName
15401                    } else {
15402                        SetQuantifier::All
15403                    }
15404                } else if self.parse_keyword(Keyword::DISTINCT) {
15405                    SetQuantifier::Distinct
15406                } else {
15407                    SetQuantifier::None
15408                }
15409            }
15410            _ => SetQuantifier::None,
15411        }
15412    }
15413
15414    /// Parse a restricted `SELECT` statement (no CTEs / `UNION` / `ORDER BY`)
15415    pub fn parse_select(&mut self) -> Result<Select, ParserError> {
15416        let mut from_first = None;
15417
15418        if self.dialect.supports_from_first_select() && self.peek_keyword(Keyword::FROM) {
15419            let from_token = self.expect_keyword(Keyword::FROM)?;
15420            let from = self.parse_table_with_joins()?;
15421            if !self.peek_keyword(Keyword::SELECT) {
15422                return Ok(Select {
15423                    select_token: AttachedToken(from_token),
15424                    optimizer_hints: vec![],
15425                    distinct: None,
15426                    select_modifiers: None,
15427                    top: None,
15428                    top_before_distinct: false,
15429                    projection: vec![],
15430                    exclude: None,
15431                    into: None,
15432                    from,
15433                    lateral_views: vec![],
15434                    prewhere: None,
15435                    selection: None,
15436                    group_by: GroupByExpr::Expressions(vec![], vec![]),
15437                    cluster_by: vec![],
15438                    distribute_by: vec![],
15439                    sort_by: vec![],
15440                    having: None,
15441                    named_window: vec![],
15442                    window_before_qualify: false,
15443                    qualify: None,
15444                    value_table_mode: None,
15445                    connect_by: vec![],
15446                    flavor: SelectFlavor::FromFirstNoSelect,
15447                });
15448            }
15449            from_first = Some(from);
15450        }
15451
15452        let select_token = self.expect_keyword(Keyword::SELECT)?;
15453        let optimizer_hints = self.maybe_parse_optimizer_hints()?;
15454        let value_table_mode = self.parse_value_table_mode()?;
15455
15456        let (select_modifiers, distinct_select_modifier) =
15457            if self.dialect.supports_select_modifiers() {
15458                self.parse_select_modifiers()?
15459            } else {
15460                (None, None)
15461            };
15462
15463        let mut top_before_distinct = false;
15464        let mut top = None;
15465        if self.dialect.supports_top_before_distinct() && self.parse_keyword(Keyword::TOP) {
15466            top = Some(self.parse_top()?);
15467            top_before_distinct = true;
15468        }
15469
15470        let distinct = if distinct_select_modifier.is_some() {
15471            distinct_select_modifier
15472        } else {
15473            self.parse_all_or_distinct()?
15474        };
15475
15476        if !self.dialect.supports_top_before_distinct() && self.parse_keyword(Keyword::TOP) {
15477            top = Some(self.parse_top()?);
15478        }
15479
15480        let projection =
15481            if self.dialect.supports_empty_projections() && self.peek_keyword(Keyword::FROM) {
15482                vec![]
15483            } else {
15484                self.parse_projection()?
15485            };
15486
15487        let exclude = if self.dialect.supports_select_exclude() {
15488            self.parse_optional_select_item_exclude()?
15489        } else {
15490            None
15491        };
15492
15493        let into = if self.parse_keyword(Keyword::INTO) {
15494            Some(self.parse_select_into()?)
15495        } else {
15496            None
15497        };
15498
15499        // Note that for keywords to be properly handled here, they need to be
15500        // added to `RESERVED_FOR_COLUMN_ALIAS` / `RESERVED_FOR_TABLE_ALIAS`,
15501        // otherwise they may be parsed as an alias as part of the `projection`
15502        // or `from`.
15503
15504        let (from, from_first) = if let Some(from) = from_first.take() {
15505            (from, true)
15506        } else if self.parse_keyword(Keyword::FROM) {
15507            (self.parse_table_with_joins()?, false)
15508        } else {
15509            (vec![], false)
15510        };
15511
15512        let mut lateral_views = vec![];
15513        loop {
15514            if self.parse_keywords(&[Keyword::LATERAL, Keyword::VIEW]) {
15515                let outer = self.parse_keyword(Keyword::OUTER);
15516                let lateral_view = self.parse_expr()?;
15517                let lateral_view_name = self.parse_object_name(false)?;
15518                let lateral_col_alias = self
15519                    .parse_comma_separated(|parser| {
15520                        parser.parse_optional_alias(&[
15521                            Keyword::WHERE,
15522                            Keyword::GROUP,
15523                            Keyword::CLUSTER,
15524                            Keyword::HAVING,
15525                            Keyword::LATERAL,
15526                        ]) // This couldn't possibly be a bad idea
15527                    })?
15528                    .into_iter()
15529                    .flatten()
15530                    .collect();
15531
15532                lateral_views.push(LateralView {
15533                    lateral_view,
15534                    lateral_view_name,
15535                    lateral_col_alias,
15536                    outer,
15537                });
15538            } else {
15539                break;
15540            }
15541        }
15542
15543        let prewhere = if self.dialect.supports_prewhere() && self.parse_keyword(Keyword::PREWHERE)
15544        {
15545            Some(self.parse_expr()?)
15546        } else {
15547            None
15548        };
15549
15550        let selection = if self.parse_keyword(Keyword::WHERE) {
15551            Some(self.parse_expr()?)
15552        } else {
15553            None
15554        };
15555
15556        let connect_by = self.maybe_parse_connect_by()?;
15557
15558        let group_by = self
15559            .parse_optional_group_by()?
15560            .unwrap_or_else(|| GroupByExpr::Expressions(vec![], vec![]));
15561
15562        let cluster_by = if self.parse_keywords(&[Keyword::CLUSTER, Keyword::BY]) {
15563            self.parse_comma_separated(Parser::parse_expr)?
15564        } else {
15565            vec![]
15566        };
15567
15568        let distribute_by = if self.parse_keywords(&[Keyword::DISTRIBUTE, Keyword::BY]) {
15569            self.parse_comma_separated(Parser::parse_expr)?
15570        } else {
15571            vec![]
15572        };
15573
15574        let sort_by = if self.parse_keywords(&[Keyword::SORT, Keyword::BY]) {
15575            self.parse_comma_separated(Parser::parse_order_by_expr)?
15576        } else {
15577            vec![]
15578        };
15579
15580        let having = if self.parse_keyword(Keyword::HAVING) {
15581            Some(self.parse_expr()?)
15582        } else {
15583            None
15584        };
15585
15586        // Accept QUALIFY and WINDOW in any order and flag accordingly.
15587        let (named_windows, qualify, window_before_qualify) = if self.parse_keyword(Keyword::WINDOW)
15588        {
15589            let named_windows = self.parse_comma_separated(Parser::parse_named_window)?;
15590            if self.parse_keyword(Keyword::QUALIFY) {
15591                (named_windows, Some(self.parse_expr()?), true)
15592            } else {
15593                (named_windows, None, true)
15594            }
15595        } else if self.parse_keyword(Keyword::QUALIFY) {
15596            let qualify = Some(self.parse_expr()?);
15597            if self.parse_keyword(Keyword::WINDOW) {
15598                (
15599                    self.parse_comma_separated(Parser::parse_named_window)?,
15600                    qualify,
15601                    false,
15602                )
15603            } else {
15604                (Default::default(), qualify, false)
15605            }
15606        } else {
15607            Default::default()
15608        };
15609
15610        Ok(Select {
15611            select_token: AttachedToken(select_token),
15612            optimizer_hints,
15613            distinct,
15614            select_modifiers,
15615            top,
15616            top_before_distinct,
15617            projection,
15618            exclude,
15619            into,
15620            from,
15621            lateral_views,
15622            prewhere,
15623            selection,
15624            group_by,
15625            cluster_by,
15626            distribute_by,
15627            sort_by,
15628            having,
15629            named_window: named_windows,
15630            window_before_qualify,
15631            qualify,
15632            value_table_mode,
15633            connect_by,
15634            flavor: if from_first {
15635                SelectFlavor::FromFirst
15636            } else {
15637                SelectFlavor::Standard
15638            },
15639        })
15640    }
15641
15642    /// Parses optimizer hints at the current token position.
15643    ///
15644    /// Collects all `/*prefix+...*/` and `--prefix+...` patterns.
15645    /// The `prefix` is any run of ASCII alphanumeric characters between the
15646    /// comment marker and `+` (e.g. `""` for `/*+...*/`, `"abc"` for `/*abc+...*/`).
15647    ///
15648    /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/optimizer-hints.html#optimizer-hints-overview)
15649    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Comments.html#GUID-D316D545-89E2-4D54-977F-FC97815CD62E)
15650    fn maybe_parse_optimizer_hints(&mut self) -> Result<Vec<OptimizerHint>, ParserError> {
15651        let supports_hints = self.dialect.supports_comment_optimizer_hint();
15652        if !supports_hints {
15653            return Ok(vec![]);
15654        }
15655        let mut hints = vec![];
15656        loop {
15657            let t = self.peek_nth_token_no_skip_ref(0);
15658            let Token::Whitespace(ws) = &t.token else {
15659                break;
15660            };
15661            match ws {
15662                Whitespace::SingleLineComment { comment, prefix } => {
15663                    if let Some((hint_prefix, text)) = Self::extract_hint_prefix_and_text(comment) {
15664                        hints.push(OptimizerHint {
15665                            prefix: hint_prefix,
15666                            text,
15667                            style: OptimizerHintStyle::SingleLine {
15668                                prefix: prefix.clone(),
15669                            },
15670                        });
15671                    }
15672                    self.next_token_no_skip();
15673                }
15674                Whitespace::MultiLineComment(comment) => {
15675                    if let Some((hint_prefix, text)) = Self::extract_hint_prefix_and_text(comment) {
15676                        hints.push(OptimizerHint {
15677                            prefix: hint_prefix,
15678                            text,
15679                            style: OptimizerHintStyle::MultiLine,
15680                        });
15681                    }
15682                    self.next_token_no_skip();
15683                }
15684                Whitespace::Space | Whitespace::Tab | Whitespace::Newline => {
15685                    self.next_token_no_skip();
15686                }
15687            }
15688        }
15689        Ok(hints)
15690    }
15691
15692    /// Checks if a comment's content starts with `[ASCII-alphanumeric]*+`
15693    /// and returns `(prefix, text_after_plus)` if so.
15694    fn extract_hint_prefix_and_text(comment: &str) -> Option<(String, String)> {
15695        let (before_plus, text) = comment.split_once('+')?;
15696        if before_plus.chars().all(|c| c.is_ascii_alphanumeric()) {
15697            Some((before_plus.to_string(), text.to_string()))
15698        } else {
15699            None
15700        }
15701    }
15702
15703    /// Parses MySQL SELECT modifiers and DISTINCT/ALL in any order.
15704    ///
15705    /// Manual testing shows odifiers can appear in any order, and modifiers other than DISTINCT/ALL
15706    /// can be repeated.
15707    ///
15708    /// <https://dev.mysql.com/doc/refman/8.4/en/select.html>
15709    fn parse_select_modifiers(
15710        &mut self,
15711    ) -> Result<(Option<SelectModifiers>, Option<Distinct>), ParserError> {
15712        let mut modifiers = SelectModifiers::default();
15713        let mut distinct = None;
15714
15715        let keywords = &[
15716            Keyword::ALL,
15717            Keyword::DISTINCT,
15718            Keyword::DISTINCTROW,
15719            Keyword::HIGH_PRIORITY,
15720            Keyword::STRAIGHT_JOIN,
15721            Keyword::SQL_SMALL_RESULT,
15722            Keyword::SQL_BIG_RESULT,
15723            Keyword::SQL_BUFFER_RESULT,
15724            Keyword::SQL_NO_CACHE,
15725            Keyword::SQL_CALC_FOUND_ROWS,
15726        ];
15727
15728        while let Some(keyword) = self.parse_one_of_keywords(keywords) {
15729            match keyword {
15730                Keyword::ALL | Keyword::DISTINCT if distinct.is_none() => {
15731                    self.prev_token();
15732                    distinct = self.parse_all_or_distinct()?;
15733                }
15734                // DISTINCTROW is a MySQL-specific legacy (but not deprecated) alias for DISTINCT
15735                Keyword::DISTINCTROW if distinct.is_none() => {
15736                    distinct = Some(Distinct::Distinct);
15737                }
15738                Keyword::HIGH_PRIORITY => modifiers.high_priority = true,
15739                Keyword::STRAIGHT_JOIN => modifiers.straight_join = true,
15740                Keyword::SQL_SMALL_RESULT => modifiers.sql_small_result = true,
15741                Keyword::SQL_BIG_RESULT => modifiers.sql_big_result = true,
15742                Keyword::SQL_BUFFER_RESULT => modifiers.sql_buffer_result = true,
15743                Keyword::SQL_NO_CACHE => modifiers.sql_no_cache = true,
15744                Keyword::SQL_CALC_FOUND_ROWS => modifiers.sql_calc_found_rows = true,
15745                _ => {
15746                    self.prev_token();
15747                    return self.expected_ref(
15748                        "HIGH_PRIORITY, STRAIGHT_JOIN, or other MySQL select modifier",
15749                        self.peek_token_ref(),
15750                    );
15751                }
15752            }
15753        }
15754
15755        // Avoid polluting the AST with `Some(SelectModifiers::default())` empty value unless there
15756        // actually were some modifiers set.
15757        let select_modifiers = if modifiers.is_any_set() {
15758            Some(modifiers)
15759        } else {
15760            None
15761        };
15762        Ok((select_modifiers, distinct))
15763    }
15764
15765    fn parse_value_table_mode(&mut self) -> Result<Option<ValueTableMode>, ParserError> {
15766        if !dialect_of!(self is BigQueryDialect) {
15767            return Ok(None);
15768        }
15769
15770        let mode = if self.parse_keywords(&[Keyword::DISTINCT, Keyword::AS, Keyword::VALUE]) {
15771            Some(ValueTableMode::DistinctAsValue)
15772        } else if self.parse_keywords(&[Keyword::DISTINCT, Keyword::AS, Keyword::STRUCT]) {
15773            Some(ValueTableMode::DistinctAsStruct)
15774        } else if self.parse_keywords(&[Keyword::AS, Keyword::VALUE])
15775            || self.parse_keywords(&[Keyword::ALL, Keyword::AS, Keyword::VALUE])
15776        {
15777            Some(ValueTableMode::AsValue)
15778        } else if self.parse_keywords(&[Keyword::AS, Keyword::STRUCT])
15779            || self.parse_keywords(&[Keyword::ALL, Keyword::AS, Keyword::STRUCT])
15780        {
15781            Some(ValueTableMode::AsStruct)
15782        } else if self.parse_keyword(Keyword::AS) {
15783            self.expected_ref("VALUE or STRUCT", self.peek_token_ref())?
15784        } else {
15785            None
15786        };
15787
15788        Ok(mode)
15789    }
15790
15791    /// Invoke `f` after first setting the parser's `ParserState` to `state`.
15792    ///
15793    /// Upon return, restores the parser's state to what it started at.
15794    fn with_state<T, F>(&mut self, state: ParserState, mut f: F) -> Result<T, ParserError>
15795    where
15796        F: FnMut(&mut Parser) -> Result<T, ParserError>,
15797    {
15798        let current_state = self.state;
15799        self.state = state;
15800        let res = f(self);
15801        self.state = current_state;
15802        res
15803    }
15804
15805    /// Parse a `CONNECT BY` clause (Oracle-style hierarchical query support).
15806    pub fn maybe_parse_connect_by(&mut self) -> Result<Vec<ConnectByKind>, ParserError> {
15807        let mut clauses = Vec::with_capacity(2);
15808        loop {
15809            if let Some(idx) = self.parse_keywords_indexed(&[Keyword::START, Keyword::WITH]) {
15810                clauses.push(ConnectByKind::StartWith {
15811                    start_token: self.token_at(idx).clone().into(),
15812                    condition: self.parse_expr()?.into(),
15813                });
15814            } else if let Some(idx) = self.parse_keywords_indexed(&[Keyword::CONNECT, Keyword::BY])
15815            {
15816                clauses.push(ConnectByKind::ConnectBy {
15817                    connect_token: self.token_at(idx).clone().into(),
15818                    nocycle: self.parse_keyword(Keyword::NOCYCLE),
15819                    relationships: self.with_state(ParserState::ConnectBy, |parser| {
15820                        parser.parse_comma_separated(Parser::parse_expr)
15821                    })?,
15822                });
15823            } else {
15824                break;
15825            }
15826        }
15827        Ok(clauses)
15828    }
15829
15830    /// Parse `CREATE TABLE x AS TABLE y`
15831    pub fn parse_as_table(&mut self) -> Result<Table, ParserError> {
15832        let first_name = self.parse_identifier()?;
15833        if self.consume_token(&Token::Period) {
15834            let second_name = self.parse_identifier()?;
15835            Ok(Table {
15836                table_name: Some(second_name),
15837                schema_name: Some(first_name),
15838            })
15839        } else {
15840            Ok(Table {
15841                table_name: Some(first_name),
15842                schema_name: None,
15843            })
15844        }
15845    }
15846
15847    /// Parse a `SET ROLE` statement. Expects SET to be consumed already.
15848    fn parse_set_role(
15849        &mut self,
15850        modifier: Option<ContextModifier>,
15851    ) -> Result<Statement, ParserError> {
15852        self.expect_keyword_is(Keyword::ROLE)?;
15853
15854        let role_name = if self.parse_keyword(Keyword::NONE) {
15855            None
15856        } else {
15857            Some(self.parse_identifier()?)
15858        };
15859        Ok(Statement::Set(Set::SetRole {
15860            context_modifier: modifier,
15861            role_name,
15862        }))
15863    }
15864
15865    fn parse_set_values(
15866        &mut self,
15867        parenthesized_assignment: bool,
15868    ) -> Result<Vec<Expr>, ParserError> {
15869        let mut values = vec![];
15870
15871        if parenthesized_assignment {
15872            self.expect_token(&Token::LParen)?;
15873        }
15874
15875        loop {
15876            let value = if let Some(expr) = self.try_parse_expr_sub_query()? {
15877                expr
15878            } else if let Ok(expr) = self.parse_expr() {
15879                expr
15880            } else {
15881                self.expected_ref("variable value", self.peek_token_ref())?
15882            };
15883
15884            values.push(value);
15885            if self.consume_token(&Token::Comma) {
15886                continue;
15887            }
15888
15889            if parenthesized_assignment {
15890                self.expect_token(&Token::RParen)?;
15891            }
15892            return Ok(values);
15893        }
15894    }
15895
15896    fn parse_context_modifier(&mut self) -> Option<ContextModifier> {
15897        let modifier =
15898            self.parse_one_of_keywords(&[Keyword::SESSION, Keyword::LOCAL, Keyword::GLOBAL])?;
15899
15900        Self::keyword_to_modifier(modifier)
15901    }
15902
15903    /// Parse a single SET statement assignment `var = expr`.
15904    fn parse_set_assignment(&mut self) -> Result<SetAssignment, ParserError> {
15905        let scope = self.parse_context_modifier();
15906
15907        let name = if self.dialect.supports_parenthesized_set_variables()
15908            && self.consume_token(&Token::LParen)
15909        {
15910            // Parenthesized assignments are handled in the `parse_set` function after
15911            // trying to parse list of assignments using this function.
15912            // If a dialect supports both, and we find a LParen, we early exit from this function.
15913            self.expected_ref("Unparenthesized assignment", self.peek_token_ref())?
15914        } else {
15915            self.parse_object_name(false)?
15916        };
15917
15918        if !(self.consume_token(&Token::Eq) || self.parse_keyword(Keyword::TO)) {
15919            return self.expected_ref("assignment operator", self.peek_token_ref());
15920        }
15921
15922        let value = self.parse_expr()?;
15923
15924        Ok(SetAssignment { scope, name, value })
15925    }
15926
15927    fn parse_set(&mut self) -> Result<Statement, ParserError> {
15928        let hivevar = self.parse_keyword(Keyword::HIVEVAR);
15929
15930        // Modifier is either HIVEVAR: or a ContextModifier (LOCAL, SESSION, etc), not both
15931        let scope = if !hivevar {
15932            self.parse_context_modifier()
15933        } else {
15934            None
15935        };
15936
15937        if hivevar {
15938            self.expect_token(&Token::Colon)?;
15939        }
15940
15941        if let Some(set_role_stmt) = self.maybe_parse(|parser| parser.parse_set_role(scope))? {
15942            return Ok(set_role_stmt);
15943        }
15944
15945        // Handle special cases first
15946        if self.parse_keywords(&[Keyword::TIME, Keyword::ZONE])
15947            || self.parse_keyword(Keyword::TIMEZONE)
15948        {
15949            if self.consume_token(&Token::Eq) || self.parse_keyword(Keyword::TO) {
15950                return Ok(Set::SingleAssignment {
15951                    scope,
15952                    hivevar,
15953                    variable: ObjectName::from(vec!["TIMEZONE".into()]),
15954                    values: self.parse_set_values(false)?,
15955                }
15956                .into());
15957            } else {
15958                // A shorthand alias for SET TIME ZONE that doesn't require
15959                // the assignment operator. It's originally PostgreSQL specific,
15960                // but we allow it for all the dialects
15961                return Ok(Set::SetTimeZone {
15962                    local: scope == Some(ContextModifier::Local),
15963                    value: self.parse_expr()?,
15964                }
15965                .into());
15966            }
15967        } else if self.dialect.supports_set_schema() && self.parse_keyword(Keyword::SCHEMA) {
15968            let value = self.parse_literal_string()?;
15969            return Ok(Set::SingleAssignment {
15970                scope,
15971                hivevar,
15972                variable: ObjectName::from(vec!["search_path".into()]),
15973                values: vec![Expr::Value(Value::SingleQuotedString(value).into())],
15974            }
15975            .into());
15976        } else if self.dialect.supports_set_names() && self.parse_keyword(Keyword::NAMES) {
15977            if self.parse_keyword(Keyword::DEFAULT) {
15978                return Ok(Set::SetNamesDefault {}.into());
15979            }
15980            let charset_name = self.parse_identifier()?;
15981            let collation_name = if self.parse_one_of_keywords(&[Keyword::COLLATE]).is_some() {
15982                Some(self.parse_literal_string()?)
15983            } else {
15984                None
15985            };
15986
15987            return Ok(Set::SetNames {
15988                charset_name,
15989                collation_name,
15990            }
15991            .into());
15992        } else if self.parse_keyword(Keyword::CHARACTERISTICS) {
15993            self.expect_keywords(&[Keyword::AS, Keyword::TRANSACTION])?;
15994            return Ok(Set::SetTransaction {
15995                modes: self.parse_transaction_modes()?,
15996                snapshot: None,
15997                session: true,
15998            }
15999            .into());
16000        } else if self.parse_keyword(Keyword::TRANSACTION) {
16001            if self.parse_keyword(Keyword::SNAPSHOT) {
16002                let snapshot_id = self.parse_value()?;
16003                return Ok(Set::SetTransaction {
16004                    modes: vec![],
16005                    snapshot: Some(snapshot_id),
16006                    session: false,
16007                }
16008                .into());
16009            }
16010            return Ok(Set::SetTransaction {
16011                modes: self.parse_transaction_modes()?,
16012                snapshot: None,
16013                session: false,
16014            }
16015            .into());
16016        } else if self.parse_keyword(Keyword::AUTHORIZATION) {
16017            let scope = match scope {
16018                Some(s) => s,
16019                None => {
16020                    return self.expected_at(
16021                        "SESSION, LOCAL, or other scope modifier before AUTHORIZATION",
16022                        self.get_current_index(),
16023                    )
16024                }
16025            };
16026            let auth_value = if self.parse_keyword(Keyword::DEFAULT) {
16027                SetSessionAuthorizationParamKind::Default
16028            } else {
16029                let value = self.parse_identifier()?;
16030                SetSessionAuthorizationParamKind::User(value)
16031            };
16032            return Ok(Set::SetSessionAuthorization(SetSessionAuthorizationParam {
16033                scope,
16034                kind: auth_value,
16035            })
16036            .into());
16037        }
16038
16039        if self.dialect.supports_comma_separated_set_assignments() {
16040            if scope.is_some() {
16041                self.prev_token();
16042            }
16043
16044            if let Some(assignments) = self
16045                .maybe_parse(|parser| parser.parse_comma_separated(Parser::parse_set_assignment))?
16046            {
16047                return if assignments.len() > 1 {
16048                    Ok(Set::MultipleAssignments { assignments }.into())
16049                } else {
16050                    let SetAssignment { scope, name, value } =
16051                        assignments.into_iter().next().ok_or_else(|| {
16052                            ParserError::ParserError("Expected at least one assignment".to_string())
16053                        })?;
16054
16055                    Ok(Set::SingleAssignment {
16056                        scope,
16057                        hivevar,
16058                        variable: name,
16059                        values: vec![value],
16060                    }
16061                    .into())
16062                };
16063            }
16064        }
16065
16066        let variables = if self.dialect.supports_parenthesized_set_variables()
16067            && self.consume_token(&Token::LParen)
16068        {
16069            let vars = OneOrManyWithParens::Many(
16070                self.parse_comma_separated(|parser: &mut Parser<'a>| parser.parse_identifier())?
16071                    .into_iter()
16072                    .map(|ident| ObjectName::from(vec![ident]))
16073                    .collect(),
16074            );
16075            self.expect_token(&Token::RParen)?;
16076            vars
16077        } else {
16078            OneOrManyWithParens::One(self.parse_object_name(false)?)
16079        };
16080
16081        if self.consume_token(&Token::Eq) || self.parse_keyword(Keyword::TO) {
16082            let stmt = match variables {
16083                OneOrManyWithParens::One(var) => Set::SingleAssignment {
16084                    scope,
16085                    hivevar,
16086                    variable: var,
16087                    values: self.parse_set_values(false)?,
16088                },
16089                OneOrManyWithParens::Many(vars) => Set::ParenthesizedAssignments {
16090                    variables: vars,
16091                    values: self.parse_set_values(true)?,
16092                },
16093            };
16094
16095            return Ok(stmt.into());
16096        }
16097
16098        if self.dialect.supports_set_stmt_without_operator() {
16099            self.prev_token();
16100            return self.parse_set_session_params();
16101        };
16102
16103        self.expected_ref("equals sign or TO", self.peek_token_ref())
16104    }
16105
16106    /// Parse session parameter assignments after `SET` when no `=` or `TO` is present.
16107    pub fn parse_set_session_params(&mut self) -> Result<Statement, ParserError> {
16108        if self.parse_keyword(Keyword::STATISTICS) {
16109            let topic = match self.parse_one_of_keywords(&[
16110                Keyword::IO,
16111                Keyword::PROFILE,
16112                Keyword::TIME,
16113                Keyword::XML,
16114            ]) {
16115                Some(Keyword::IO) => SessionParamStatsTopic::IO,
16116                Some(Keyword::PROFILE) => SessionParamStatsTopic::Profile,
16117                Some(Keyword::TIME) => SessionParamStatsTopic::Time,
16118                Some(Keyword::XML) => SessionParamStatsTopic::Xml,
16119                _ => return self.expected_ref("IO, PROFILE, TIME or XML", self.peek_token_ref()),
16120            };
16121            let value = self.parse_session_param_value()?;
16122            Ok(
16123                Set::SetSessionParam(SetSessionParamKind::Statistics(SetSessionParamStatistics {
16124                    topic,
16125                    value,
16126                }))
16127                .into(),
16128            )
16129        } else if self.parse_keyword(Keyword::IDENTITY_INSERT) {
16130            let obj = self.parse_object_name(false)?;
16131            let value = self.parse_session_param_value()?;
16132            Ok(Set::SetSessionParam(SetSessionParamKind::IdentityInsert(
16133                SetSessionParamIdentityInsert { obj, value },
16134            ))
16135            .into())
16136        } else if self.parse_keyword(Keyword::OFFSETS) {
16137            let keywords = self.parse_comma_separated(|parser| {
16138                let next_token = parser.next_token();
16139                match &next_token.token {
16140                    Token::Word(w) => Ok(w.to_string()),
16141                    _ => parser.expected("SQL keyword", next_token),
16142                }
16143            })?;
16144            let value = self.parse_session_param_value()?;
16145            Ok(
16146                Set::SetSessionParam(SetSessionParamKind::Offsets(SetSessionParamOffsets {
16147                    keywords,
16148                    value,
16149                }))
16150                .into(),
16151            )
16152        } else {
16153            let names = self.parse_comma_separated(|parser| {
16154                let next_token = parser.next_token();
16155                match next_token.token {
16156                    Token::Word(w) => Ok(w.to_string()),
16157                    _ => parser.expected("Session param name", next_token),
16158                }
16159            })?;
16160            let value = self.parse_expr()?.to_string();
16161            Ok(
16162                Set::SetSessionParam(SetSessionParamKind::Generic(SetSessionParamGeneric {
16163                    names,
16164                    value,
16165                }))
16166                .into(),
16167            )
16168        }
16169    }
16170
16171    fn parse_session_param_value(&mut self) -> Result<SessionParamValue, ParserError> {
16172        if self.parse_keyword(Keyword::ON) {
16173            Ok(SessionParamValue::On)
16174        } else if self.parse_keyword(Keyword::OFF) {
16175            Ok(SessionParamValue::Off)
16176        } else {
16177            self.expected_ref("ON or OFF", self.peek_token_ref())
16178        }
16179    }
16180
16181    /// Parse a `SHOW` statement and dispatch to specific SHOW handlers.
16182    pub fn parse_show(&mut self) -> Result<Statement, ParserError> {
16183        let terse = self.parse_keyword(Keyword::TERSE);
16184        let extended = self.parse_keyword(Keyword::EXTENDED);
16185        let full = self.parse_keyword(Keyword::FULL);
16186        let session = self.parse_keyword(Keyword::SESSION);
16187        let global = self.parse_keyword(Keyword::GLOBAL);
16188        let external = self.parse_keyword(Keyword::EXTERNAL);
16189        if self
16190            .parse_one_of_keywords(&[Keyword::COLUMNS, Keyword::FIELDS])
16191            .is_some()
16192        {
16193            Ok(self.parse_show_columns(extended, full)?)
16194        } else if self.parse_keyword(Keyword::TABLES) {
16195            Ok(self.parse_show_tables(terse, extended, full, external)?)
16196        } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEWS]) {
16197            Ok(self.parse_show_views(terse, true)?)
16198        } else if self.parse_keyword(Keyword::VIEWS) {
16199            Ok(self.parse_show_views(terse, false)?)
16200        } else if self.parse_keyword(Keyword::FUNCTIONS) {
16201            Ok(self.parse_show_functions()?)
16202        } else if self.parse_keyword(Keyword::PROCESSLIST) {
16203            Ok(Statement::ShowProcessList { full })
16204        } else if extended || full {
16205            Err(ParserError::ParserError(
16206                "EXTENDED/FULL are not supported with this type of SHOW query".to_string(),
16207            ))
16208        } else if self.parse_one_of_keywords(&[Keyword::CREATE]).is_some() {
16209            Ok(self.parse_show_create()?)
16210        } else if self.parse_keyword(Keyword::COLLATION) {
16211            Ok(self.parse_show_collation()?)
16212        } else if self.parse_keyword(Keyword::VARIABLES)
16213            && dialect_of!(self is MySqlDialect | GenericDialect)
16214        {
16215            Ok(Statement::ShowVariables {
16216                filter: self.parse_show_statement_filter()?,
16217                session,
16218                global,
16219            })
16220        } else if self.parse_keyword(Keyword::STATUS)
16221            && dialect_of!(self is MySqlDialect | GenericDialect)
16222        {
16223            Ok(Statement::ShowStatus {
16224                filter: self.parse_show_statement_filter()?,
16225                session,
16226                global,
16227            })
16228        } else if self.parse_keyword(Keyword::CATALOGS) {
16229            self.parse_show_catalogs(terse)
16230        } else if self.parse_keyword(Keyword::DATABASES) {
16231            self.parse_show_databases(terse)
16232        } else if self.parse_keyword(Keyword::SCHEMAS) {
16233            self.parse_show_schemas(terse)
16234        } else if self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET]) {
16235            self.parse_show_charset(false)
16236        } else if self.parse_keyword(Keyword::CHARSET) {
16237            self.parse_show_charset(true)
16238        } else {
16239            Ok(Statement::ShowVariable {
16240                variable: self.parse_identifiers()?,
16241            })
16242        }
16243    }
16244
16245    fn parse_show_charset(&mut self, is_shorthand: bool) -> Result<Statement, ParserError> {
16246        // parse one of keywords
16247        Ok(Statement::ShowCharset(ShowCharset {
16248            is_shorthand,
16249            filter: self.parse_show_statement_filter()?,
16250        }))
16251    }
16252
16253    fn parse_show_catalogs(&mut self, terse: bool) -> Result<Statement, ParserError> {
16254        let history = self.parse_keyword(Keyword::HISTORY);
16255        let show_options = self.parse_show_stmt_options()?;
16256        Ok(Statement::ShowCatalogs {
16257            terse,
16258            history,
16259            show_options,
16260        })
16261    }
16262
16263    fn parse_show_databases(&mut self, terse: bool) -> Result<Statement, ParserError> {
16264        let history = self.parse_keyword(Keyword::HISTORY);
16265        let show_options = self.parse_show_stmt_options()?;
16266        Ok(Statement::ShowDatabases {
16267            terse,
16268            history,
16269            show_options,
16270        })
16271    }
16272
16273    fn parse_show_schemas(&mut self, terse: bool) -> Result<Statement, ParserError> {
16274        let history = self.parse_keyword(Keyword::HISTORY);
16275        let show_options = self.parse_show_stmt_options()?;
16276        Ok(Statement::ShowSchemas {
16277            terse,
16278            history,
16279            show_options,
16280        })
16281    }
16282
16283    /// Parse `SHOW CREATE <object>` returning the corresponding `ShowCreate` statement.
16284    pub fn parse_show_create(&mut self) -> Result<Statement, ParserError> {
16285        let obj_type = match self.expect_one_of_keywords(&[
16286            Keyword::TABLE,
16287            Keyword::TRIGGER,
16288            Keyword::FUNCTION,
16289            Keyword::PROCEDURE,
16290            Keyword::EVENT,
16291            Keyword::VIEW,
16292        ])? {
16293            Keyword::TABLE => Ok(ShowCreateObject::Table),
16294            Keyword::TRIGGER => Ok(ShowCreateObject::Trigger),
16295            Keyword::FUNCTION => Ok(ShowCreateObject::Function),
16296            Keyword::PROCEDURE => Ok(ShowCreateObject::Procedure),
16297            Keyword::EVENT => Ok(ShowCreateObject::Event),
16298            Keyword::VIEW => Ok(ShowCreateObject::View),
16299            keyword => Err(ParserError::ParserError(format!(
16300                "Unable to map keyword to ShowCreateObject: {keyword:?}"
16301            ))),
16302        }?;
16303
16304        let obj_name = self.parse_object_name(false)?;
16305
16306        Ok(Statement::ShowCreate { obj_type, obj_name })
16307    }
16308
16309    /// Parse `SHOW COLUMNS`/`SHOW FIELDS` and return a `ShowColumns` statement.
16310    pub fn parse_show_columns(
16311        &mut self,
16312        extended: bool,
16313        full: bool,
16314    ) -> Result<Statement, ParserError> {
16315        let show_options = self.parse_show_stmt_options()?;
16316        Ok(Statement::ShowColumns {
16317            extended,
16318            full,
16319            show_options,
16320        })
16321    }
16322
16323    fn parse_show_tables(
16324        &mut self,
16325        terse: bool,
16326        extended: bool,
16327        full: bool,
16328        external: bool,
16329    ) -> Result<Statement, ParserError> {
16330        let history = !external && self.parse_keyword(Keyword::HISTORY);
16331        let show_options = self.parse_show_stmt_options()?;
16332        Ok(Statement::ShowTables {
16333            terse,
16334            history,
16335            extended,
16336            full,
16337            external,
16338            show_options,
16339        })
16340    }
16341
16342    fn parse_show_views(
16343        &mut self,
16344        terse: bool,
16345        materialized: bool,
16346    ) -> Result<Statement, ParserError> {
16347        let show_options = self.parse_show_stmt_options()?;
16348        Ok(Statement::ShowViews {
16349            materialized,
16350            terse,
16351            show_options,
16352        })
16353    }
16354
16355    /// Parse `SHOW FUNCTIONS` and optional filter.
16356    pub fn parse_show_functions(&mut self) -> Result<Statement, ParserError> {
16357        let filter = self.parse_show_statement_filter()?;
16358        Ok(Statement::ShowFunctions { filter })
16359    }
16360
16361    /// Parse `SHOW COLLATION` and optional filter.
16362    pub fn parse_show_collation(&mut self) -> Result<Statement, ParserError> {
16363        let filter = self.parse_show_statement_filter()?;
16364        Ok(Statement::ShowCollation { filter })
16365    }
16366
16367    /// Parse an optional filter used by `SHOW` statements (LIKE, ILIKE, WHERE, or literal).
16368    pub fn parse_show_statement_filter(
16369        &mut self,
16370    ) -> Result<Option<ShowStatementFilter>, ParserError> {
16371        if self.parse_keyword(Keyword::LIKE) {
16372            Ok(Some(ShowStatementFilter::Like(
16373                self.parse_literal_string()?,
16374            )))
16375        } else if self.parse_keyword(Keyword::ILIKE) {
16376            Ok(Some(ShowStatementFilter::ILike(
16377                self.parse_literal_string()?,
16378            )))
16379        } else if self.parse_keyword(Keyword::WHERE) {
16380            Ok(Some(ShowStatementFilter::Where(self.parse_expr()?)))
16381        } else {
16382            self.maybe_parse(|parser| -> Result<String, ParserError> {
16383                parser.parse_literal_string()
16384            })?
16385            .map_or(Ok(None), |filter| {
16386                Ok(Some(ShowStatementFilter::NoKeyword(filter)))
16387            })
16388        }
16389    }
16390
16391    /// Parse a `USE` statement (database/catalog/schema/warehouse/role selection).
16392    pub fn parse_use(&mut self) -> Result<Statement, ParserError> {
16393        // Determine which keywords are recognized by the current dialect
16394        let parsed_keyword = if dialect_of!(self is HiveDialect) {
16395            // HiveDialect accepts USE DEFAULT; statement without any db specified
16396            if self.parse_keyword(Keyword::DEFAULT) {
16397                return Ok(Statement::Use(Use::Default));
16398            }
16399            None // HiveDialect doesn't expect any other specific keyword after `USE`
16400        } else if dialect_of!(self is DatabricksDialect) {
16401            self.parse_one_of_keywords(&[Keyword::CATALOG, Keyword::DATABASE, Keyword::SCHEMA])
16402        } else if dialect_of!(self is SnowflakeDialect) {
16403            self.parse_one_of_keywords(&[
16404                Keyword::DATABASE,
16405                Keyword::SCHEMA,
16406                Keyword::WAREHOUSE,
16407                Keyword::ROLE,
16408                Keyword::SECONDARY,
16409            ])
16410        } else {
16411            None // No specific keywords for other dialects, including GenericDialect
16412        };
16413
16414        let result = if matches!(parsed_keyword, Some(Keyword::SECONDARY)) {
16415            self.parse_secondary_roles()?
16416        } else {
16417            let obj_name = self.parse_object_name(false)?;
16418            match parsed_keyword {
16419                Some(Keyword::CATALOG) => Use::Catalog(obj_name),
16420                Some(Keyword::DATABASE) => Use::Database(obj_name),
16421                Some(Keyword::SCHEMA) => Use::Schema(obj_name),
16422                Some(Keyword::WAREHOUSE) => Use::Warehouse(obj_name),
16423                Some(Keyword::ROLE) => Use::Role(obj_name),
16424                _ => Use::Object(obj_name),
16425            }
16426        };
16427
16428        Ok(Statement::Use(result))
16429    }
16430
16431    fn parse_secondary_roles(&mut self) -> Result<Use, ParserError> {
16432        self.expect_one_of_keywords(&[Keyword::ROLES, Keyword::ROLE])?;
16433        if self.parse_keyword(Keyword::NONE) {
16434            Ok(Use::SecondaryRoles(SecondaryRoles::None))
16435        } else if self.parse_keyword(Keyword::ALL) {
16436            Ok(Use::SecondaryRoles(SecondaryRoles::All))
16437        } else {
16438            let roles = self.parse_comma_separated(|parser| parser.parse_identifier())?;
16439            Ok(Use::SecondaryRoles(SecondaryRoles::List(roles)))
16440        }
16441    }
16442
16443    /// Parse a table factor followed by any join clauses, returning `TableWithJoins`.
16444    pub fn parse_table_and_joins(&mut self) -> Result<TableWithJoins, ParserError> {
16445        let relation = self.parse_table_factor()?;
16446        // Note that for keywords to be properly handled here, they need to be
16447        // added to `RESERVED_FOR_TABLE_ALIAS`, otherwise they may be parsed as
16448        // a table alias.
16449        let joins = self.parse_joins()?;
16450        Ok(TableWithJoins { relation, joins })
16451    }
16452
16453    fn parse_joins(&mut self) -> Result<Vec<Join>, ParserError> {
16454        let mut joins = vec![];
16455        loop {
16456            let global = self.parse_keyword(Keyword::GLOBAL);
16457            let join = if self.parse_keyword(Keyword::CROSS) {
16458                let join_operator = if self.parse_keyword(Keyword::JOIN) {
16459                    JoinOperator::CrossJoin(JoinConstraint::None)
16460                } else if self.parse_keyword(Keyword::APPLY) {
16461                    // MSSQL extension, similar to CROSS JOIN LATERAL
16462                    JoinOperator::CrossApply
16463                } else {
16464                    return self.expected_ref("JOIN or APPLY after CROSS", self.peek_token_ref());
16465                };
16466                let relation = self.parse_table_factor()?;
16467                let join_operator = if matches!(join_operator, JoinOperator::CrossJoin(_))
16468                    && self.dialect.supports_cross_join_constraint()
16469                {
16470                    let constraint = self.parse_join_constraint(false)?;
16471                    JoinOperator::CrossJoin(constraint)
16472                } else {
16473                    join_operator
16474                };
16475                Join {
16476                    relation,
16477                    global,
16478                    join_operator,
16479                }
16480            } else if self.parse_keyword(Keyword::OUTER) {
16481                // MSSQL extension, similar to LEFT JOIN LATERAL .. ON 1=1
16482                self.expect_keyword_is(Keyword::APPLY)?;
16483                Join {
16484                    relation: self.parse_table_factor()?,
16485                    global,
16486                    join_operator: JoinOperator::OuterApply,
16487                }
16488            } else if self.parse_keyword(Keyword::ASOF) {
16489                self.expect_keyword_is(Keyword::JOIN)?;
16490                let relation = self.parse_table_factor()?;
16491                self.expect_keyword_is(Keyword::MATCH_CONDITION)?;
16492                let match_condition = self.parse_parenthesized(Self::parse_expr)?;
16493                Join {
16494                    relation,
16495                    global,
16496                    join_operator: JoinOperator::AsOf {
16497                        match_condition,
16498                        constraint: self.parse_join_constraint(false)?,
16499                    },
16500                }
16501            } else if self.dialect.supports_array_join_syntax()
16502                && self.parse_keywords(&[Keyword::INNER, Keyword::ARRAY, Keyword::JOIN])
16503            {
16504                // ClickHouse: INNER ARRAY JOIN
16505                Join {
16506                    relation: self.parse_table_factor()?,
16507                    global,
16508                    join_operator: JoinOperator::InnerArrayJoin,
16509                }
16510            } else if self.dialect.supports_array_join_syntax()
16511                && self.parse_keywords(&[Keyword::LEFT, Keyword::ARRAY, Keyword::JOIN])
16512            {
16513                // ClickHouse: LEFT ARRAY JOIN
16514                Join {
16515                    relation: self.parse_table_factor()?,
16516                    global,
16517                    join_operator: JoinOperator::LeftArrayJoin,
16518                }
16519            } else if self.dialect.supports_array_join_syntax()
16520                && self.parse_keywords(&[Keyword::ARRAY, Keyword::JOIN])
16521            {
16522                // ClickHouse: ARRAY JOIN
16523                Join {
16524                    relation: self.parse_table_factor()?,
16525                    global,
16526                    join_operator: JoinOperator::ArrayJoin,
16527                }
16528            } else {
16529                let natural = self.parse_keyword(Keyword::NATURAL);
16530                let peek_keyword = if let Token::Word(w) = &self.peek_token_ref().token {
16531                    w.keyword
16532                } else {
16533                    Keyword::NoKeyword
16534                };
16535
16536                let join_operator_type = match peek_keyword {
16537                    Keyword::INNER | Keyword::JOIN => {
16538                        let inner = self.parse_keyword(Keyword::INNER); // [ INNER ]
16539                        self.expect_keyword_is(Keyword::JOIN)?;
16540                        if inner {
16541                            JoinOperator::Inner
16542                        } else {
16543                            JoinOperator::Join
16544                        }
16545                    }
16546                    kw @ Keyword::LEFT | kw @ Keyword::RIGHT => {
16547                        let _ = self.next_token(); // consume LEFT/RIGHT
16548                        let is_left = kw == Keyword::LEFT;
16549                        let join_type = self.parse_one_of_keywords(&[
16550                            Keyword::OUTER,
16551                            Keyword::SEMI,
16552                            Keyword::ANTI,
16553                            Keyword::JOIN,
16554                        ]);
16555                        match join_type {
16556                            Some(Keyword::OUTER) => {
16557                                self.expect_keyword_is(Keyword::JOIN)?;
16558                                if is_left {
16559                                    JoinOperator::LeftOuter
16560                                } else {
16561                                    JoinOperator::RightOuter
16562                                }
16563                            }
16564                            Some(Keyword::SEMI) => {
16565                                self.expect_keyword_is(Keyword::JOIN)?;
16566                                if is_left {
16567                                    JoinOperator::LeftSemi
16568                                } else {
16569                                    JoinOperator::RightSemi
16570                                }
16571                            }
16572                            Some(Keyword::ANTI) => {
16573                                self.expect_keyword_is(Keyword::JOIN)?;
16574                                if is_left {
16575                                    JoinOperator::LeftAnti
16576                                } else {
16577                                    JoinOperator::RightAnti
16578                                }
16579                            }
16580                            Some(Keyword::JOIN) => {
16581                                if is_left {
16582                                    JoinOperator::Left
16583                                } else {
16584                                    JoinOperator::Right
16585                                }
16586                            }
16587                            _ => {
16588                                return Err(ParserError::ParserError(format!(
16589                                    "expected OUTER, SEMI, ANTI or JOIN after {kw:?}"
16590                                )))
16591                            }
16592                        }
16593                    }
16594                    Keyword::ANTI => {
16595                        let _ = self.next_token(); // consume ANTI
16596                        self.expect_keyword_is(Keyword::JOIN)?;
16597                        JoinOperator::Anti
16598                    }
16599                    Keyword::SEMI => {
16600                        let _ = self.next_token(); // consume SEMI
16601                        self.expect_keyword_is(Keyword::JOIN)?;
16602                        JoinOperator::Semi
16603                    }
16604                    Keyword::FULL => {
16605                        let _ = self.next_token(); // consume FULL
16606                        let _ = self.parse_keyword(Keyword::OUTER); // [ OUTER ]
16607                        self.expect_keyword_is(Keyword::JOIN)?;
16608                        JoinOperator::FullOuter
16609                    }
16610                    Keyword::OUTER => {
16611                        return self.expected_ref("LEFT, RIGHT, or FULL", self.peek_token_ref());
16612                    }
16613                    Keyword::STRAIGHT_JOIN => {
16614                        let _ = self.next_token(); // consume STRAIGHT_JOIN
16615                        JoinOperator::StraightJoin
16616                    }
16617                    _ if natural => {
16618                        return self
16619                            .expected_ref("a join type after NATURAL", self.peek_token_ref());
16620                    }
16621                    _ => break,
16622                };
16623                let mut relation = self.parse_table_factor()?;
16624
16625                if !self
16626                    .dialect
16627                    .supports_left_associative_joins_without_parens()
16628                    && !natural
16629                    && self.peek_parens_less_nested_join()
16630                {
16631                    let joins = self.parse_joins()?;
16632                    relation = TableFactor::NestedJoin {
16633                        table_with_joins: Box::new(TableWithJoins { relation, joins }),
16634                        alias: None,
16635                    };
16636                }
16637
16638                let join_constraint = self.parse_join_constraint(natural)?;
16639                Join {
16640                    relation,
16641                    global,
16642                    join_operator: join_operator_type(join_constraint),
16643                }
16644            };
16645            joins.push(join);
16646        }
16647        Ok(joins)
16648    }
16649
16650    fn peek_parens_less_nested_join(&self) -> bool {
16651        matches!(
16652            self.peek_token_ref().token,
16653            Token::Word(Word {
16654                keyword: Keyword::JOIN
16655                    | Keyword::INNER
16656                    | Keyword::LEFT
16657                    | Keyword::RIGHT
16658                    | Keyword::FULL,
16659                ..
16660            })
16661        )
16662    }
16663
16664    /// A table name or a parenthesized subquery, followed by optional `[AS] alias`
16665    #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
16666    pub fn parse_table_factor(&mut self) -> Result<TableFactor, ParserError> {
16667        let _guard = self.recursion_counter.try_decrease()?;
16668        if self.parse_keyword(Keyword::LATERAL) {
16669            // LATERAL must always be followed by a subquery or table function.
16670            if self.consume_token(&Token::LParen) {
16671                self.parse_derived_table_factor(Lateral)
16672            } else {
16673                let name = self.parse_object_name(false)?;
16674                self.expect_token(&Token::LParen)?;
16675                let args = self.parse_optional_args()?;
16676                let with_ordinality = self.parse_keywords(&[Keyword::WITH, Keyword::ORDINALITY]);
16677                let alias = self.maybe_parse_table_alias()?;
16678                Ok(TableFactor::Function {
16679                    lateral: true,
16680                    name,
16681                    args,
16682                    with_ordinality,
16683                    alias,
16684                })
16685            }
16686        } else if self.parse_keyword(Keyword::TABLE) {
16687            // parse table function (SELECT * FROM TABLE (<expr>) [ AS <alias> ])
16688            self.expect_token(&Token::LParen)?;
16689            let expr = self.parse_expr()?;
16690            self.expect_token(&Token::RParen)?;
16691            let alias = self.maybe_parse_table_alias()?;
16692            Ok(TableFactor::TableFunction { expr, alias })
16693        } else if self.consume_token(&Token::LParen) {
16694            // A left paren introduces either a derived table (i.e., a subquery)
16695            // or a nested join. It's nearly impossible to determine ahead of
16696            // time which it is... so we just try to parse both.
16697            //
16698            // Here's an example that demonstrates the complexity:
16699            //                     /-------------------------------------------------------\
16700            //                     | /-----------------------------------\                 |
16701            //     SELECT * FROM ( ( ( (SELECT 1) UNION (SELECT 2) ) AS t1 NATURAL JOIN t2 ) )
16702            //                   ^ ^ ^ ^
16703            //                   | | | |
16704            //                   | | | |
16705            //                   | | | (4) belongs to a SetExpr::Query inside the subquery
16706            //                   | | (3) starts a derived table (subquery)
16707            //                   | (2) starts a nested join
16708            //                   (1) an additional set of parens around a nested join
16709            //
16710
16711            // If the recently consumed '(' starts a derived table, the call to
16712            // `parse_derived_table_factor` below will return success after parsing the
16713            // subquery, followed by the closing ')', and the alias of the derived table.
16714            // In the example above this is case (3).
16715            //
16716            // Memoize failures to break the 2^N work on inputs like
16717            // `FROM ((((...`, where the nested-join fallback recurses back into
16718            // `parse_table_factor` and re-attempts the same speculative parse.
16719            let derived_pos = self.index;
16720            let derived = if self
16721                .failed_derived_table_factor_positions
16722                .contains(&derived_pos)
16723            {
16724                None
16725            } else {
16726                match self.maybe_parse(|parser| parser.parse_derived_table_factor(NotLateral))? {
16727                    Some(t) => Some(t),
16728                    None => {
16729                        self.failed_derived_table_factor_positions
16730                            .insert(derived_pos);
16731                        None
16732                    }
16733                }
16734            };
16735            if let Some(mut table) = derived {
16736                while let Some(kw) = self.parse_one_of_keywords(&[Keyword::PIVOT, Keyword::UNPIVOT])
16737                {
16738                    table = match kw {
16739                        Keyword::PIVOT => self.parse_pivot_table_factor(table)?,
16740                        Keyword::UNPIVOT => self.parse_unpivot_table_factor(table)?,
16741                        unexpected_keyword => return Err(ParserError::ParserError(
16742                            format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in pivot/unpivot"),
16743                        )),
16744                    }
16745                }
16746                return Ok(table);
16747            }
16748
16749            // A parsing error from `parse_derived_table_factor` indicates that the '(' we've
16750            // recently consumed does not start a derived table (cases 1, 2, or 4).
16751            // `maybe_parse` will ignore such an error and rewind to be after the opening '('.
16752
16753            // Inside the parentheses we expect to find an (A) table factor
16754            // followed by some joins or (B) another level of nesting.
16755            let mut table_and_joins = self.parse_table_and_joins()?;
16756
16757            #[allow(clippy::if_same_then_else)]
16758            if !table_and_joins.joins.is_empty() {
16759                self.expect_token(&Token::RParen)?;
16760                let alias = self.maybe_parse_table_alias()?;
16761                Ok(TableFactor::NestedJoin {
16762                    table_with_joins: Box::new(table_and_joins),
16763                    alias,
16764                }) // (A)
16765            } else if let TableFactor::NestedJoin {
16766                table_with_joins: _,
16767                alias: _,
16768            } = &table_and_joins.relation
16769            {
16770                // (B): `table_and_joins` (what we found inside the parentheses)
16771                // is a nested join `(foo JOIN bar)`, not followed by other joins.
16772                self.expect_token(&Token::RParen)?;
16773                let alias = self.maybe_parse_table_alias()?;
16774                Ok(TableFactor::NestedJoin {
16775                    table_with_joins: Box::new(table_and_joins),
16776                    alias,
16777                })
16778            } else if self.dialect.supports_parens_around_table_factor() {
16779                // Dialect-specific behavior: Snowflake diverges from the
16780                // standard and from most of the other implementations by
16781                // allowing extra parentheses not only around a join (B), but
16782                // around lone table names (e.g. `FROM (mytable [AS alias])`)
16783                // and around derived tables (e.g. `FROM ((SELECT ...)
16784                // [AS alias])`) as well.
16785                self.expect_token(&Token::RParen)?;
16786
16787                if let Some(outer_alias) = self.maybe_parse_table_alias()? {
16788                    // Snowflake also allows specifying an alias *after* parens
16789                    // e.g. `FROM (mytable) AS alias`
16790                    match &mut table_and_joins.relation {
16791                        TableFactor::Derived { alias, .. }
16792                        | TableFactor::Table { alias, .. }
16793                        | TableFactor::Function { alias, .. }
16794                        | TableFactor::UNNEST { alias, .. }
16795                        | TableFactor::JsonTable { alias, .. }
16796                        | TableFactor::XmlTable { alias, .. }
16797                        | TableFactor::OpenJsonTable { alias, .. }
16798                        | TableFactor::TableFunction { alias, .. }
16799                        | TableFactor::Pivot { alias, .. }
16800                        | TableFactor::Unpivot { alias, .. }
16801                        | TableFactor::MatchRecognize { alias, .. }
16802                        | TableFactor::SemanticView { alias, .. }
16803                        | TableFactor::NestedJoin { alias, .. } => {
16804                            // but not `FROM (mytable AS alias1) AS alias2`.
16805                            if let Some(inner_alias) = alias {
16806                                return Err(ParserError::ParserError(format!(
16807                                    "duplicate alias {inner_alias}"
16808                                )));
16809                            }
16810                            // Act as if the alias was specified normally next
16811                            // to the table name: `(mytable) AS alias` ->
16812                            // `(mytable AS alias)`
16813                            alias.replace(outer_alias);
16814                        }
16815                        TableFactor::UnpivotExpr { .. } => {
16816                            return Err(ParserError::ParserError(
16817                                "alias after parenthesized UNPIVOT expression is not supported"
16818                                    .to_string(),
16819                            ))
16820                        }
16821                    };
16822                }
16823                // Do not store the extra set of parens in the AST
16824                Ok(table_and_joins.relation)
16825            } else {
16826                // The SQL spec prohibits derived tables and bare tables from
16827                // appearing alone in parentheses (e.g. `FROM (mytable)`)
16828                self.expected_ref("joined table", self.peek_token_ref())
16829            }
16830        } else if self.dialect.supports_values_as_table_factor()
16831            && matches!(
16832                self.peek_tokens(),
16833                [
16834                    Token::Word(Word {
16835                        keyword: Keyword::VALUES,
16836                        ..
16837                    }),
16838                    Token::LParen
16839                ]
16840            )
16841        {
16842            self.expect_keyword_is(Keyword::VALUES)?;
16843
16844            // Snowflake and Databricks allow syntax like below:
16845            // SELECT * FROM VALUES (1, 'a'), (2, 'b') AS t (col1, col2)
16846            // where there are no parentheses around the VALUES clause.
16847            let values = SetExpr::Values(self.parse_values(false, false)?);
16848            let alias = self.maybe_parse_table_alias()?;
16849            Ok(TableFactor::Derived {
16850                lateral: false,
16851                subquery: Box::new(Query {
16852                    with: None,
16853                    body: Box::new(values),
16854                    order_by: None,
16855                    limit_clause: None,
16856                    fetch: None,
16857                    locks: vec![],
16858                    for_clause: None,
16859                    settings: None,
16860                    format_clause: None,
16861                    pipe_operators: vec![],
16862                }),
16863                alias,
16864                sample: None,
16865            })
16866        } else if dialect_of!(self is BigQueryDialect | PostgreSqlDialect | GenericDialect)
16867            && self.parse_keyword(Keyword::UNNEST)
16868        {
16869            self.expect_token(&Token::LParen)?;
16870            let array_exprs = self.parse_comma_separated(Parser::parse_expr)?;
16871            self.expect_token(&Token::RParen)?;
16872
16873            let with_ordinality = self.parse_keywords(&[Keyword::WITH, Keyword::ORDINALITY]);
16874            let alias = match self.maybe_parse_table_alias() {
16875                Ok(Some(alias)) => Some(alias),
16876                Ok(None) => None,
16877                Err(e) => return Err(e),
16878            };
16879
16880            let with_offset = match self.expect_keywords(&[Keyword::WITH, Keyword::OFFSET]) {
16881                Ok(()) => true,
16882                Err(_) => false,
16883            };
16884
16885            let with_offset_alias = if with_offset {
16886                match self.parse_optional_alias(keywords::RESERVED_FOR_COLUMN_ALIAS) {
16887                    Ok(Some(alias)) => Some(alias),
16888                    Ok(None) => None,
16889                    Err(e) => return Err(e),
16890                }
16891            } else {
16892                None
16893            };
16894
16895            Ok(TableFactor::UNNEST {
16896                alias,
16897                array_exprs,
16898                with_offset,
16899                with_offset_alias,
16900                with_ordinality,
16901            })
16902        } else if self.dialect.supports_unpivot_expr() && self.peek_keyword(Keyword::UNPIVOT) {
16903            self.parse_unpivot_expr_table_factor()
16904        } else if self.parse_keyword_with_tokens(Keyword::JSON_TABLE, &[Token::LParen]) {
16905            let json_expr = self.parse_expr()?;
16906            self.expect_token(&Token::Comma)?;
16907            let json_path = self.parse_value()?;
16908            self.expect_keyword_is(Keyword::COLUMNS)?;
16909            self.expect_token(&Token::LParen)?;
16910            let columns = self.parse_comma_separated(Parser::parse_json_table_column_def)?;
16911            self.expect_token(&Token::RParen)?;
16912            self.expect_token(&Token::RParen)?;
16913            let alias = self.maybe_parse_table_alias()?;
16914            Ok(TableFactor::JsonTable {
16915                json_expr,
16916                json_path,
16917                columns,
16918                alias,
16919            })
16920        } else if self.parse_keyword_with_tokens(Keyword::OPENJSON, &[Token::LParen]) {
16921            self.prev_token();
16922            self.parse_open_json_table_factor()
16923        } else if self.parse_keyword_with_tokens(Keyword::XMLTABLE, &[Token::LParen]) {
16924            self.prev_token();
16925            self.parse_xml_table_factor()
16926        } else if self.dialect.supports_semantic_view_table_factor()
16927            && self.peek_keyword_with_tokens(Keyword::SEMANTIC_VIEW, &[Token::LParen])
16928        {
16929            self.parse_semantic_view_table_factor()
16930        } else if self.dialect.supports_stages() && self.peek_token_ref().token == Token::AtSign {
16931            // Stage reference: @mystage or @namespace.stage (e.g. Snowflake)
16932            self.parse_snowflake_stage_table_factor()
16933        } else {
16934            let name = self.parse_object_name(true)?;
16935
16936            let json_path = match &self.peek_token_ref().token {
16937                Token::LBracket if self.dialect.supports_partiql() => Some(self.parse_json_path()?),
16938                _ => None,
16939            };
16940
16941            let partitions: Vec<Ident> = if self.dialect.supports_table_partitions()
16942                && self.parse_keyword(Keyword::PARTITION)
16943            {
16944                self.parse_parenthesized_identifiers()?
16945            } else {
16946                vec![]
16947            };
16948
16949            // Parse potential version qualifier
16950            let version = self.maybe_parse_table_version()?;
16951
16952            // Postgres, MSSQL, ClickHouse: table-valued functions:
16953            let args = if self.consume_token(&Token::LParen) {
16954                Some(self.parse_table_function_args()?)
16955            } else {
16956                None
16957            };
16958
16959            let with_ordinality = self.parse_keywords(&[Keyword::WITH, Keyword::ORDINALITY]);
16960
16961            let mut sample = None;
16962            if self.dialect.supports_table_sample_before_alias() {
16963                if let Some(parsed_sample) = self.maybe_parse_table_sample()? {
16964                    sample = Some(TableSampleKind::BeforeTableAlias(parsed_sample));
16965                }
16966            }
16967
16968            let alias = self.maybe_parse_table_alias()?;
16969
16970            // MYSQL-specific table hints:
16971            let index_hints = if self.dialect.supports_table_hints() {
16972                self.maybe_parse(|p| p.parse_table_index_hints())?
16973                    .unwrap_or(vec![])
16974            } else {
16975                vec![]
16976            };
16977
16978            // MSSQL-specific table hints:
16979            let mut with_hints = vec![];
16980            if self.parse_keyword(Keyword::WITH) {
16981                if self.consume_token(&Token::LParen) {
16982                    with_hints = self.parse_comma_separated(Parser::parse_expr)?;
16983                    self.expect_token(&Token::RParen)?;
16984                } else {
16985                    // rewind, as WITH may belong to the next statement's CTE
16986                    self.prev_token();
16987                }
16988            };
16989
16990            if !self.dialect.supports_table_sample_before_alias() {
16991                if let Some(parsed_sample) = self.maybe_parse_table_sample()? {
16992                    sample = Some(TableSampleKind::AfterTableAlias(parsed_sample));
16993                }
16994            }
16995
16996            let mut table = TableFactor::Table {
16997                name,
16998                alias,
16999                args,
17000                with_hints,
17001                version,
17002                partitions,
17003                with_ordinality,
17004                json_path,
17005                sample,
17006                index_hints,
17007            };
17008
17009            while let Some(kw) = self.parse_one_of_keywords(&[Keyword::PIVOT, Keyword::UNPIVOT]) {
17010                table = match kw {
17011                    Keyword::PIVOT => self.parse_pivot_table_factor(table)?,
17012                    Keyword::UNPIVOT => self.parse_unpivot_table_factor(table)?,
17013                    unexpected_keyword => return Err(ParserError::ParserError(
17014                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in pivot/unpivot"),
17015                    )),
17016                }
17017            }
17018
17019            if self.dialect.supports_match_recognize()
17020                && self.parse_keyword(Keyword::MATCH_RECOGNIZE)
17021            {
17022                table = self.parse_match_recognize(table)?;
17023            }
17024
17025            Ok(table)
17026        }
17027    }
17028
17029    /// Parse a Snowflake stage reference as a table factor.
17030    /// Handles syntax like: `@mystage1 (file_format => 'myformat', pattern => '...')`
17031    ///
17032    /// See: <https://docs.snowflake.com/en/user-guide/querying-stage>
17033    fn parse_snowflake_stage_table_factor(&mut self) -> Result<TableFactor, ParserError> {
17034        // Parse the stage name starting with @
17035        let name = crate::dialect::parse_snowflake_stage_name(self)?;
17036
17037        // Parse optional stage options like (file_format => 'myformat', pattern => '...')
17038        let args = if self.consume_token(&Token::LParen) {
17039            Some(self.parse_table_function_args()?)
17040        } else {
17041            None
17042        };
17043
17044        let alias = self.maybe_parse_table_alias()?;
17045
17046        Ok(TableFactor::Table {
17047            name,
17048            alias,
17049            args,
17050            with_hints: vec![],
17051            version: None,
17052            partitions: vec![],
17053            with_ordinality: false,
17054            json_path: None,
17055            sample: None,
17056            index_hints: vec![],
17057        })
17058    }
17059
17060    fn maybe_parse_table_sample(&mut self) -> Result<Option<Box<TableSample>>, ParserError> {
17061        let modifier = if self.parse_keyword(Keyword::TABLESAMPLE) {
17062            TableSampleModifier::TableSample
17063        } else if self.parse_keyword(Keyword::SAMPLE) {
17064            TableSampleModifier::Sample
17065        } else {
17066            return Ok(None);
17067        };
17068        self.parse_table_sample(modifier).map(Some)
17069    }
17070
17071    fn parse_table_sample(
17072        &mut self,
17073        modifier: TableSampleModifier,
17074    ) -> Result<Box<TableSample>, ParserError> {
17075        let name = match self.parse_one_of_keywords(&[
17076            Keyword::BERNOULLI,
17077            Keyword::ROW,
17078            Keyword::SYSTEM,
17079            Keyword::BLOCK,
17080        ]) {
17081            Some(Keyword::BERNOULLI) => Some(TableSampleMethod::Bernoulli),
17082            Some(Keyword::ROW) => Some(TableSampleMethod::Row),
17083            Some(Keyword::SYSTEM) => Some(TableSampleMethod::System),
17084            Some(Keyword::BLOCK) => Some(TableSampleMethod::Block),
17085            _ => None,
17086        };
17087
17088        let parenthesized = self.consume_token(&Token::LParen);
17089
17090        let (quantity, bucket) = if parenthesized && self.parse_keyword(Keyword::BUCKET) {
17091            let selected_bucket = self.parse_number_value()?;
17092            self.expect_keywords(&[Keyword::OUT, Keyword::OF])?;
17093            let total = self.parse_number_value()?;
17094            let on = if self.parse_keyword(Keyword::ON) {
17095                Some(self.parse_expr()?)
17096            } else {
17097                None
17098            };
17099            (
17100                None,
17101                Some(TableSampleBucket {
17102                    bucket: selected_bucket,
17103                    total,
17104                    on,
17105                }),
17106            )
17107        } else {
17108            let value = match self.maybe_parse(|p| p.parse_expr())? {
17109                Some(num) => num,
17110                None => {
17111                    let next_token = self.next_token();
17112                    if let Token::Word(w) = next_token.token {
17113                        Expr::Value(Value::Placeholder(w.value).with_span(next_token.span))
17114                    } else {
17115                        return parser_err!(
17116                            "Expecting number or byte length e.g. 100M",
17117                            self.peek_token_ref().span.start
17118                        );
17119                    }
17120                }
17121            };
17122            let unit = if self.parse_keyword(Keyword::ROWS) {
17123                Some(TableSampleUnit::Rows)
17124            } else if self.parse_keyword(Keyword::PERCENT) {
17125                Some(TableSampleUnit::Percent)
17126            } else {
17127                None
17128            };
17129            (
17130                Some(TableSampleQuantity {
17131                    parenthesized,
17132                    value,
17133                    unit,
17134                }),
17135                None,
17136            )
17137        };
17138        if parenthesized {
17139            self.expect_token(&Token::RParen)?;
17140        }
17141
17142        let seed = if self.parse_keyword(Keyword::REPEATABLE) {
17143            Some(self.parse_table_sample_seed(TableSampleSeedModifier::Repeatable)?)
17144        } else if self.parse_keyword(Keyword::SEED) {
17145            Some(self.parse_table_sample_seed(TableSampleSeedModifier::Seed)?)
17146        } else {
17147            None
17148        };
17149
17150        let offset = if self.parse_keyword(Keyword::OFFSET) {
17151            Some(self.parse_expr()?)
17152        } else {
17153            None
17154        };
17155
17156        Ok(Box::new(TableSample {
17157            modifier,
17158            name,
17159            quantity,
17160            seed,
17161            bucket,
17162            offset,
17163        }))
17164    }
17165
17166    fn parse_table_sample_seed(
17167        &mut self,
17168        modifier: TableSampleSeedModifier,
17169    ) -> Result<TableSampleSeed, ParserError> {
17170        self.expect_token(&Token::LParen)?;
17171        let value = self.parse_number_value()?;
17172        self.expect_token(&Token::RParen)?;
17173        Ok(TableSampleSeed { modifier, value })
17174    }
17175
17176    /// Parses `OPENJSON( jsonExpression [ , path ] )  [ <with_clause> ]` clause,
17177    /// assuming the `OPENJSON` keyword was already consumed.
17178    fn parse_open_json_table_factor(&mut self) -> Result<TableFactor, ParserError> {
17179        self.expect_token(&Token::LParen)?;
17180        let json_expr = self.parse_expr()?;
17181        let json_path = if self.consume_token(&Token::Comma) {
17182            Some(self.parse_value()?)
17183        } else {
17184            None
17185        };
17186        self.expect_token(&Token::RParen)?;
17187        let columns = if self.parse_keyword(Keyword::WITH) {
17188            self.expect_token(&Token::LParen)?;
17189            let columns = self.parse_comma_separated(Parser::parse_openjson_table_column_def)?;
17190            self.expect_token(&Token::RParen)?;
17191            columns
17192        } else {
17193            Vec::new()
17194        };
17195        let alias = self.maybe_parse_table_alias()?;
17196        Ok(TableFactor::OpenJsonTable {
17197            json_expr,
17198            json_path,
17199            columns,
17200            alias,
17201        })
17202    }
17203
17204    fn parse_xml_table_factor(&mut self) -> Result<TableFactor, ParserError> {
17205        self.expect_token(&Token::LParen)?;
17206        let namespaces = if self.parse_keyword(Keyword::XMLNAMESPACES) {
17207            self.expect_token(&Token::LParen)?;
17208            let namespaces = self.parse_comma_separated(Parser::parse_xml_namespace_definition)?;
17209            self.expect_token(&Token::RParen)?;
17210            self.expect_token(&Token::Comma)?;
17211            namespaces
17212        } else {
17213            vec![]
17214        };
17215        let row_expression = self.parse_expr()?;
17216        let passing = self.parse_xml_passing_clause()?;
17217        self.expect_keyword_is(Keyword::COLUMNS)?;
17218        let columns = self.parse_comma_separated(Parser::parse_xml_table_column)?;
17219        self.expect_token(&Token::RParen)?;
17220        let alias = self.maybe_parse_table_alias()?;
17221        Ok(TableFactor::XmlTable {
17222            namespaces,
17223            row_expression,
17224            passing,
17225            columns,
17226            alias,
17227        })
17228    }
17229
17230    fn parse_xml_namespace_definition(&mut self) -> Result<XmlNamespaceDefinition, ParserError> {
17231        let uri = self.parse_expr()?;
17232        self.expect_keyword_is(Keyword::AS)?;
17233        let name = self.parse_identifier()?;
17234        Ok(XmlNamespaceDefinition { uri, name })
17235    }
17236
17237    fn parse_xml_table_column(&mut self) -> Result<XmlTableColumn, ParserError> {
17238        let name = self.parse_identifier()?;
17239
17240        let option = if self.parse_keyword(Keyword::FOR) {
17241            self.expect_keyword(Keyword::ORDINALITY)?;
17242            XmlTableColumnOption::ForOrdinality
17243        } else {
17244            let r#type = self.parse_data_type()?;
17245            let mut path = None;
17246            let mut default = None;
17247
17248            if self.parse_keyword(Keyword::PATH) {
17249                path = Some(self.parse_expr()?);
17250            }
17251
17252            if self.parse_keyword(Keyword::DEFAULT) {
17253                default = Some(self.parse_expr()?);
17254            }
17255
17256            let not_null = self.parse_keywords(&[Keyword::NOT, Keyword::NULL]);
17257            if !not_null {
17258                // NULL is the default but can be specified explicitly
17259                let _ = self.parse_keyword(Keyword::NULL);
17260            }
17261
17262            XmlTableColumnOption::NamedInfo {
17263                r#type,
17264                path,
17265                default,
17266                nullable: !not_null,
17267            }
17268        };
17269        Ok(XmlTableColumn { name, option })
17270    }
17271
17272    fn parse_xml_passing_clause(&mut self) -> Result<XmlPassingClause, ParserError> {
17273        let mut arguments = vec![];
17274        if self.parse_keyword(Keyword::PASSING) {
17275            loop {
17276                let by_value =
17277                    self.parse_keyword(Keyword::BY) && self.expect_keyword(Keyword::VALUE).is_ok();
17278                let expr = self.parse_expr()?;
17279                let alias = if self.parse_keyword(Keyword::AS) {
17280                    Some(self.parse_identifier()?)
17281                } else {
17282                    None
17283                };
17284                arguments.push(XmlPassingArgument {
17285                    expr,
17286                    alias,
17287                    by_value,
17288                });
17289                if !self.consume_token(&Token::Comma) {
17290                    break;
17291                }
17292            }
17293        }
17294        Ok(XmlPassingClause { arguments })
17295    }
17296
17297    /// Parse a [TableFactor::SemanticView]
17298    fn parse_semantic_view_table_factor(&mut self) -> Result<TableFactor, ParserError> {
17299        self.expect_keyword(Keyword::SEMANTIC_VIEW)?;
17300        self.expect_token(&Token::LParen)?;
17301
17302        let name = self.parse_object_name(true)?;
17303
17304        // Parse DIMENSIONS, METRICS, FACTS and WHERE clauses in flexible order
17305        let mut dimensions = Vec::new();
17306        let mut metrics = Vec::new();
17307        let mut facts = Vec::new();
17308        let mut where_clause = None;
17309
17310        while self.peek_token_ref().token != Token::RParen {
17311            if self.parse_keyword(Keyword::DIMENSIONS) {
17312                if !dimensions.is_empty() {
17313                    return Err(ParserError::ParserError(
17314                        "DIMENSIONS clause can only be specified once".to_string(),
17315                    ));
17316                }
17317                dimensions = self.parse_comma_separated(Parser::parse_wildcard_expr)?;
17318            } else if self.parse_keyword(Keyword::METRICS) {
17319                if !metrics.is_empty() {
17320                    return Err(ParserError::ParserError(
17321                        "METRICS clause can only be specified once".to_string(),
17322                    ));
17323                }
17324                metrics = self.parse_comma_separated(Parser::parse_wildcard_expr)?;
17325            } else if self.parse_keyword(Keyword::FACTS) {
17326                if !facts.is_empty() {
17327                    return Err(ParserError::ParserError(
17328                        "FACTS clause can only be specified once".to_string(),
17329                    ));
17330                }
17331                facts = self.parse_comma_separated(Parser::parse_wildcard_expr)?;
17332            } else if self.parse_keyword(Keyword::WHERE) {
17333                if where_clause.is_some() {
17334                    return Err(ParserError::ParserError(
17335                        "WHERE clause can only be specified once".to_string(),
17336                    ));
17337                }
17338                where_clause = Some(self.parse_expr()?);
17339            } else {
17340                let tok = self.peek_token_ref();
17341                parser_err!(
17342                    format!(
17343                        "Expected one of DIMENSIONS, METRICS, FACTS or WHERE, got {}",
17344                        tok.token
17345                    ),
17346                    tok.span.start
17347                )?;
17348            }
17349        }
17350
17351        self.expect_token(&Token::RParen)?;
17352
17353        let alias = self.maybe_parse_table_alias()?;
17354
17355        Ok(TableFactor::SemanticView {
17356            name,
17357            dimensions,
17358            metrics,
17359            facts,
17360            where_clause,
17361            alias,
17362        })
17363    }
17364
17365    fn parse_match_recognize(&mut self, table: TableFactor) -> Result<TableFactor, ParserError> {
17366        self.expect_token(&Token::LParen)?;
17367
17368        let partition_by = if self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
17369            self.parse_comma_separated(Parser::parse_expr)?
17370        } else {
17371            vec![]
17372        };
17373
17374        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
17375            self.parse_comma_separated(Parser::parse_order_by_expr)?
17376        } else {
17377            vec![]
17378        };
17379
17380        let measures = if self.parse_keyword(Keyword::MEASURES) {
17381            self.parse_comma_separated(|p| {
17382                let expr = p.parse_expr()?;
17383                let _ = p.parse_keyword(Keyword::AS);
17384                let alias = p.parse_identifier()?;
17385                Ok(Measure { expr, alias })
17386            })?
17387        } else {
17388            vec![]
17389        };
17390
17391        let rows_per_match =
17392            if self.parse_keywords(&[Keyword::ONE, Keyword::ROW, Keyword::PER, Keyword::MATCH]) {
17393                Some(RowsPerMatch::OneRow)
17394            } else if self.parse_keywords(&[
17395                Keyword::ALL,
17396                Keyword::ROWS,
17397                Keyword::PER,
17398                Keyword::MATCH,
17399            ]) {
17400                Some(RowsPerMatch::AllRows(
17401                    if self.parse_keywords(&[Keyword::SHOW, Keyword::EMPTY, Keyword::MATCHES]) {
17402                        Some(EmptyMatchesMode::Show)
17403                    } else if self.parse_keywords(&[
17404                        Keyword::OMIT,
17405                        Keyword::EMPTY,
17406                        Keyword::MATCHES,
17407                    ]) {
17408                        Some(EmptyMatchesMode::Omit)
17409                    } else if self.parse_keywords(&[
17410                        Keyword::WITH,
17411                        Keyword::UNMATCHED,
17412                        Keyword::ROWS,
17413                    ]) {
17414                        Some(EmptyMatchesMode::WithUnmatched)
17415                    } else {
17416                        None
17417                    },
17418                ))
17419            } else {
17420                None
17421            };
17422
17423        let after_match_skip =
17424            if self.parse_keywords(&[Keyword::AFTER, Keyword::MATCH, Keyword::SKIP]) {
17425                if self.parse_keywords(&[Keyword::PAST, Keyword::LAST, Keyword::ROW]) {
17426                    Some(AfterMatchSkip::PastLastRow)
17427                } else if self.parse_keywords(&[Keyword::TO, Keyword::NEXT, Keyword::ROW]) {
17428                    Some(AfterMatchSkip::ToNextRow)
17429                } else if self.parse_keywords(&[Keyword::TO, Keyword::FIRST]) {
17430                    Some(AfterMatchSkip::ToFirst(self.parse_identifier()?))
17431                } else if self.parse_keywords(&[Keyword::TO, Keyword::LAST]) {
17432                    Some(AfterMatchSkip::ToLast(self.parse_identifier()?))
17433                } else {
17434                    let found = self.next_token();
17435                    return self.expected("after match skip option", found);
17436                }
17437            } else {
17438                None
17439            };
17440
17441        self.expect_keyword_is(Keyword::PATTERN)?;
17442        let pattern = self.parse_parenthesized(Self::parse_pattern)?;
17443
17444        self.expect_keyword_is(Keyword::DEFINE)?;
17445
17446        let symbols = self.parse_comma_separated(|p| {
17447            let symbol = p.parse_identifier()?;
17448            p.expect_keyword_is(Keyword::AS)?;
17449            let definition = p.parse_expr()?;
17450            Ok(SymbolDefinition { symbol, definition })
17451        })?;
17452
17453        self.expect_token(&Token::RParen)?;
17454
17455        let alias = self.maybe_parse_table_alias()?;
17456
17457        Ok(TableFactor::MatchRecognize {
17458            table: Box::new(table),
17459            partition_by,
17460            order_by,
17461            measures,
17462            rows_per_match,
17463            after_match_skip,
17464            pattern,
17465            symbols,
17466            alias,
17467        })
17468    }
17469
17470    fn parse_base_pattern(&mut self) -> Result<MatchRecognizePattern, ParserError> {
17471        match self.next_token().token {
17472            Token::Caret => Ok(MatchRecognizePattern::Symbol(MatchRecognizeSymbol::Start)),
17473            Token::Placeholder(s) if s == "$" => {
17474                Ok(MatchRecognizePattern::Symbol(MatchRecognizeSymbol::End))
17475            }
17476            Token::LBrace => {
17477                self.expect_token(&Token::Minus)?;
17478                let symbol = self.parse_identifier().map(MatchRecognizeSymbol::Named)?;
17479                self.expect_token(&Token::Minus)?;
17480                self.expect_token(&Token::RBrace)?;
17481                Ok(MatchRecognizePattern::Exclude(symbol))
17482            }
17483            Token::Word(Word {
17484                value,
17485                quote_style: None,
17486                ..
17487            }) if value == "PERMUTE" => {
17488                self.expect_token(&Token::LParen)?;
17489                let symbols = self.parse_comma_separated(|p| {
17490                    p.parse_identifier().map(MatchRecognizeSymbol::Named)
17491                })?;
17492                self.expect_token(&Token::RParen)?;
17493                Ok(MatchRecognizePattern::Permute(symbols))
17494            }
17495            Token::LParen => {
17496                let pattern = self.parse_pattern()?;
17497                self.expect_token(&Token::RParen)?;
17498                Ok(MatchRecognizePattern::Group(Box::new(pattern)))
17499            }
17500            _ => {
17501                self.prev_token();
17502                self.parse_identifier()
17503                    .map(MatchRecognizeSymbol::Named)
17504                    .map(MatchRecognizePattern::Symbol)
17505            }
17506        }
17507    }
17508
17509    fn parse_repetition_pattern(&mut self) -> Result<MatchRecognizePattern, ParserError> {
17510        let pattern = self.parse_base_pattern()?;
17511        let token = self.next_token();
17512        let quantifier = match token.token {
17513            Token::Mul => RepetitionQuantifier::ZeroOrMore,
17514            Token::Plus => RepetitionQuantifier::OneOrMore,
17515            Token::Placeholder(s) if s == "?" => RepetitionQuantifier::AtMostOne,
17516            Token::LBrace => {
17517                // quantifier is a range like {n} or {n,} or {,m} or {n,m}
17518                let token = self.next_token();
17519                match token.token {
17520                    Token::Comma => {
17521                        let next_token = self.next_token();
17522                        let Token::Number(n, _) = next_token.token else {
17523                            return self.expected("literal number", next_token);
17524                        };
17525                        self.expect_token(&Token::RBrace)?;
17526                        RepetitionQuantifier::AtMost(Self::parse(n, token.span.start)?)
17527                    }
17528                    Token::Number(n, _) if self.consume_token(&Token::Comma) => {
17529                        let next_token = self.next_token();
17530                        match next_token.token {
17531                            Token::Number(m, _) => {
17532                                self.expect_token(&Token::RBrace)?;
17533                                RepetitionQuantifier::Range(
17534                                    Self::parse(n, token.span.start)?,
17535                                    Self::parse(m, token.span.start)?,
17536                                )
17537                            }
17538                            Token::RBrace => {
17539                                RepetitionQuantifier::AtLeast(Self::parse(n, token.span.start)?)
17540                            }
17541                            _ => return self.expected("} or upper bound", next_token),
17542                        }
17543                    }
17544                    Token::Number(n, _) => {
17545                        self.expect_token(&Token::RBrace)?;
17546                        RepetitionQuantifier::Exactly(Self::parse(n, token.span.start)?)
17547                    }
17548                    _ => return self.expected("quantifier range", token),
17549                }
17550            }
17551            _ => {
17552                self.prev_token();
17553                return Ok(pattern);
17554            }
17555        };
17556        let quantifier = if self.consume_token(&Token::Placeholder("?".into())) {
17557            RepetitionQuantifier::Reluctant(Box::new(quantifier))
17558        } else {
17559            quantifier
17560        };
17561        Ok(MatchRecognizePattern::Repetition(
17562            Box::new(pattern),
17563            quantifier,
17564        ))
17565    }
17566
17567    fn parse_concat_pattern(&mut self) -> Result<MatchRecognizePattern, ParserError> {
17568        let mut patterns = vec![self.parse_repetition_pattern()?];
17569        while !matches!(self.peek_token_ref().token, Token::RParen | Token::Pipe) {
17570            patterns.push(self.parse_repetition_pattern()?);
17571        }
17572        match <[MatchRecognizePattern; 1]>::try_from(patterns) {
17573            Ok([pattern]) => Ok(pattern),
17574            Err(patterns) => Ok(MatchRecognizePattern::Concat(patterns)),
17575        }
17576    }
17577
17578    fn parse_pattern(&mut self) -> Result<MatchRecognizePattern, ParserError> {
17579        let pattern = self.parse_concat_pattern()?;
17580        if self.consume_token(&Token::Pipe) {
17581            match self.parse_pattern()? {
17582                // flatten nested alternations
17583                MatchRecognizePattern::Alternation(mut patterns) => {
17584                    patterns.insert(0, pattern);
17585                    Ok(MatchRecognizePattern::Alternation(patterns))
17586                }
17587                next => Ok(MatchRecognizePattern::Alternation(vec![pattern, next])),
17588            }
17589        } else {
17590            Ok(pattern)
17591        }
17592    }
17593
17594    /// Parses a the timestamp version specifier (i.e. query historical data)
17595    pub fn maybe_parse_table_version(&mut self) -> Result<Option<TableVersion>, ParserError> {
17596        if self.dialect.supports_table_versioning() {
17597            if self.parse_keywords(&[Keyword::FOR, Keyword::SYSTEM_TIME, Keyword::AS, Keyword::OF])
17598            {
17599                let expr = self.parse_expr()?;
17600                return Ok(Some(TableVersion::ForSystemTimeAsOf(expr)));
17601            } else if self.peek_keyword(Keyword::CHANGES) {
17602                return self.parse_table_version_changes().map(Some);
17603            } else if self.peek_keyword(Keyword::AT) || self.peek_keyword(Keyword::BEFORE) {
17604                let func_name = self.parse_object_name(true)?;
17605                let func = self.parse_function(func_name)?;
17606                return Ok(Some(TableVersion::Function(func)));
17607            } else if self.parse_keywords(&[Keyword::TIMESTAMP, Keyword::AS, Keyword::OF]) {
17608                let expr = self.parse_expr()?;
17609                return Ok(Some(TableVersion::TimestampAsOf(expr)));
17610            } else if self.parse_keywords(&[Keyword::VERSION, Keyword::AS, Keyword::OF]) {
17611                let expr = Expr::Value(self.parse_number_value()?);
17612                return Ok(Some(TableVersion::VersionAsOf(expr)));
17613            }
17614        }
17615        Ok(None)
17616    }
17617
17618    /// Parses the Snowflake `CHANGES` clause for change tracking queries.
17619    ///
17620    /// Syntax:
17621    /// ```sql
17622    /// CHANGES (INFORMATION => DEFAULT)
17623    ///   AT (TIMESTAMP => <expr>)
17624    ///   [END (TIMESTAMP => <expr>)]
17625    /// ```
17626    ///
17627    /// <https://docs.snowflake.com/en/sql-reference/constructs/changes>
17628    fn parse_table_version_changes(&mut self) -> Result<TableVersion, ParserError> {
17629        let changes_name = self.parse_object_name(true)?;
17630        let changes = self.parse_function(changes_name)?;
17631        let at_name = self.parse_object_name(true)?;
17632        let at = self.parse_function(at_name)?;
17633        let end = if self.peek_keyword(Keyword::END) {
17634            let end_name = self.parse_object_name(true)?;
17635            Some(self.parse_function(end_name)?)
17636        } else {
17637            None
17638        };
17639        Ok(TableVersion::Changes { changes, at, end })
17640    }
17641
17642    /// Parses MySQL's JSON_TABLE column definition.
17643    /// For example: `id INT EXISTS PATH '$' DEFAULT '0' ON EMPTY ERROR ON ERROR`
17644    pub fn parse_json_table_column_def(&mut self) -> Result<JsonTableColumn, ParserError> {
17645        if self.parse_keyword(Keyword::NESTED) {
17646            let _has_path_keyword = self.parse_keyword(Keyword::PATH);
17647            let path = self.parse_value()?;
17648            self.expect_keyword_is(Keyword::COLUMNS)?;
17649            let columns = self.parse_parenthesized(|p| {
17650                p.parse_comma_separated(Self::parse_json_table_column_def)
17651            })?;
17652            return Ok(JsonTableColumn::Nested(JsonTableNestedColumn {
17653                path,
17654                columns,
17655            }));
17656        }
17657        let name = self.parse_identifier()?;
17658        if self.parse_keyword(Keyword::FOR) {
17659            self.expect_keyword_is(Keyword::ORDINALITY)?;
17660            return Ok(JsonTableColumn::ForOrdinality(name));
17661        }
17662        let r#type = self.parse_data_type()?;
17663        let exists = self.parse_keyword(Keyword::EXISTS);
17664        self.expect_keyword_is(Keyword::PATH)?;
17665        let path = self.parse_value()?;
17666        let mut on_empty = None;
17667        let mut on_error = None;
17668        while let Some(error_handling) = self.parse_json_table_column_error_handling()? {
17669            if self.parse_keyword(Keyword::EMPTY) {
17670                on_empty = Some(error_handling);
17671            } else {
17672                self.expect_keyword_is(Keyword::ERROR)?;
17673                on_error = Some(error_handling);
17674            }
17675        }
17676        Ok(JsonTableColumn::Named(JsonTableNamedColumn {
17677            name,
17678            r#type,
17679            path,
17680            exists,
17681            on_empty,
17682            on_error,
17683        }))
17684    }
17685
17686    /// Parses MSSQL's `OPENJSON WITH` column definition.
17687    ///
17688    /// ```sql
17689    /// colName type [ column_path ] [ AS JSON ]
17690    /// ```
17691    ///
17692    /// Reference: <https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16#syntax>
17693    pub fn parse_openjson_table_column_def(&mut self) -> Result<OpenJsonTableColumn, ParserError> {
17694        let name = self.parse_identifier()?;
17695        let r#type = self.parse_data_type()?;
17696        let path = if let Token::SingleQuotedString(path) = self.peek_token().token {
17697            self.next_token();
17698            Some(path)
17699        } else {
17700            None
17701        };
17702        let as_json = self.parse_keyword(Keyword::AS);
17703        if as_json {
17704            self.expect_keyword_is(Keyword::JSON)?;
17705        }
17706        Ok(OpenJsonTableColumn {
17707            name,
17708            r#type,
17709            path,
17710            as_json,
17711        })
17712    }
17713
17714    fn parse_json_table_column_error_handling(
17715        &mut self,
17716    ) -> Result<Option<JsonTableColumnErrorHandling>, ParserError> {
17717        let res = if self.parse_keyword(Keyword::NULL) {
17718            JsonTableColumnErrorHandling::Null
17719        } else if self.parse_keyword(Keyword::ERROR) {
17720            JsonTableColumnErrorHandling::Error
17721        } else if self.parse_keyword(Keyword::DEFAULT) {
17722            JsonTableColumnErrorHandling::Default(self.parse_value()?)
17723        } else {
17724            return Ok(None);
17725        };
17726        self.expect_keyword_is(Keyword::ON)?;
17727        Ok(Some(res))
17728    }
17729
17730    /// Parse a derived table factor (a parenthesized subquery), handling optional LATERAL.
17731    pub fn parse_derived_table_factor(
17732        &mut self,
17733        lateral: IsLateral,
17734    ) -> Result<TableFactor, ParserError> {
17735        let subquery = self.parse_query()?;
17736        self.expect_token(&Token::RParen)?;
17737        let alias = self.maybe_parse_table_alias()?;
17738
17739        // Parse optional SAMPLE clause after alias
17740        let sample = self
17741            .maybe_parse_table_sample()?
17742            .map(TableSampleKind::AfterTableAlias);
17743
17744        Ok(TableFactor::Derived {
17745            lateral: match lateral {
17746                Lateral => true,
17747                NotLateral => false,
17748            },
17749            subquery,
17750            alias,
17751            sample,
17752        })
17753    }
17754
17755    /// Parses an expression with an optional alias
17756    ///
17757    /// Examples:
17758    ///
17759    /// ```sql
17760    /// SUM(price) AS total_price
17761    /// ```
17762    /// ```sql
17763    /// SUM(price)
17764    /// ```
17765    ///
17766    /// Example
17767    /// ```
17768    /// # use sqlparser::parser::{Parser, ParserError};
17769    /// # use sqlparser::dialect::GenericDialect;
17770    /// # fn main() ->Result<(), ParserError> {
17771    /// let sql = r#"SUM("a") as "b""#;
17772    /// let mut parser = Parser::new(&GenericDialect).try_with_sql(sql)?;
17773    /// let expr_with_alias = parser.parse_expr_with_alias()?;
17774    /// assert_eq!(Some("b".to_string()), expr_with_alias.alias.map(|x|x.value));
17775    /// # Ok(())
17776    /// # }
17777    pub fn parse_expr_with_alias(&mut self) -> Result<ExprWithAlias, ParserError> {
17778        let expr = self.parse_expr()?;
17779        let alias = if self.parse_keyword(Keyword::AS) {
17780            Some(self.parse_identifier()?)
17781        } else {
17782            None
17783        };
17784
17785        Ok(ExprWithAlias { expr, alias })
17786    }
17787
17788    /// Parse an expression followed by an optional alias; Unlike
17789    /// [Self::parse_expr_with_alias] the "AS" keyword between the expression
17790    /// and the alias is optional.
17791    fn parse_expr_with_alias_optional_as_keyword(&mut self) -> Result<ExprWithAlias, ParserError> {
17792        let expr = self.parse_expr()?;
17793        let alias = self.parse_identifier_optional_alias()?;
17794        Ok(ExprWithAlias { expr, alias })
17795    }
17796
17797    /// Parses a plain function call with an optional alias for the `PIVOT` clause
17798    fn parse_pivot_aggregate_function(&mut self) -> Result<ExprWithAlias, ParserError> {
17799        let function_name = match self.next_token().token {
17800            Token::Word(w) => Ok(w.value),
17801            _ => self.expected_ref("a function identifier", self.peek_token_ref()),
17802        }?;
17803        let expr = self.parse_function(ObjectName::from(vec![Ident::new(function_name)]))?;
17804        let alias = {
17805            fn validator(explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
17806                // ~ for a PIVOT aggregate function the alias must not be a "FOR"; in any dialect
17807                kw != &Keyword::FOR && parser.dialect.is_select_item_alias(explicit, kw, parser)
17808            }
17809            self.parse_optional_alias_inner(None, validator)?
17810        };
17811        Ok(ExprWithAlias { expr, alias })
17812    }
17813
17814    /// Parse a PIVOT table factor (ClickHouse/Oracle style pivot), returning a TableFactor.
17815    pub fn parse_pivot_table_factor(
17816        &mut self,
17817        table: TableFactor,
17818    ) -> Result<TableFactor, ParserError> {
17819        self.expect_token(&Token::LParen)?;
17820        let aggregate_functions =
17821            self.parse_comma_separated(Self::parse_pivot_aggregate_function)?;
17822        self.expect_keyword_is(Keyword::FOR)?;
17823        let value_column = if self.peek_token_ref().token == Token::LParen {
17824            self.parse_parenthesized_column_list_inner(Mandatory, false, |p| {
17825                p.parse_subexpr(self.dialect.prec_value(Precedence::Between))
17826            })?
17827        } else {
17828            vec![self.parse_subexpr(self.dialect.prec_value(Precedence::Between))?]
17829        };
17830        self.expect_keyword_is(Keyword::IN)?;
17831
17832        self.expect_token(&Token::LParen)?;
17833        let value_source = if self.parse_keyword(Keyword::ANY) {
17834            let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
17835                self.parse_comma_separated(Parser::parse_order_by_expr)?
17836            } else {
17837                vec![]
17838            };
17839            PivotValueSource::Any(order_by)
17840        } else if self.peek_sub_query() {
17841            PivotValueSource::Subquery(self.parse_query()?)
17842        } else {
17843            PivotValueSource::List(
17844                self.parse_comma_separated(Self::parse_expr_with_alias_optional_as_keyword)?,
17845            )
17846        };
17847        self.expect_token(&Token::RParen)?;
17848
17849        let default_on_null =
17850            if self.parse_keywords(&[Keyword::DEFAULT, Keyword::ON, Keyword::NULL]) {
17851                self.expect_token(&Token::LParen)?;
17852                let expr = self.parse_expr()?;
17853                self.expect_token(&Token::RParen)?;
17854                Some(expr)
17855            } else {
17856                None
17857            };
17858
17859        self.expect_token(&Token::RParen)?;
17860        let alias = self.maybe_parse_table_alias()?;
17861        Ok(TableFactor::Pivot {
17862            table: Box::new(table),
17863            aggregate_functions,
17864            value_column,
17865            value_source,
17866            default_on_null,
17867            alias,
17868        })
17869    }
17870
17871    /// Parse an UNPIVOT table factor, returning a TableFactor.
17872    pub fn parse_unpivot_table_factor(
17873        &mut self,
17874        table: TableFactor,
17875    ) -> Result<TableFactor, ParserError> {
17876        let null_inclusion = if self.parse_keyword(Keyword::INCLUDE) {
17877            self.expect_keyword_is(Keyword::NULLS)?;
17878            Some(NullInclusion::IncludeNulls)
17879        } else if self.parse_keyword(Keyword::EXCLUDE) {
17880            self.expect_keyword_is(Keyword::NULLS)?;
17881            Some(NullInclusion::ExcludeNulls)
17882        } else {
17883            None
17884        };
17885        self.expect_token(&Token::LParen)?;
17886        let value = self.parse_expr()?;
17887        self.expect_keyword_is(Keyword::FOR)?;
17888        let name = self.parse_identifier()?;
17889        self.expect_keyword_is(Keyword::IN)?;
17890        let columns = self.parse_parenthesized_column_list_inner(Mandatory, false, |p| {
17891            p.parse_expr_with_alias()
17892        })?;
17893        self.expect_token(&Token::RParen)?;
17894        let alias = self.maybe_parse_table_alias()?;
17895        Ok(TableFactor::Unpivot {
17896            table: Box::new(table),
17897            value,
17898            null_inclusion,
17899            name,
17900            columns,
17901            alias,
17902        })
17903    }
17904
17905    /// Parse an object UNPIVOT table factor in FROM clause.
17906    ///
17907    /// Syntax:
17908    /// `UNPIVOT expression AS value_alias [AT attribute_alias]`
17909    pub fn parse_unpivot_expr_table_factor(&mut self) -> Result<TableFactor, ParserError> {
17910        self.expect_keyword_is(Keyword::UNPIVOT)?;
17911        let expression = self.parse_expr()?;
17912        self.expect_keyword_is(Keyword::AS)?;
17913        let value_alias = self.parse_identifier()?;
17914        let attribute_alias = if self.parse_keyword(Keyword::AT) {
17915            Some(self.parse_identifier()?)
17916        } else {
17917            None
17918        };
17919
17920        Ok(TableFactor::UnpivotExpr {
17921            expression,
17922            value_alias,
17923            attribute_alias,
17924        })
17925    }
17926
17927    /// Parse a JOIN constraint (`NATURAL`, `ON <expr>`, `USING (...)`, or no constraint).
17928    pub fn parse_join_constraint(&mut self, natural: bool) -> Result<JoinConstraint, ParserError> {
17929        if natural {
17930            Ok(JoinConstraint::Natural)
17931        } else if self.parse_keyword(Keyword::ON) {
17932            let constraint = self.parse_expr()?;
17933            Ok(JoinConstraint::On(constraint))
17934        } else if self.parse_keyword(Keyword::USING) {
17935            let columns = self.parse_parenthesized_qualified_column_list(Mandatory, false)?;
17936            Ok(JoinConstraint::Using(columns))
17937        } else {
17938            Ok(JoinConstraint::None)
17939            //self.expected_ref("ON, or USING after JOIN", self.peek_token_ref())
17940        }
17941    }
17942
17943    /// Parse a GRANT statement.
17944    pub fn parse_grant(&mut self) -> Result<Grant, ParserError> {
17945        let (privileges, objects) = self.parse_grant_deny_revoke_privileges_objects()?;
17946
17947        self.expect_keyword_is(Keyword::TO)?;
17948        let grantees = self.parse_grantees()?;
17949
17950        let with_grant_option =
17951            self.parse_keywords(&[Keyword::WITH, Keyword::GRANT, Keyword::OPTION]);
17952
17953        let current_grants =
17954            if self.parse_keywords(&[Keyword::COPY, Keyword::CURRENT, Keyword::GRANTS]) {
17955                Some(CurrentGrantsKind::CopyCurrentGrants)
17956            } else if self.parse_keywords(&[Keyword::REVOKE, Keyword::CURRENT, Keyword::GRANTS]) {
17957                Some(CurrentGrantsKind::RevokeCurrentGrants)
17958            } else {
17959                None
17960            };
17961
17962        let as_grantor = if self.parse_keywords(&[Keyword::AS]) {
17963            Some(self.parse_identifier()?)
17964        } else {
17965            None
17966        };
17967
17968        let granted_by = if self.parse_keywords(&[Keyword::GRANTED, Keyword::BY]) {
17969            Some(self.parse_identifier()?)
17970        } else {
17971            None
17972        };
17973
17974        Ok(Grant {
17975            privileges,
17976            objects,
17977            grantees,
17978            with_grant_option,
17979            as_grantor,
17980            granted_by,
17981            current_grants,
17982        })
17983    }
17984
17985    fn parse_grantees(&mut self) -> Result<Vec<Grantee>, ParserError> {
17986        let mut values = vec![];
17987        let mut grantee_type = GranteesType::None;
17988        loop {
17989            let new_grantee_type = if self.parse_keyword(Keyword::ROLE) {
17990                GranteesType::Role
17991            } else if self.parse_keyword(Keyword::USER) {
17992                GranteesType::User
17993            } else if self.parse_keyword(Keyword::SHARE) {
17994                GranteesType::Share
17995            } else if self.parse_keyword(Keyword::GROUP) {
17996                GranteesType::Group
17997            } else if self.parse_keyword(Keyword::PUBLIC) {
17998                GranteesType::Public
17999            } else if self.parse_keywords(&[Keyword::DATABASE, Keyword::ROLE]) {
18000                GranteesType::DatabaseRole
18001            } else if self.parse_keywords(&[Keyword::APPLICATION, Keyword::ROLE]) {
18002                GranteesType::ApplicationRole
18003            } else if self.parse_keyword(Keyword::APPLICATION) {
18004                GranteesType::Application
18005            } else {
18006                grantee_type.clone() // keep from previous iteraton, if not specified
18007            };
18008
18009            if self
18010                .dialect
18011                .get_reserved_grantees_types()
18012                .contains(&new_grantee_type)
18013            {
18014                self.prev_token();
18015            } else {
18016                grantee_type = new_grantee_type;
18017            }
18018
18019            let grantee = if grantee_type == GranteesType::Public {
18020                Grantee {
18021                    grantee_type: grantee_type.clone(),
18022                    name: None,
18023                }
18024            } else {
18025                let mut name = self.parse_grantee_name()?;
18026                if self.consume_token(&Token::Colon) {
18027                    // Redshift supports namespace prefix for external users and groups:
18028                    // <Namespace>:<GroupName> or <Namespace>:<UserName>
18029                    // https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-access-control-native-idp.html
18030                    let ident = self.parse_identifier()?;
18031                    if let GranteeName::ObjectName(namespace) = name {
18032                        name = GranteeName::ObjectName(ObjectName::from(vec![Ident::new(
18033                            format!("{namespace}:{ident}"),
18034                        )]));
18035                    };
18036                }
18037                Grantee {
18038                    grantee_type: grantee_type.clone(),
18039                    name: Some(name),
18040                }
18041            };
18042
18043            values.push(grantee);
18044
18045            if !self.consume_token(&Token::Comma) {
18046                break;
18047            }
18048        }
18049
18050        Ok(values)
18051    }
18052
18053    /// Parse privileges and optional target objects for GRANT/DENY/REVOKE statements.
18054    pub fn parse_grant_deny_revoke_privileges_objects(
18055        &mut self,
18056    ) -> Result<(Privileges, Option<GrantObjects>), ParserError> {
18057        let privileges = if self.parse_keyword(Keyword::ALL) {
18058            Privileges::All {
18059                with_privileges_keyword: self.parse_keyword(Keyword::PRIVILEGES),
18060            }
18061        } else {
18062            let actions = self.parse_actions_list()?;
18063            Privileges::Actions(actions)
18064        };
18065
18066        let objects = if self.parse_keyword(Keyword::ON) {
18067            if self.parse_keywords(&[Keyword::ALL, Keyword::TABLES, Keyword::IN, Keyword::SCHEMA]) {
18068                Some(GrantObjects::AllTablesInSchema {
18069                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
18070                })
18071            } else if self.parse_keywords(&[
18072                Keyword::ALL,
18073                Keyword::EXTERNAL,
18074                Keyword::TABLES,
18075                Keyword::IN,
18076                Keyword::SCHEMA,
18077            ]) {
18078                Some(GrantObjects::AllExternalTablesInSchema {
18079                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
18080                })
18081            } else if self.parse_keywords(&[
18082                Keyword::ALL,
18083                Keyword::VIEWS,
18084                Keyword::IN,
18085                Keyword::SCHEMA,
18086            ]) {
18087                Some(GrantObjects::AllViewsInSchema {
18088                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
18089                })
18090            } else if self.parse_keywords(&[
18091                Keyword::ALL,
18092                Keyword::MATERIALIZED,
18093                Keyword::VIEWS,
18094                Keyword::IN,
18095                Keyword::SCHEMA,
18096            ]) {
18097                Some(GrantObjects::AllMaterializedViewsInSchema {
18098                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
18099                })
18100            } else if self.parse_keywords(&[
18101                Keyword::ALL,
18102                Keyword::FUNCTIONS,
18103                Keyword::IN,
18104                Keyword::SCHEMA,
18105            ]) {
18106                Some(GrantObjects::AllFunctionsInSchema {
18107                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
18108                })
18109            } else if self.parse_keywords(&[
18110                Keyword::FUTURE,
18111                Keyword::SCHEMAS,
18112                Keyword::IN,
18113                Keyword::DATABASE,
18114            ]) {
18115                Some(GrantObjects::FutureSchemasInDatabase {
18116                    databases: self.parse_comma_separated(|p| p.parse_object_name(false))?,
18117                })
18118            } else if self.parse_keywords(&[
18119                Keyword::FUTURE,
18120                Keyword::TABLES,
18121                Keyword::IN,
18122                Keyword::SCHEMA,
18123            ]) {
18124                Some(GrantObjects::FutureTablesInSchema {
18125                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
18126                })
18127            } else if self.parse_keywords(&[
18128                Keyword::FUTURE,
18129                Keyword::EXTERNAL,
18130                Keyword::TABLES,
18131                Keyword::IN,
18132                Keyword::SCHEMA,
18133            ]) {
18134                Some(GrantObjects::FutureExternalTablesInSchema {
18135                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
18136                })
18137            } else if self.parse_keywords(&[
18138                Keyword::FUTURE,
18139                Keyword::VIEWS,
18140                Keyword::IN,
18141                Keyword::SCHEMA,
18142            ]) {
18143                Some(GrantObjects::FutureViewsInSchema {
18144                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
18145                })
18146            } else if self.parse_keywords(&[
18147                Keyword::FUTURE,
18148                Keyword::MATERIALIZED,
18149                Keyword::VIEWS,
18150                Keyword::IN,
18151                Keyword::SCHEMA,
18152            ]) {
18153                Some(GrantObjects::FutureMaterializedViewsInSchema {
18154                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
18155                })
18156            } else if self.parse_keywords(&[
18157                Keyword::ALL,
18158                Keyword::SEQUENCES,
18159                Keyword::IN,
18160                Keyword::SCHEMA,
18161            ]) {
18162                Some(GrantObjects::AllSequencesInSchema {
18163                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
18164                })
18165            } else if self.parse_keywords(&[
18166                Keyword::FUTURE,
18167                Keyword::SEQUENCES,
18168                Keyword::IN,
18169                Keyword::SCHEMA,
18170            ]) {
18171                Some(GrantObjects::FutureSequencesInSchema {
18172                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
18173                })
18174            } else if self.parse_keywords(&[Keyword::RESOURCE, Keyword::MONITOR]) {
18175                Some(GrantObjects::ResourceMonitors(
18176                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
18177                ))
18178            } else if self.parse_keywords(&[Keyword::COMPUTE, Keyword::POOL]) {
18179                Some(GrantObjects::ComputePools(
18180                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
18181                ))
18182            } else if self.parse_keywords(&[Keyword::FAILOVER, Keyword::GROUP]) {
18183                Some(GrantObjects::FailoverGroup(
18184                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
18185                ))
18186            } else if self.parse_keywords(&[Keyword::REPLICATION, Keyword::GROUP]) {
18187                Some(GrantObjects::ReplicationGroup(
18188                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
18189                ))
18190            } else if self.parse_keywords(&[Keyword::EXTERNAL, Keyword::VOLUME]) {
18191                Some(GrantObjects::ExternalVolumes(
18192                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
18193                ))
18194            } else {
18195                let object_type = self.parse_one_of_keywords(&[
18196                    Keyword::SEQUENCE,
18197                    Keyword::DATABASE,
18198                    Keyword::SCHEMA,
18199                    Keyword::TABLE,
18200                    Keyword::VIEW,
18201                    Keyword::WAREHOUSE,
18202                    Keyword::INTEGRATION,
18203                    Keyword::VIEW,
18204                    Keyword::WAREHOUSE,
18205                    Keyword::INTEGRATION,
18206                    Keyword::USER,
18207                    Keyword::CONNECTION,
18208                    Keyword::PROCEDURE,
18209                    Keyword::FUNCTION,
18210                ]);
18211                let objects =
18212                    self.parse_comma_separated(|p| p.parse_object_name_inner(false, true));
18213                match object_type {
18214                    Some(Keyword::DATABASE) => Some(GrantObjects::Databases(objects?)),
18215                    Some(Keyword::SCHEMA) => Some(GrantObjects::Schemas(objects?)),
18216                    Some(Keyword::SEQUENCE) => Some(GrantObjects::Sequences(objects?)),
18217                    Some(Keyword::WAREHOUSE) => Some(GrantObjects::Warehouses(objects?)),
18218                    Some(Keyword::INTEGRATION) => Some(GrantObjects::Integrations(objects?)),
18219                    Some(Keyword::VIEW) => Some(GrantObjects::Views(objects?)),
18220                    Some(Keyword::USER) => Some(GrantObjects::Users(objects?)),
18221                    Some(Keyword::CONNECTION) => Some(GrantObjects::Connections(objects?)),
18222                    kw @ (Some(Keyword::PROCEDURE) | Some(Keyword::FUNCTION)) => {
18223                        if let Some(name) = objects?.first() {
18224                            self.parse_grant_procedure_or_function(name, &kw)?
18225                        } else {
18226                            self.expected_ref("procedure or function name", self.peek_token_ref())?
18227                        }
18228                    }
18229                    Some(Keyword::TABLE) | None => Some(GrantObjects::Tables(objects?)),
18230                    Some(unexpected_keyword) => return Err(ParserError::ParserError(
18231                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in grant objects"),
18232                    )),
18233                }
18234            }
18235        } else {
18236            None
18237        };
18238
18239        Ok((privileges, objects))
18240    }
18241
18242    fn parse_grant_procedure_or_function(
18243        &mut self,
18244        name: &ObjectName,
18245        kw: &Option<Keyword>,
18246    ) -> Result<Option<GrantObjects>, ParserError> {
18247        let arg_types = if self.consume_token(&Token::LParen) {
18248            let list = self.parse_comma_separated0(Self::parse_data_type, Token::RParen)?;
18249            self.expect_token(&Token::RParen)?;
18250            list
18251        } else {
18252            vec![]
18253        };
18254        match kw {
18255            Some(Keyword::PROCEDURE) => Ok(Some(GrantObjects::Procedure {
18256                name: name.clone(),
18257                arg_types,
18258            })),
18259            Some(Keyword::FUNCTION) => Ok(Some(GrantObjects::Function {
18260                name: name.clone(),
18261                arg_types,
18262            })),
18263            _ => self.expected_ref("procedure or function keywords", self.peek_token_ref())?,
18264        }
18265    }
18266
18267    /// Parse a single grantable permission/action (used within GRANT statements).
18268    pub fn parse_grant_permission(&mut self) -> Result<Action, ParserError> {
18269        fn parse_columns(parser: &mut Parser) -> Result<Option<Vec<Ident>>, ParserError> {
18270            let columns = parser.parse_parenthesized_column_list(Optional, false)?;
18271            if columns.is_empty() {
18272                Ok(None)
18273            } else {
18274                Ok(Some(columns))
18275            }
18276        }
18277
18278        // Multi-word privileges
18279        if self.parse_keywords(&[Keyword::IMPORTED, Keyword::PRIVILEGES]) {
18280            Ok(Action::ImportedPrivileges)
18281        } else if self.parse_keywords(&[Keyword::ADD, Keyword::SEARCH, Keyword::OPTIMIZATION]) {
18282            Ok(Action::AddSearchOptimization)
18283        } else if self.parse_keywords(&[Keyword::ATTACH, Keyword::LISTING]) {
18284            Ok(Action::AttachListing)
18285        } else if self.parse_keywords(&[Keyword::ATTACH, Keyword::POLICY]) {
18286            Ok(Action::AttachPolicy)
18287        } else if self.parse_keywords(&[Keyword::BIND, Keyword::SERVICE, Keyword::ENDPOINT]) {
18288            Ok(Action::BindServiceEndpoint)
18289        } else if self.parse_keywords(&[Keyword::DATABASE, Keyword::ROLE]) {
18290            let role = self.parse_object_name(false)?;
18291            Ok(Action::DatabaseRole { role })
18292        } else if self.parse_keywords(&[Keyword::EVOLVE, Keyword::SCHEMA]) {
18293            Ok(Action::EvolveSchema)
18294        } else if self.parse_keywords(&[Keyword::IMPORT, Keyword::SHARE]) {
18295            Ok(Action::ImportShare)
18296        } else if self.parse_keywords(&[Keyword::MANAGE, Keyword::VERSIONS]) {
18297            Ok(Action::ManageVersions)
18298        } else if self.parse_keywords(&[Keyword::MANAGE, Keyword::RELEASES]) {
18299            Ok(Action::ManageReleases)
18300        } else if self.parse_keywords(&[Keyword::OVERRIDE, Keyword::SHARE, Keyword::RESTRICTIONS]) {
18301            Ok(Action::OverrideShareRestrictions)
18302        } else if self.parse_keywords(&[
18303            Keyword::PURCHASE,
18304            Keyword::DATA,
18305            Keyword::EXCHANGE,
18306            Keyword::LISTING,
18307        ]) {
18308            Ok(Action::PurchaseDataExchangeListing)
18309        } else if self.parse_keywords(&[Keyword::RESOLVE, Keyword::ALL]) {
18310            Ok(Action::ResolveAll)
18311        } else if self.parse_keywords(&[Keyword::READ, Keyword::SESSION]) {
18312            Ok(Action::ReadSession)
18313
18314        // Single-word privileges
18315        } else if self.parse_keyword(Keyword::APPLY) {
18316            let apply_type = self.parse_action_apply_type()?;
18317            Ok(Action::Apply { apply_type })
18318        } else if self.parse_keyword(Keyword::APPLYBUDGET) {
18319            Ok(Action::ApplyBudget)
18320        } else if self.parse_keyword(Keyword::AUDIT) {
18321            Ok(Action::Audit)
18322        } else if self.parse_keyword(Keyword::CONNECT) {
18323            Ok(Action::Connect)
18324        } else if self.parse_keyword(Keyword::CREATE) {
18325            let obj_type = self.maybe_parse_action_create_object_type();
18326            Ok(Action::Create { obj_type })
18327        } else if self.parse_keyword(Keyword::DELETE) {
18328            Ok(Action::Delete)
18329        } else if self.parse_keyword(Keyword::EXEC) {
18330            let obj_type = self.maybe_parse_action_execute_obj_type();
18331            Ok(Action::Exec { obj_type })
18332        } else if self.parse_keyword(Keyword::EXECUTE) {
18333            let obj_type = self.maybe_parse_action_execute_obj_type();
18334            Ok(Action::Execute { obj_type })
18335        } else if self.parse_keyword(Keyword::FAILOVER) {
18336            Ok(Action::Failover)
18337        } else if self.parse_keyword(Keyword::INSERT) {
18338            Ok(Action::Insert {
18339                columns: parse_columns(self)?,
18340            })
18341        } else if self.parse_keyword(Keyword::MANAGE) {
18342            let manage_type = self.parse_action_manage_type()?;
18343            Ok(Action::Manage { manage_type })
18344        } else if self.parse_keyword(Keyword::MODIFY) {
18345            let modify_type = self.parse_action_modify_type();
18346            Ok(Action::Modify { modify_type })
18347        } else if self.parse_keyword(Keyword::MONITOR) {
18348            let monitor_type = self.parse_action_monitor_type();
18349            Ok(Action::Monitor { monitor_type })
18350        } else if self.parse_keyword(Keyword::OPERATE) {
18351            Ok(Action::Operate)
18352        } else if self.parse_keyword(Keyword::REFERENCES) {
18353            Ok(Action::References {
18354                columns: parse_columns(self)?,
18355            })
18356        } else if self.parse_keyword(Keyword::READ) {
18357            Ok(Action::Read)
18358        } else if self.parse_keyword(Keyword::REPLICATE) {
18359            Ok(Action::Replicate)
18360        } else if self.parse_keyword(Keyword::ROLE) {
18361            let role = self.parse_object_name(false)?;
18362            Ok(Action::Role { role })
18363        } else if self.parse_keyword(Keyword::SELECT) {
18364            Ok(Action::Select {
18365                columns: parse_columns(self)?,
18366            })
18367        } else if self.parse_keyword(Keyword::TEMPORARY) {
18368            Ok(Action::Temporary)
18369        } else if self.parse_keyword(Keyword::TRIGGER) {
18370            Ok(Action::Trigger)
18371        } else if self.parse_keyword(Keyword::TRUNCATE) {
18372            Ok(Action::Truncate)
18373        } else if self.parse_keyword(Keyword::UPDATE) {
18374            Ok(Action::Update {
18375                columns: parse_columns(self)?,
18376            })
18377        } else if self.parse_keyword(Keyword::USAGE) {
18378            Ok(Action::Usage)
18379        } else if self.parse_keyword(Keyword::OWNERSHIP) {
18380            Ok(Action::Ownership)
18381        } else if self.parse_keyword(Keyword::DROP) {
18382            Ok(Action::Drop)
18383        } else {
18384            self.expected_ref("a privilege keyword", self.peek_token_ref())?
18385        }
18386    }
18387
18388    fn maybe_parse_action_create_object_type(&mut self) -> Option<ActionCreateObjectType> {
18389        // Multi-word object types
18390        if self.parse_keywords(&[Keyword::APPLICATION, Keyword::PACKAGE]) {
18391            Some(ActionCreateObjectType::ApplicationPackage)
18392        } else if self.parse_keywords(&[Keyword::COMPUTE, Keyword::POOL]) {
18393            Some(ActionCreateObjectType::ComputePool)
18394        } else if self.parse_keywords(&[Keyword::DATA, Keyword::EXCHANGE, Keyword::LISTING]) {
18395            Some(ActionCreateObjectType::DataExchangeListing)
18396        } else if self.parse_keywords(&[Keyword::EXTERNAL, Keyword::VOLUME]) {
18397            Some(ActionCreateObjectType::ExternalVolume)
18398        } else if self.parse_keywords(&[Keyword::FAILOVER, Keyword::GROUP]) {
18399            Some(ActionCreateObjectType::FailoverGroup)
18400        } else if self.parse_keywords(&[Keyword::NETWORK, Keyword::POLICY]) {
18401            Some(ActionCreateObjectType::NetworkPolicy)
18402        } else if self.parse_keywords(&[Keyword::ORGANIZATION, Keyword::LISTING]) {
18403            Some(ActionCreateObjectType::OrganiationListing)
18404        } else if self.parse_keywords(&[Keyword::REPLICATION, Keyword::GROUP]) {
18405            Some(ActionCreateObjectType::ReplicationGroup)
18406        }
18407        // Single-word object types
18408        else if self.parse_keyword(Keyword::ACCOUNT) {
18409            Some(ActionCreateObjectType::Account)
18410        } else if self.parse_keyword(Keyword::APPLICATION) {
18411            Some(ActionCreateObjectType::Application)
18412        } else if self.parse_keyword(Keyword::DATABASE) {
18413            Some(ActionCreateObjectType::Database)
18414        } else if self.parse_keyword(Keyword::INTEGRATION) {
18415            Some(ActionCreateObjectType::Integration)
18416        } else if self.parse_keyword(Keyword::ROLE) {
18417            Some(ActionCreateObjectType::Role)
18418        } else if self.parse_keyword(Keyword::SCHEMA) {
18419            Some(ActionCreateObjectType::Schema)
18420        } else if self.parse_keyword(Keyword::SHARE) {
18421            Some(ActionCreateObjectType::Share)
18422        } else if self.parse_keyword(Keyword::USER) {
18423            Some(ActionCreateObjectType::User)
18424        } else if self.parse_keyword(Keyword::WAREHOUSE) {
18425            Some(ActionCreateObjectType::Warehouse)
18426        } else {
18427            None
18428        }
18429    }
18430
18431    fn parse_action_apply_type(&mut self) -> Result<ActionApplyType, ParserError> {
18432        if self.parse_keywords(&[Keyword::AGGREGATION, Keyword::POLICY]) {
18433            Ok(ActionApplyType::AggregationPolicy)
18434        } else if self.parse_keywords(&[Keyword::AUTHENTICATION, Keyword::POLICY]) {
18435            Ok(ActionApplyType::AuthenticationPolicy)
18436        } else if self.parse_keywords(&[Keyword::JOIN, Keyword::POLICY]) {
18437            Ok(ActionApplyType::JoinPolicy)
18438        } else if self.parse_keywords(&[Keyword::MASKING, Keyword::POLICY]) {
18439            Ok(ActionApplyType::MaskingPolicy)
18440        } else if self.parse_keywords(&[Keyword::PACKAGES, Keyword::POLICY]) {
18441            Ok(ActionApplyType::PackagesPolicy)
18442        } else if self.parse_keywords(&[Keyword::PASSWORD, Keyword::POLICY]) {
18443            Ok(ActionApplyType::PasswordPolicy)
18444        } else if self.parse_keywords(&[Keyword::PROJECTION, Keyword::POLICY]) {
18445            Ok(ActionApplyType::ProjectionPolicy)
18446        } else if self.parse_keywords(&[Keyword::ROW, Keyword::ACCESS, Keyword::POLICY]) {
18447            Ok(ActionApplyType::RowAccessPolicy)
18448        } else if self.parse_keywords(&[Keyword::SESSION, Keyword::POLICY]) {
18449            Ok(ActionApplyType::SessionPolicy)
18450        } else if self.parse_keyword(Keyword::TAG) {
18451            Ok(ActionApplyType::Tag)
18452        } else {
18453            self.expected_ref("GRANT APPLY type", self.peek_token_ref())
18454        }
18455    }
18456
18457    fn maybe_parse_action_execute_obj_type(&mut self) -> Option<ActionExecuteObjectType> {
18458        if self.parse_keywords(&[Keyword::DATA, Keyword::METRIC, Keyword::FUNCTION]) {
18459            Some(ActionExecuteObjectType::DataMetricFunction)
18460        } else if self.parse_keywords(&[Keyword::MANAGED, Keyword::ALERT]) {
18461            Some(ActionExecuteObjectType::ManagedAlert)
18462        } else if self.parse_keywords(&[Keyword::MANAGED, Keyword::TASK]) {
18463            Some(ActionExecuteObjectType::ManagedTask)
18464        } else if self.parse_keyword(Keyword::ALERT) {
18465            Some(ActionExecuteObjectType::Alert)
18466        } else if self.parse_keyword(Keyword::TASK) {
18467            Some(ActionExecuteObjectType::Task)
18468        } else {
18469            None
18470        }
18471    }
18472
18473    fn parse_action_manage_type(&mut self) -> Result<ActionManageType, ParserError> {
18474        if self.parse_keywords(&[Keyword::ACCOUNT, Keyword::SUPPORT, Keyword::CASES]) {
18475            Ok(ActionManageType::AccountSupportCases)
18476        } else if self.parse_keywords(&[Keyword::EVENT, Keyword::SHARING]) {
18477            Ok(ActionManageType::EventSharing)
18478        } else if self.parse_keywords(&[Keyword::LISTING, Keyword::AUTO, Keyword::FULFILLMENT]) {
18479            Ok(ActionManageType::ListingAutoFulfillment)
18480        } else if self.parse_keywords(&[Keyword::ORGANIZATION, Keyword::SUPPORT, Keyword::CASES]) {
18481            Ok(ActionManageType::OrganizationSupportCases)
18482        } else if self.parse_keywords(&[Keyword::USER, Keyword::SUPPORT, Keyword::CASES]) {
18483            Ok(ActionManageType::UserSupportCases)
18484        } else if self.parse_keyword(Keyword::GRANTS) {
18485            Ok(ActionManageType::Grants)
18486        } else if self.parse_keyword(Keyword::WAREHOUSES) {
18487            Ok(ActionManageType::Warehouses)
18488        } else {
18489            self.expected_ref("GRANT MANAGE type", self.peek_token_ref())
18490        }
18491    }
18492
18493    fn parse_action_modify_type(&mut self) -> Option<ActionModifyType> {
18494        if self.parse_keywords(&[Keyword::LOG, Keyword::LEVEL]) {
18495            Some(ActionModifyType::LogLevel)
18496        } else if self.parse_keywords(&[Keyword::TRACE, Keyword::LEVEL]) {
18497            Some(ActionModifyType::TraceLevel)
18498        } else if self.parse_keywords(&[Keyword::SESSION, Keyword::LOG, Keyword::LEVEL]) {
18499            Some(ActionModifyType::SessionLogLevel)
18500        } else if self.parse_keywords(&[Keyword::SESSION, Keyword::TRACE, Keyword::LEVEL]) {
18501            Some(ActionModifyType::SessionTraceLevel)
18502        } else {
18503            None
18504        }
18505    }
18506
18507    fn parse_action_monitor_type(&mut self) -> Option<ActionMonitorType> {
18508        if self.parse_keyword(Keyword::EXECUTION) {
18509            Some(ActionMonitorType::Execution)
18510        } else if self.parse_keyword(Keyword::SECURITY) {
18511            Some(ActionMonitorType::Security)
18512        } else if self.parse_keyword(Keyword::USAGE) {
18513            Some(ActionMonitorType::Usage)
18514        } else {
18515            None
18516        }
18517    }
18518
18519    /// Parse a grantee name, possibly with a host qualifier (user@host).
18520    pub fn parse_grantee_name(&mut self) -> Result<GranteeName, ParserError> {
18521        let mut name = self.parse_object_name(false)?;
18522        if self.dialect.supports_user_host_grantee()
18523            && name.0.len() == 1
18524            && name.0[0].as_ident().is_some()
18525            && self.consume_token(&Token::AtSign)
18526        {
18527            let user = name.0.pop().unwrap().as_ident().unwrap().clone();
18528            let host = self.parse_identifier()?;
18529            Ok(GranteeName::UserHost { user, host })
18530        } else {
18531            Ok(GranteeName::ObjectName(name))
18532        }
18533    }
18534
18535    /// Parse [`Statement::Deny`]
18536    pub fn parse_deny(&mut self) -> Result<Statement, ParserError> {
18537        self.expect_keyword(Keyword::DENY)?;
18538
18539        let (privileges, objects) = self.parse_grant_deny_revoke_privileges_objects()?;
18540        let objects = match objects {
18541            Some(o) => o,
18542            None => {
18543                return parser_err!(
18544                    "DENY statements must specify an object",
18545                    self.peek_token_ref().span.start
18546                )
18547            }
18548        };
18549
18550        self.expect_keyword_is(Keyword::TO)?;
18551        let grantees = self.parse_grantees()?;
18552        let cascade = self.parse_cascade_option();
18553        let granted_by = if self.parse_keywords(&[Keyword::AS]) {
18554            Some(self.parse_identifier()?)
18555        } else {
18556            None
18557        };
18558
18559        Ok(Statement::Deny(DenyStatement {
18560            privileges,
18561            objects,
18562            grantees,
18563            cascade,
18564            granted_by,
18565        }))
18566    }
18567
18568    /// Parse a REVOKE statement
18569    pub fn parse_revoke(&mut self) -> Result<Revoke, ParserError> {
18570        let grant_option_for =
18571            self.parse_keywords(&[Keyword::GRANT, Keyword::OPTION, Keyword::FOR]);
18572
18573        let (privileges, objects) = self.parse_grant_deny_revoke_privileges_objects()?;
18574
18575        self.expect_keyword_is(Keyword::FROM)?;
18576        let grantees = self.parse_grantees()?;
18577
18578        let granted_by = if self.parse_keywords(&[Keyword::GRANTED, Keyword::BY]) {
18579            Some(self.parse_identifier()?)
18580        } else {
18581            None
18582        };
18583
18584        let cascade = self.parse_cascade_option();
18585
18586        Ok(Revoke {
18587            grant_option_for,
18588            privileges,
18589            objects,
18590            grantees,
18591            granted_by,
18592            cascade,
18593        })
18594    }
18595
18596    /// Parse an REPLACE statement
18597    pub fn parse_replace(
18598        &mut self,
18599        replace_token: TokenWithSpan,
18600    ) -> Result<Statement, ParserError> {
18601        if !dialect_of!(self is MySqlDialect | GenericDialect) {
18602            return parser_err!(
18603                "Unsupported statement REPLACE",
18604                self.peek_token_ref().span.start
18605            );
18606        }
18607
18608        let mut insert = self.parse_insert(replace_token)?;
18609        if let Statement::Insert(Insert { replace_into, .. }) = &mut insert {
18610            *replace_into = true;
18611        }
18612
18613        Ok(insert)
18614    }
18615
18616    /// Parse an INSERT statement, returning a `Box`ed SetExpr
18617    ///
18618    /// This is used to reduce the size of the stack frames in debug builds
18619    fn parse_insert_setexpr_boxed(
18620        &mut self,
18621        insert_token: TokenWithSpan,
18622    ) -> Result<Box<SetExpr>, ParserError> {
18623        Ok(Box::new(SetExpr::Insert(self.parse_insert(insert_token)?)))
18624    }
18625
18626    /// Parse an INSERT statement
18627    pub fn parse_insert(&mut self, insert_token: TokenWithSpan) -> Result<Statement, ParserError> {
18628        let optimizer_hints = self.maybe_parse_optimizer_hints()?;
18629        let or = self.parse_conflict_clause();
18630        let priority = if !dialect_of!(self is MySqlDialect | GenericDialect) {
18631            None
18632        } else if self.parse_keyword(Keyword::LOW_PRIORITY) {
18633            Some(MysqlInsertPriority::LowPriority)
18634        } else if self.parse_keyword(Keyword::DELAYED) {
18635            Some(MysqlInsertPriority::Delayed)
18636        } else if self.parse_keyword(Keyword::HIGH_PRIORITY) {
18637            Some(MysqlInsertPriority::HighPriority)
18638        } else {
18639            None
18640        };
18641
18642        let ignore = dialect_of!(self is MySqlDialect | GenericDialect)
18643            && self.parse_keyword(Keyword::IGNORE);
18644
18645        let replace_into = false;
18646
18647        let overwrite = self.parse_keyword(Keyword::OVERWRITE);
18648        let into = self.parse_keyword(Keyword::INTO);
18649
18650        let local = self.parse_keyword(Keyword::LOCAL);
18651
18652        if self.parse_keyword(Keyword::DIRECTORY) {
18653            let path = self.parse_literal_string()?;
18654            let file_format = if self.parse_keywords(&[Keyword::STORED, Keyword::AS]) {
18655                Some(self.parse_file_format()?)
18656            } else {
18657                None
18658            };
18659            let source = self.parse_query()?;
18660            Ok(Statement::Directory {
18661                local,
18662                path,
18663                overwrite,
18664                file_format,
18665                source,
18666            })
18667        } else {
18668            // Hive lets you put table here regardless
18669            let table = self.parse_keyword(Keyword::TABLE);
18670            let table_object = self.parse_table_object()?;
18671
18672            // `BY NAME` is an INSERT clause, not a table alias.
18673            let table_alias = if self.dialect.supports_insert_table_alias()
18674                && !self.peek_keywords(&[Keyword::BY, Keyword::NAME])
18675                && !self.peek_sub_query()
18676                && self
18677                    .peek_one_of_keywords(&[Keyword::DEFAULT, Keyword::VALUES])
18678                    .is_none()
18679            {
18680                if self.parse_keyword(Keyword::AS) {
18681                    Some(TableAliasWithoutColumns {
18682                        explicit: true,
18683                        alias: self.parse_identifier()?,
18684                    })
18685                } else {
18686                    self.maybe_parse(|parser| parser.parse_identifier())?
18687                        .map(|alias| TableAliasWithoutColumns {
18688                            explicit: false,
18689                            alias,
18690                        })
18691                }
18692            } else {
18693                None
18694            };
18695
18696            let is_mysql = dialect_of!(self is MySqlDialect);
18697
18698            let mut by_name = false;
18699            let (columns, partitioned, after_columns, output, source, assignments) = if self
18700                .parse_keywords(&[Keyword::DEFAULT, Keyword::VALUES])
18701            {
18702                (vec![], None, vec![], None, None, vec![])
18703            } else {
18704                let (columns, partitioned, after_columns) = if !self.peek_subquery_start() {
18705                    let columns =
18706                        self.parse_parenthesized_qualified_column_list(Optional, is_mysql)?;
18707
18708                    let partitioned = self.parse_insert_partition()?;
18709                    by_name = self.parse_keywords(&[Keyword::BY, Keyword::NAME]);
18710                    // Hive allows you to specify columns after partitions as well if you want.
18711                    let after_columns = if dialect_of!(self is HiveDialect) {
18712                        self.parse_parenthesized_column_list(Optional, false)?
18713                    } else {
18714                        vec![]
18715                    };
18716                    (columns, partitioned, after_columns)
18717                } else {
18718                    Default::default()
18719                };
18720
18721                let output = self.maybe_parse_output_clause()?;
18722
18723                let (source, assignments) = if self.peek_keyword(Keyword::FORMAT)
18724                    || self.peek_keyword(Keyword::SETTINGS)
18725                {
18726                    (None, vec![])
18727                } else if self.dialect.supports_insert_set() && self.parse_keyword(Keyword::SET) {
18728                    (None, self.parse_comma_separated(Parser::parse_assignment)?)
18729                } else {
18730                    (Some(self.parse_query()?), vec![])
18731                };
18732
18733                (
18734                    columns,
18735                    partitioned,
18736                    after_columns,
18737                    output,
18738                    source,
18739                    assignments,
18740                )
18741            };
18742
18743            let (format_clause, settings) = if self.dialect.supports_insert_format() {
18744                // Settings always comes before `FORMAT` for ClickHouse:
18745                // <https://clickhouse.com/docs/en/sql-reference/statements/insert-into>
18746                let settings = self.parse_settings()?;
18747
18748                let format = if self.parse_keyword(Keyword::FORMAT) {
18749                    Some(self.parse_input_format_clause()?)
18750                } else {
18751                    None
18752                };
18753
18754                (format, settings)
18755            } else {
18756                Default::default()
18757            };
18758
18759            let insert_alias = if dialect_of!(self is MySqlDialect | GenericDialect)
18760                && self.parse_keyword(Keyword::AS)
18761            {
18762                let row_alias = self.parse_object_name(false)?;
18763                let col_aliases = Some(self.parse_parenthesized_column_list(Optional, false)?);
18764                Some(InsertAliases {
18765                    row_alias,
18766                    col_aliases,
18767                })
18768            } else {
18769                None
18770            };
18771
18772            let on = if self.parse_keyword(Keyword::ON) {
18773                if self.parse_keyword(Keyword::CONFLICT) {
18774                    let conflict_target =
18775                        if self.parse_keywords(&[Keyword::ON, Keyword::CONSTRAINT]) {
18776                            Some(ConflictTarget::OnConstraint(self.parse_object_name(false)?))
18777                        } else if self.peek_token_ref().token == Token::LParen {
18778                            let columns =
18779                                self.parse_parenthesized_column_list(IsOptional::Mandatory, false)?;
18780                            let predicate = if self.parse_keyword(Keyword::WHERE) {
18781                                Some(self.parse_expr()?)
18782                            } else {
18783                                None
18784                            };
18785                            Some(ConflictTarget::Columns { columns, predicate })
18786                        } else {
18787                            None
18788                        };
18789
18790                    self.expect_keyword_is(Keyword::DO)?;
18791                    let action = if self.parse_keyword(Keyword::NOTHING) {
18792                        OnConflictAction::DoNothing
18793                    } else {
18794                        self.expect_keyword_is(Keyword::UPDATE)?;
18795                        self.expect_keyword_is(Keyword::SET)?;
18796                        let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
18797                        let selection = if self.parse_keyword(Keyword::WHERE) {
18798                            Some(self.parse_expr()?)
18799                        } else {
18800                            None
18801                        };
18802                        OnConflictAction::DoUpdate(DoUpdate {
18803                            assignments,
18804                            selection,
18805                        })
18806                    };
18807
18808                    Some(OnInsert::OnConflict(OnConflict {
18809                        conflict_target,
18810                        action,
18811                    }))
18812                } else {
18813                    self.expect_keyword_is(Keyword::DUPLICATE)?;
18814                    self.expect_keyword_is(Keyword::KEY)?;
18815                    self.expect_keyword_is(Keyword::UPDATE)?;
18816                    let l = self.parse_comma_separated(Parser::parse_assignment)?;
18817
18818                    Some(OnInsert::DuplicateKeyUpdate(l))
18819                }
18820            } else {
18821                None
18822            };
18823
18824            let returning = if self.parse_keyword(Keyword::RETURNING) {
18825                Some(self.parse_comma_separated(Parser::parse_select_item)?)
18826            } else {
18827                None
18828            };
18829
18830            Ok(Insert {
18831                insert_token: insert_token.into(),
18832                optimizer_hints,
18833                or,
18834                table: table_object,
18835                table_alias,
18836                ignore,
18837                into,
18838                overwrite,
18839                by_name,
18840                partitioned,
18841                columns,
18842                after_columns,
18843                source,
18844                assignments,
18845                has_table_keyword: table,
18846                on,
18847                returning,
18848                output,
18849                replace_into,
18850                priority,
18851                insert_alias,
18852                settings,
18853                format_clause,
18854                multi_table_insert_type: None,
18855                multi_table_into_clauses: vec![],
18856                multi_table_when_clauses: vec![],
18857                multi_table_else_clause: None,
18858            }
18859            .into())
18860        }
18861    }
18862
18863    /// Parses input format clause used for ClickHouse.
18864    ///
18865    /// <https://clickhouse.com/docs/en/interfaces/formats>
18866    pub fn parse_input_format_clause(&mut self) -> Result<InputFormatClause, ParserError> {
18867        let ident = self.parse_identifier()?;
18868        let values = self
18869            .maybe_parse(|p| p.parse_comma_separated(|p| p.parse_expr()))?
18870            .unwrap_or_default();
18871
18872        Ok(InputFormatClause { ident, values })
18873    }
18874
18875    /// Returns true if the immediate tokens look like the
18876    /// beginning of a subquery. `(SELECT ...` or `((SELECT ...` etc.
18877    fn peek_subquery_start(&mut self) -> bool {
18878        // Handle (SELECT, ((SELECT, (((SELECT, etc.
18879        // This makes INSERT consistent with other contexts where nested
18880        // parentheses around subqueries are handled by recursive descent.
18881        let mut i = 0;
18882        loop {
18883            match &self.peek_nth_token_ref(i).token {
18884                Token::LParen => i += 1,
18885                Token::Word(w) if w.keyword == Keyword::SELECT => return i > 0,
18886                _ => return false,
18887            }
18888        }
18889    }
18890
18891    /// Returns true if the immediate tokens look like the
18892    /// beginning of a subquery possibly preceded by CTEs;
18893    /// i.e. `(WITH ...` or `(SELECT ...`.
18894    fn peek_subquery_or_cte_start(&mut self) -> bool {
18895        matches!(
18896            self.peek_tokens_ref(),
18897            [
18898                TokenWithSpan {
18899                    token: Token::LParen,
18900                    ..
18901                },
18902                TokenWithSpan {
18903                    token: Token::Word(Word {
18904                        keyword: Keyword::SELECT | Keyword::WITH,
18905                        ..
18906                    }),
18907                    ..
18908                },
18909            ]
18910        )
18911    }
18912
18913    fn parse_conflict_clause(&mut self) -> Option<SqliteOnConflict> {
18914        if self.parse_keywords(&[Keyword::OR, Keyword::REPLACE]) {
18915            Some(SqliteOnConflict::Replace)
18916        } else if self.parse_keywords(&[Keyword::OR, Keyword::ROLLBACK]) {
18917            Some(SqliteOnConflict::Rollback)
18918        } else if self.parse_keywords(&[Keyword::OR, Keyword::ABORT]) {
18919            Some(SqliteOnConflict::Abort)
18920        } else if self.parse_keywords(&[Keyword::OR, Keyword::FAIL]) {
18921            Some(SqliteOnConflict::Fail)
18922        } else if self.parse_keywords(&[Keyword::OR, Keyword::IGNORE]) {
18923            Some(SqliteOnConflict::Ignore)
18924        } else if self.parse_keyword(Keyword::REPLACE) {
18925            Some(SqliteOnConflict::Replace)
18926        } else {
18927            None
18928        }
18929    }
18930
18931    /// Parse an optional `PARTITION (...)` clause for INSERT statements.
18932    pub fn parse_insert_partition(&mut self) -> Result<Option<Vec<Expr>>, ParserError> {
18933        if self.parse_keyword(Keyword::PARTITION) {
18934            self.expect_token(&Token::LParen)?;
18935            let partition_cols = Some(self.parse_comma_separated(Parser::parse_expr)?);
18936            self.expect_token(&Token::RParen)?;
18937            Ok(partition_cols)
18938        } else {
18939            Ok(None)
18940        }
18941    }
18942
18943    /// Parse optional Hive `INPUTFORMAT ... SERDE ...` clause used by LOAD DATA.
18944    pub fn parse_load_data_table_format(
18945        &mut self,
18946    ) -> Result<Option<HiveLoadDataFormat>, ParserError> {
18947        if self.parse_keyword(Keyword::INPUTFORMAT) {
18948            let input_format = self.parse_expr()?;
18949            self.expect_keyword_is(Keyword::SERDE)?;
18950            let serde = self.parse_expr()?;
18951            Ok(Some(HiveLoadDataFormat {
18952                input_format,
18953                serde,
18954            }))
18955        } else {
18956            Ok(None)
18957        }
18958    }
18959
18960    /// Parse an UPDATE statement, returning a `Box`ed SetExpr
18961    ///
18962    /// This is used to reduce the size of the stack frames in debug builds
18963    fn parse_update_setexpr_boxed(
18964        &mut self,
18965        update_token: TokenWithSpan,
18966    ) -> Result<Box<SetExpr>, ParserError> {
18967        Ok(Box::new(SetExpr::Update(self.parse_update(update_token)?)))
18968    }
18969
18970    /// Parse an `UPDATE` statement and return `Statement::Update`.
18971    pub fn parse_update(&mut self, update_token: TokenWithSpan) -> Result<Statement, ParserError> {
18972        let optimizer_hints = self.maybe_parse_optimizer_hints()?;
18973        let or = self.parse_conflict_clause();
18974        let table = self.parse_table_and_joins()?;
18975        let from_before_set = if self.parse_keyword(Keyword::FROM) {
18976            Some(UpdateTableFromKind::BeforeSet(
18977                self.parse_table_with_joins()?,
18978            ))
18979        } else {
18980            None
18981        };
18982        self.expect_keyword(Keyword::SET)?;
18983        let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
18984
18985        let output = self.maybe_parse_output_clause()?;
18986
18987        let from = if from_before_set.is_none() && self.parse_keyword(Keyword::FROM) {
18988            Some(UpdateTableFromKind::AfterSet(
18989                self.parse_table_with_joins()?,
18990            ))
18991        } else {
18992            from_before_set
18993        };
18994        let selection = if self.parse_keyword(Keyword::WHERE) {
18995            Some(self.parse_expr()?)
18996        } else {
18997            None
18998        };
18999        let returning = if self.parse_keyword(Keyword::RETURNING) {
19000            Some(self.parse_comma_separated(Parser::parse_select_item)?)
19001        } else {
19002            None
19003        };
19004        let order_by = if self.dialect.supports_update_order_by()
19005            && self.parse_keywords(&[Keyword::ORDER, Keyword::BY])
19006        {
19007            self.parse_comma_separated(Parser::parse_order_by_expr)?
19008        } else {
19009            vec![]
19010        };
19011        let limit = if self.parse_keyword(Keyword::LIMIT) {
19012            Some(self.parse_expr()?)
19013        } else {
19014            None
19015        };
19016        Ok(Update {
19017            update_token: update_token.into(),
19018            optimizer_hints,
19019            table,
19020            assignments,
19021            from,
19022            selection,
19023            returning,
19024            output,
19025            or,
19026            order_by,
19027            limit,
19028        }
19029        .into())
19030    }
19031
19032    /// Parse a `var = expr` assignment, used in an UPDATE statement
19033    pub fn parse_assignment(&mut self) -> Result<Assignment, ParserError> {
19034        let target = self.parse_assignment_target()?;
19035        if self.dialect.supports_double_eq_assignment() {
19036            if !self.consume_token(&Token::Eq) && !self.consume_token(&Token::DoubleEq) {
19037                return self.expected("= or == (for assignment)", self.peek_token());
19038            }
19039        } else {
19040            self.expect_token(&Token::Eq)?;
19041        }
19042        let value = self.parse_expr()?;
19043        Ok(Assignment { target, value })
19044    }
19045
19046    /// Parse the left-hand side of an assignment, used in an UPDATE statement
19047    pub fn parse_assignment_target(&mut self) -> Result<AssignmentTarget, ParserError> {
19048        if self.consume_token(&Token::LParen) {
19049            let columns = self.parse_comma_separated(|p| p.parse_object_name(false))?;
19050            self.expect_token(&Token::RParen)?;
19051            Ok(AssignmentTarget::Tuple(columns))
19052        } else {
19053            let column = self.parse_object_name(false)?;
19054            let mut subscripts = Vec::new();
19055            while self.consume_token(&Token::LBracket) {
19056                subscripts.push(self.parse_subscript_inner()?);
19057            }
19058            if subscripts.is_empty() {
19059                Ok(AssignmentTarget::ColumnName(column))
19060            } else {
19061                Ok(AssignmentTarget::Subscript { column, subscripts })
19062            }
19063        }
19064    }
19065
19066    /// Parse a single function argument, handling named and unnamed variants.
19067    pub fn parse_function_args(&mut self) -> Result<FunctionArg, ParserError> {
19068        // Parse the argument expression once, then check for a named-arg
19069        // operator. Parsing it speculatively and re-parsing on the unnamed
19070        // path is O(2^depth) on nested calls like `CAST(CASE (CAST(CASE (…`.
19071        if self.dialect.supports_named_fn_args_with_expr_name() {
19072            let expr = self.parse_wildcard_expr()?;
19073            // A wildcard is never a named-arg name; only the unnamed form applies.
19074            if !matches!(expr, Expr::Wildcard(_) | Expr::QualifiedWildcard(..)) {
19075                if let Some(operator) =
19076                    self.maybe_parse(|p| p.parse_function_named_arg_operator())?
19077                {
19078                    let arg = self.parse_wildcard_expr()?.into();
19079                    return Ok(FunctionArg::ExprNamed {
19080                        name: expr,
19081                        arg,
19082                        operator,
19083                    });
19084                }
19085            }
19086            let arg_expr = self.function_arg_expr_from_wildcard(expr)?;
19087            return Ok(FunctionArg::Unnamed(
19088                self.maybe_parse_aliased_function_arg(arg_expr)?,
19089            ));
19090        }
19091
19092        let arg = self.maybe_parse(|p| {
19093            let name = p.parse_identifier()?;
19094            let operator = p.parse_function_named_arg_operator()?;
19095            let arg = p.parse_wildcard_expr()?.into();
19096            Ok(FunctionArg::Named {
19097                name,
19098                arg,
19099                operator,
19100            })
19101        })?;
19102        if let Some(arg) = arg {
19103            return Ok(arg);
19104        }
19105        let wildcard_expr = self.parse_wildcard_expr()?;
19106        let arg_expr = self.function_arg_expr_from_wildcard(wildcard_expr)?;
19107        Ok(FunctionArg::Unnamed(
19108            self.maybe_parse_aliased_function_arg(arg_expr)?,
19109        ))
19110    }
19111
19112    /// Wrap an already-parsed expression as a function argument, parsing any
19113    /// trailing wildcard options (e.g. Snowflake's `HASH(* EXCLUDE(col))`).
19114    fn function_arg_expr_from_wildcard(
19115        &mut self,
19116        wildcard_expr: Expr,
19117    ) -> Result<FunctionArgExpr, ParserError> {
19118        Ok(match wildcard_expr {
19119            Expr::Wildcard(ref token) if self.dialect.supports_select_wildcard_exclude() => {
19120                // Parse the options the same way SELECT items do.
19121                let opts = self.parse_wildcard_additional_options(token.0.clone())?;
19122                if opts.opt_exclude.is_some()
19123                    || opts.opt_except.is_some()
19124                    || opts.opt_replace.is_some()
19125                    || opts.opt_rename.is_some()
19126                    || opts.opt_ilike.is_some()
19127                {
19128                    FunctionArgExpr::WildcardWithOptions(opts)
19129                } else {
19130                    wildcard_expr.into()
19131                }
19132            }
19133            other => other.into(),
19134        })
19135    }
19136
19137    /// Parse an optional `AS <alias>` on an unnamed function argument
19138    /// (e.g. `XMLFOREST(a AS x)` in PostgreSQL).
19139    fn maybe_parse_aliased_function_arg(
19140        &mut self,
19141        arg_expr: FunctionArgExpr,
19142    ) -> Result<FunctionArgExpr, ParserError> {
19143        Ok(match arg_expr {
19144            FunctionArgExpr::Expr(expr)
19145                if self.dialect.supports_aliased_function_args()
19146                    && self.parse_keyword(Keyword::AS) =>
19147            {
19148                FunctionArgExpr::Expr(Expr::Named {
19149                    expr: expr.into(),
19150                    name: self.parse_identifier()?,
19151                })
19152            }
19153            other => other,
19154        })
19155    }
19156
19157    fn parse_function_named_arg_operator(&mut self) -> Result<FunctionArgOperator, ParserError> {
19158        if self.parse_keyword(Keyword::VALUE) {
19159            return Ok(FunctionArgOperator::Value);
19160        }
19161        let tok = self.next_token();
19162        match tok.token {
19163            Token::RArrow if self.dialect.supports_named_fn_args_with_rarrow_operator() => {
19164                Ok(FunctionArgOperator::RightArrow)
19165            }
19166            Token::Eq if self.dialect.supports_named_fn_args_with_eq_operator() => {
19167                Ok(FunctionArgOperator::Equals)
19168            }
19169            Token::Assignment
19170                if self
19171                    .dialect
19172                    .supports_named_fn_args_with_assignment_operator() =>
19173            {
19174                Ok(FunctionArgOperator::Assignment)
19175            }
19176            Token::Colon if self.dialect.supports_named_fn_args_with_colon_operator() => {
19177                Ok(FunctionArgOperator::Colon)
19178            }
19179            _ => {
19180                self.prev_token();
19181                self.expected("argument operator", tok)
19182            }
19183        }
19184    }
19185
19186    /// Parse an optional, comma-separated list of function arguments (consumes closing paren).
19187    pub fn parse_optional_args(&mut self) -> Result<Vec<FunctionArg>, ParserError> {
19188        if self.consume_token(&Token::RParen) {
19189            Ok(vec![])
19190        } else {
19191            let args = self.parse_comma_separated(Parser::parse_function_args)?;
19192            self.expect_token(&Token::RParen)?;
19193            Ok(args)
19194        }
19195    }
19196
19197    fn parse_table_function_args(&mut self) -> Result<TableFunctionArgs, ParserError> {
19198        if self.consume_token(&Token::RParen) {
19199            return Ok(TableFunctionArgs {
19200                args: vec![],
19201                settings: None,
19202            });
19203        }
19204        let mut args = vec![];
19205        let settings = loop {
19206            if let Some(settings) = self.parse_settings()? {
19207                break Some(settings);
19208            }
19209            args.push(self.parse_function_args()?);
19210            if self.is_parse_comma_separated_end() {
19211                break None;
19212            }
19213        };
19214        self.expect_token(&Token::RParen)?;
19215        Ok(TableFunctionArgs { args, settings })
19216    }
19217
19218    /// Parses a potentially empty list of arguments to a function
19219    /// (including the closing parenthesis).
19220    ///
19221    /// Examples:
19222    /// ```sql
19223    /// FIRST_VALUE(x ORDER BY 1,2,3);
19224    /// FIRST_VALUE(x IGNORE NULL);
19225    /// ```
19226    fn parse_function_argument_list(&mut self) -> Result<FunctionArgumentList, ParserError> {
19227        let mut clauses = vec![];
19228
19229        // Handle clauses that may exist with an empty argument list
19230
19231        if let Some(null_clause) = self.parse_json_null_clause() {
19232            clauses.push(FunctionArgumentClause::JsonNullClause(null_clause));
19233        }
19234
19235        if let Some(json_returning_clause) = self.maybe_parse_json_returning_clause()? {
19236            clauses.push(FunctionArgumentClause::JsonReturningClause(
19237                json_returning_clause,
19238            ));
19239        }
19240
19241        if self.consume_token(&Token::RParen) {
19242            return Ok(FunctionArgumentList {
19243                duplicate_treatment: None,
19244                args: vec![],
19245                clauses,
19246            });
19247        }
19248
19249        let duplicate_treatment = self.parse_duplicate_treatment()?;
19250        let args = self.parse_comma_separated(Parser::parse_function_args)?;
19251
19252        if self.parse_keyword(Keyword::WHERE) {
19253            clauses.push(FunctionArgumentClause::Where(self.parse_expr()?));
19254        }
19255
19256        if self.dialect.supports_window_function_null_treatment_arg() {
19257            if let Some(null_treatment) = self.parse_null_treatment()? {
19258                clauses.push(FunctionArgumentClause::IgnoreOrRespectNulls(null_treatment));
19259            }
19260        }
19261
19262        if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
19263            clauses.push(FunctionArgumentClause::OrderBy(
19264                self.parse_comma_separated(Parser::parse_order_by_expr)?,
19265            ));
19266        }
19267
19268        if self.parse_keyword(Keyword::LIMIT) {
19269            clauses.push(FunctionArgumentClause::Limit(self.parse_expr()?));
19270        }
19271
19272        if dialect_of!(self is GenericDialect | BigQueryDialect)
19273            && self.parse_keyword(Keyword::HAVING)
19274        {
19275            let kind = match self.expect_one_of_keywords(&[Keyword::MIN, Keyword::MAX])? {
19276                Keyword::MIN => HavingBoundKind::Min,
19277                Keyword::MAX => HavingBoundKind::Max,
19278                unexpected_keyword => return Err(ParserError::ParserError(
19279                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in having bound"),
19280                )),
19281            };
19282            clauses.push(FunctionArgumentClause::Having(HavingBound(
19283                kind,
19284                self.parse_expr()?,
19285            )))
19286        }
19287
19288        if dialect_of!(self is GenericDialect | MySqlDialect)
19289            && self.parse_keyword(Keyword::SEPARATOR)
19290        {
19291            clauses.push(FunctionArgumentClause::Separator(self.parse_value()?));
19292        }
19293
19294        if let Some(on_overflow) = self.parse_listagg_on_overflow()? {
19295            clauses.push(FunctionArgumentClause::OnOverflow(on_overflow));
19296        }
19297
19298        if let Some(null_clause) = self.parse_json_null_clause() {
19299            clauses.push(FunctionArgumentClause::JsonNullClause(null_clause));
19300        }
19301
19302        if let Some(json_returning_clause) = self.maybe_parse_json_returning_clause()? {
19303            clauses.push(FunctionArgumentClause::JsonReturningClause(
19304                json_returning_clause,
19305            ));
19306        }
19307
19308        self.expect_token(&Token::RParen)?;
19309        Ok(FunctionArgumentList {
19310            duplicate_treatment,
19311            args,
19312            clauses,
19313        })
19314    }
19315
19316    fn parse_json_null_clause(&mut self) -> Option<JsonNullClause> {
19317        if self.parse_keywords(&[Keyword::ABSENT, Keyword::ON, Keyword::NULL]) {
19318            Some(JsonNullClause::AbsentOnNull)
19319        } else if self.parse_keywords(&[Keyword::NULL, Keyword::ON, Keyword::NULL]) {
19320            Some(JsonNullClause::NullOnNull)
19321        } else {
19322            None
19323        }
19324    }
19325
19326    fn maybe_parse_json_returning_clause(
19327        &mut self,
19328    ) -> Result<Option<JsonReturningClause>, ParserError> {
19329        if self.parse_keyword(Keyword::RETURNING) {
19330            let data_type = self.parse_data_type()?;
19331            Ok(Some(JsonReturningClause { data_type }))
19332        } else {
19333            Ok(None)
19334        }
19335    }
19336
19337    fn parse_duplicate_treatment(&mut self) -> Result<Option<DuplicateTreatment>, ParserError> {
19338        let loc = self.peek_token_ref().span.start;
19339        match (
19340            self.parse_keyword(Keyword::ALL),
19341            self.parse_keyword(Keyword::DISTINCT),
19342        ) {
19343            (true, false) => Ok(Some(DuplicateTreatment::All)),
19344            (false, true) => Ok(Some(DuplicateTreatment::Distinct)),
19345            (false, false) => Ok(None),
19346            (true, true) => parser_err!("Cannot specify both ALL and DISTINCT".to_string(), loc),
19347        }
19348    }
19349
19350    /// Parse a comma-delimited list of projections after SELECT
19351    pub fn parse_select_item(&mut self) -> Result<SelectItem, ParserError> {
19352        let prefix = self
19353            .parse_one_of_keywords(
19354                self.dialect
19355                    .get_reserved_keywords_for_select_item_operator(),
19356            )
19357            .map(|keyword| Ident::new(format!("{keyword:?}")));
19358
19359        match self.parse_wildcard_expr()? {
19360            Expr::QualifiedWildcard(prefix, token) => Ok(SelectItem::QualifiedWildcard(
19361                SelectItemQualifiedWildcardKind::ObjectName(prefix),
19362                self.parse_wildcard_additional_options(token.0)?,
19363            )),
19364            Expr::Wildcard(token) => Ok(SelectItem::Wildcard(
19365                self.parse_wildcard_additional_options(token.0)?,
19366            )),
19367            Expr::Identifier(v) if v.value.to_lowercase() == "from" && v.quote_style.is_none() => {
19368                parser_err!(
19369                    format!("Expected an expression, found: {}", v),
19370                    self.peek_token_ref().span.start
19371                )
19372            }
19373            Expr::BinaryOp {
19374                left,
19375                op: BinaryOperator::Eq,
19376                right,
19377            } if self.dialect.supports_eq_alias_assignment()
19378                && matches!(left.as_ref(), Expr::Identifier(_)) =>
19379            {
19380                if matches!(right.as_ref(), Expr::Identifier(v) if v.value.to_lowercase() == "from" && v.quote_style.is_none())
19381                {
19382                    return parser_err!(
19383                        format!("Expected an expression, found: {right}"),
19384                        self.peek_token_ref().span.start
19385                    );
19386                }
19387                let Expr::Identifier(alias) = *left else {
19388                    return parser_err!(
19389                        "BUG: expected identifier expression as alias",
19390                        self.peek_token_ref().span.start
19391                    );
19392                };
19393                Ok(SelectItem::ExprWithAlias {
19394                    expr: *right,
19395                    alias,
19396                })
19397            }
19398            expr if self.dialect.supports_select_expr_star()
19399                && self.consume_tokens(&[Token::Period, Token::Mul]) =>
19400            {
19401                let wildcard_token = self.get_previous_token().clone();
19402                Ok(SelectItem::QualifiedWildcard(
19403                    SelectItemQualifiedWildcardKind::Expr(expr),
19404                    self.parse_wildcard_additional_options(wildcard_token)?,
19405                ))
19406            }
19407            expr if self.dialect.supports_select_item_multi_column_alias()
19408                && self.peek_keyword(Keyword::AS)
19409                && self.peek_nth_token(1).token == Token::LParen =>
19410            {
19411                self.expect_keyword(Keyword::AS)?;
19412                self.expect_token(&Token::LParen)?;
19413                let aliases = self.parse_comma_separated(|p| p.parse_identifier())?;
19414                self.expect_token(&Token::RParen)?;
19415                Ok(SelectItem::ExprWithAliases {
19416                    expr: maybe_prefixed_expr(expr, prefix),
19417                    aliases,
19418                })
19419            }
19420            expr => self
19421                .maybe_parse_select_item_alias()
19422                .map(|alias| match alias {
19423                    Some(alias) => SelectItem::ExprWithAlias {
19424                        expr: maybe_prefixed_expr(expr, prefix),
19425                        alias,
19426                    },
19427                    None => SelectItem::UnnamedExpr(maybe_prefixed_expr(expr, prefix)),
19428                }),
19429        }
19430    }
19431
19432    /// Parse an [`WildcardAdditionalOptions`] information for wildcard select items.
19433    ///
19434    /// If it is not possible to parse it, will return an option.
19435    pub fn parse_wildcard_additional_options(
19436        &mut self,
19437        wildcard_token: TokenWithSpan,
19438    ) -> Result<WildcardAdditionalOptions, ParserError> {
19439        let opt_ilike = if self.dialect.supports_select_wildcard_ilike() {
19440            self.parse_optional_select_item_ilike()?
19441        } else {
19442            None
19443        };
19444        let opt_exclude = if opt_ilike.is_none() && self.dialect.supports_select_wildcard_exclude()
19445        {
19446            self.parse_optional_select_item_exclude()?
19447        } else {
19448            None
19449        };
19450        let opt_except = if self.dialect.supports_select_wildcard_except() {
19451            self.parse_optional_select_item_except()?
19452        } else {
19453            None
19454        };
19455        let opt_replace = if self.dialect.supports_select_wildcard_replace() {
19456            self.parse_optional_select_item_replace()?
19457        } else {
19458            None
19459        };
19460        let opt_rename = if self.dialect.supports_select_wildcard_rename() {
19461            self.parse_optional_select_item_rename()?
19462        } else {
19463            None
19464        };
19465
19466        let opt_alias = if self.dialect.supports_select_wildcard_with_alias() {
19467            self.maybe_parse_select_item_alias()?
19468        } else {
19469            None
19470        };
19471
19472        Ok(WildcardAdditionalOptions {
19473            wildcard_token: wildcard_token.into(),
19474            opt_ilike,
19475            opt_exclude,
19476            opt_except,
19477            opt_rename,
19478            opt_replace,
19479            opt_alias,
19480        })
19481    }
19482
19483    /// Parse an [`Ilike`](IlikeSelectItem) information for wildcard select items.
19484    ///
19485    /// If it is not possible to parse it, will return an option.
19486    pub fn parse_optional_select_item_ilike(
19487        &mut self,
19488    ) -> Result<Option<IlikeSelectItem>, ParserError> {
19489        let opt_ilike = if self.parse_keyword(Keyword::ILIKE) {
19490            let next_token = self.next_token();
19491            let pattern = match next_token.token {
19492                Token::SingleQuotedString(s) => s,
19493                _ => return self.expected("ilike pattern", next_token),
19494            };
19495            Some(IlikeSelectItem { pattern })
19496        } else {
19497            None
19498        };
19499        Ok(opt_ilike)
19500    }
19501
19502    /// Parse an [`Exclude`](ExcludeSelectItem) information for wildcard select items.
19503    ///
19504    /// If it is not possible to parse it, will return an option.
19505    pub fn parse_optional_select_item_exclude(
19506        &mut self,
19507    ) -> Result<Option<ExcludeSelectItem>, ParserError> {
19508        let opt_exclude = if self.parse_keyword(Keyword::EXCLUDE) {
19509            if self.consume_token(&Token::LParen) {
19510                let columns =
19511                    self.parse_comma_separated(|parser| parser.parse_object_name(false))?;
19512                self.expect_token(&Token::RParen)?;
19513                Some(ExcludeSelectItem::Multiple(columns))
19514            } else {
19515                let column = self.parse_object_name(false)?;
19516                Some(ExcludeSelectItem::Single(column))
19517            }
19518        } else {
19519            None
19520        };
19521
19522        Ok(opt_exclude)
19523    }
19524
19525    /// Parse an [`Except`](ExceptSelectItem) information for wildcard select items.
19526    ///
19527    /// If it is not possible to parse it, will return an option.
19528    pub fn parse_optional_select_item_except(
19529        &mut self,
19530    ) -> Result<Option<ExceptSelectItem>, ParserError> {
19531        let opt_except = if self.parse_keyword(Keyword::EXCEPT) {
19532            if self.peek_token_ref().token == Token::LParen {
19533                let idents = self.parse_parenthesized_column_list(Mandatory, false)?;
19534                match &idents[..] {
19535                    [] => {
19536                        return self.expected_ref(
19537                            "at least one column should be parsed by the expect clause",
19538                            self.peek_token_ref(),
19539                        )?;
19540                    }
19541                    [first, idents @ ..] => Some(ExceptSelectItem {
19542                        first_element: first.clone(),
19543                        additional_elements: idents.to_vec(),
19544                    }),
19545                }
19546            } else {
19547                // Clickhouse allows EXCEPT column_name
19548                let ident = self.parse_identifier()?;
19549                Some(ExceptSelectItem {
19550                    first_element: ident,
19551                    additional_elements: vec![],
19552                })
19553            }
19554        } else {
19555            None
19556        };
19557
19558        Ok(opt_except)
19559    }
19560
19561    /// Parse a [`Rename`](RenameSelectItem) information for wildcard select items.
19562    pub fn parse_optional_select_item_rename(
19563        &mut self,
19564    ) -> Result<Option<RenameSelectItem>, ParserError> {
19565        let opt_rename = if self.parse_keyword(Keyword::RENAME) {
19566            if self.consume_token(&Token::LParen) {
19567                let idents =
19568                    self.parse_comma_separated(|parser| parser.parse_identifier_with_alias())?;
19569                self.expect_token(&Token::RParen)?;
19570                Some(RenameSelectItem::Multiple(idents))
19571            } else {
19572                let ident = self.parse_identifier_with_alias()?;
19573                Some(RenameSelectItem::Single(ident))
19574            }
19575        } else {
19576            None
19577        };
19578
19579        Ok(opt_rename)
19580    }
19581
19582    /// Parse a [`Replace`](ReplaceSelectItem) information for wildcard select items.
19583    pub fn parse_optional_select_item_replace(
19584        &mut self,
19585    ) -> Result<Option<ReplaceSelectItem>, ParserError> {
19586        let opt_replace = if self.parse_keyword(Keyword::REPLACE) {
19587            if self.consume_token(&Token::LParen) {
19588                let items = self.parse_comma_separated(|parser| {
19589                    Ok(Box::new(parser.parse_replace_elements()?))
19590                })?;
19591                self.expect_token(&Token::RParen)?;
19592                Some(ReplaceSelectItem { items })
19593            } else {
19594                let tok = self.next_token();
19595                return self.expected("( after REPLACE but", tok);
19596            }
19597        } else {
19598            None
19599        };
19600
19601        Ok(opt_replace)
19602    }
19603    /// Parse a single element of a `REPLACE (...)` select-item clause.
19604    pub fn parse_replace_elements(&mut self) -> Result<ReplaceSelectElement, ParserError> {
19605        let expr = self.parse_expr()?;
19606        let as_keyword = self.parse_keyword(Keyword::AS);
19607        let ident = self.parse_identifier()?;
19608        Ok(ReplaceSelectElement {
19609            expr,
19610            column_name: ident,
19611            as_keyword,
19612        })
19613    }
19614
19615    /// Parse ASC or DESC, returns an Option with true if ASC, false of DESC or `None` if none of
19616    /// them.
19617    pub fn parse_asc_desc(&mut self) -> Option<bool> {
19618        if self.parse_keyword(Keyword::ASC) {
19619            Some(true)
19620        } else if self.parse_keyword(Keyword::DESC) {
19621            Some(false)
19622        } else {
19623            None
19624        }
19625    }
19626
19627    /// Parse ASC or DESC and map to [OrderBySort].
19628    fn parse_optional_order_by_sort(&mut self) -> Option<OrderBySort> {
19629        match self.parse_asc_desc() {
19630            Some(true) => Some(OrderBySort::Asc),
19631            Some(false) => Some(OrderBySort::Desc),
19632            None => None,
19633        }
19634    }
19635
19636    /// Parse an [OrderByExpr] expression.
19637    pub fn parse_order_by_expr(&mut self) -> Result<OrderByExpr, ParserError> {
19638        self.parse_order_by_expr_inner(false)
19639            .map(|(order_by, _)| order_by)
19640    }
19641
19642    /// Parse an [IndexColumn].
19643    pub fn parse_create_index_expr(&mut self) -> Result<IndexColumn, ParserError> {
19644        self.parse_order_by_expr_inner(true)
19645            .map(|(column, operator_class)| IndexColumn {
19646                column,
19647                operator_class,
19648            })
19649    }
19650
19651    fn parse_order_by_expr_inner(
19652        &mut self,
19653        with_operator_class: bool,
19654    ) -> Result<(OrderByExpr, Option<ObjectName>), ParserError> {
19655        let expr = self.parse_expr()?;
19656
19657        let operator_class: Option<ObjectName> = if with_operator_class {
19658            // We check that if non of the following keywords are present, then we parse an
19659            // identifier as operator class.
19660            if self
19661                .peek_one_of_keywords(&[Keyword::ASC, Keyword::DESC, Keyword::NULLS, Keyword::WITH])
19662                .is_some()
19663            {
19664                None
19665            } else {
19666                self.maybe_parse(|parser| parser.parse_object_name(false))?
19667            }
19668        } else {
19669            None
19670        };
19671
19672        let options = if !with_operator_class
19673            && self.dialect.supports_order_by_using_operator()
19674            && self.parse_keyword(Keyword::USING)
19675        {
19676            let op = self.parse_order_by_using_operator()?;
19677            OrderByOptions {
19678                sort: Some(OrderBySort::Using(op)),
19679                nulls_first: self.parse_null_ordering_modifier(),
19680            }
19681        } else {
19682            self.parse_order_by_options()?
19683        };
19684
19685        let with_fill = if self.dialect.supports_with_fill()
19686            && self.parse_keywords(&[Keyword::WITH, Keyword::FILL])
19687        {
19688            Some(self.parse_with_fill()?)
19689        } else {
19690            None
19691        };
19692
19693        Ok((
19694            OrderByExpr {
19695                expr,
19696                options,
19697                with_fill,
19698            },
19699            operator_class,
19700        ))
19701    }
19702
19703    fn parse_order_by_using_operator(&mut self) -> Result<ObjectName, ParserError> {
19704        if self.parse_keyword(Keyword::OPERATOR) {
19705            self.expect_token(&Token::LParen)?;
19706            let operator_name = self.parse_operator_name()?;
19707            self.expect_token(&Token::RParen)?;
19708            return Ok(operator_name);
19709        }
19710
19711        let token = self.next_token();
19712        Ok(ObjectName::from(vec![Ident::new(token.token.to_string())]))
19713    }
19714
19715    fn parse_null_ordering_modifier(&mut self) -> Option<bool> {
19716        if self.parse_keywords(&[Keyword::NULLS, Keyword::FIRST]) {
19717            Some(true)
19718        } else if self.parse_keywords(&[Keyword::NULLS, Keyword::LAST]) {
19719            Some(false)
19720        } else {
19721            None
19722        }
19723    }
19724
19725    fn parse_order_by_options(&mut self) -> Result<OrderByOptions, ParserError> {
19726        let sort = self.parse_optional_order_by_sort();
19727        let nulls_first = self.parse_null_ordering_modifier();
19728
19729        Ok(OrderByOptions { sort, nulls_first })
19730    }
19731
19732    // Parse a WITH FILL clause (ClickHouse dialect)
19733    // that follow the WITH FILL keywords in a ORDER BY clause
19734    /// Parse a `WITH FILL` clause used in ORDER BY (ClickHouse dialect).
19735    pub fn parse_with_fill(&mut self) -> Result<WithFill, ParserError> {
19736        let from = if self.parse_keyword(Keyword::FROM) {
19737            Some(self.parse_expr()?)
19738        } else {
19739            None
19740        };
19741
19742        let to = if self.parse_keyword(Keyword::TO) {
19743            Some(self.parse_expr()?)
19744        } else {
19745            None
19746        };
19747
19748        let step = if self.parse_keyword(Keyword::STEP) {
19749            Some(self.parse_expr()?)
19750        } else {
19751            None
19752        };
19753
19754        Ok(WithFill { from, to, step })
19755    }
19756
19757    /// Parse a set of comma separated INTERPOLATE expressions (ClickHouse dialect)
19758    /// that follow the INTERPOLATE keyword in an ORDER BY clause with the WITH FILL modifier
19759    pub fn parse_interpolations(&mut self) -> Result<Option<Interpolate>, ParserError> {
19760        if !self.parse_keyword(Keyword::INTERPOLATE) {
19761            return Ok(None);
19762        }
19763
19764        if self.consume_token(&Token::LParen) {
19765            let interpolations =
19766                self.parse_comma_separated0(|p| p.parse_interpolation(), Token::RParen)?;
19767            self.expect_token(&Token::RParen)?;
19768            // INTERPOLATE () and INTERPOLATE ( ... ) variants
19769            return Ok(Some(Interpolate {
19770                exprs: Some(interpolations),
19771            }));
19772        }
19773
19774        // INTERPOLATE
19775        Ok(Some(Interpolate { exprs: None }))
19776    }
19777
19778    /// Parse a INTERPOLATE expression (ClickHouse dialect)
19779    pub fn parse_interpolation(&mut self) -> Result<InterpolateExpr, ParserError> {
19780        let column = self.parse_identifier()?;
19781        let expr = if self.parse_keyword(Keyword::AS) {
19782            Some(self.parse_expr()?)
19783        } else {
19784            None
19785        };
19786        Ok(InterpolateExpr { column, expr })
19787    }
19788
19789    /// Parse a TOP clause, MSSQL equivalent of LIMIT,
19790    /// that follows after `SELECT [DISTINCT]`.
19791    pub fn parse_top(&mut self) -> Result<Top, ParserError> {
19792        let quantity = if self.consume_token(&Token::LParen) {
19793            let quantity = self.parse_expr()?;
19794            self.expect_token(&Token::RParen)?;
19795            Some(TopQuantity::Expr(quantity))
19796        } else {
19797            let next_token = self.next_token();
19798            let quantity = match next_token.token {
19799                Token::Number(s, _) => Self::parse::<u64>(s, next_token.span.start)?,
19800                _ => self.expected("literal int", next_token)?,
19801            };
19802            Some(TopQuantity::Constant(quantity))
19803        };
19804
19805        let percent = self.parse_keyword(Keyword::PERCENT);
19806
19807        let with_ties = self.parse_keywords(&[Keyword::WITH, Keyword::TIES]);
19808
19809        Ok(Top {
19810            with_ties,
19811            percent,
19812            quantity,
19813        })
19814    }
19815
19816    /// Parse a LIMIT clause
19817    pub fn parse_limit(&mut self) -> Result<Option<Expr>, ParserError> {
19818        if self.parse_keyword(Keyword::ALL) {
19819            Ok(None)
19820        } else {
19821            Ok(Some(self.parse_expr()?))
19822        }
19823    }
19824
19825    /// Parse an OFFSET clause
19826    pub fn parse_offset(&mut self) -> Result<Offset, ParserError> {
19827        let value = self.parse_expr()?;
19828        let rows = if self.parse_keyword(Keyword::ROW) {
19829            OffsetRows::Row
19830        } else if self.parse_keyword(Keyword::ROWS) {
19831            OffsetRows::Rows
19832        } else {
19833            OffsetRows::None
19834        };
19835        Ok(Offset { value, rows })
19836    }
19837
19838    /// Parse a FETCH clause
19839    pub fn parse_fetch(&mut self) -> Result<Fetch, ParserError> {
19840        let _ = self.parse_one_of_keywords(&[Keyword::FIRST, Keyword::NEXT]);
19841
19842        let (quantity, percent) = if self
19843            .parse_one_of_keywords(&[Keyword::ROW, Keyword::ROWS])
19844            .is_some()
19845        {
19846            (None, false)
19847        } else {
19848            let quantity = Expr::Value(self.parse_value()?);
19849            let percent = self.parse_keyword(Keyword::PERCENT);
19850            let _ = self.parse_one_of_keywords(&[Keyword::ROW, Keyword::ROWS]);
19851            (Some(quantity), percent)
19852        };
19853
19854        let with_ties = if self.parse_keyword(Keyword::ONLY) {
19855            false
19856        } else {
19857            self.parse_keywords(&[Keyword::WITH, Keyword::TIES])
19858        };
19859
19860        Ok(Fetch {
19861            with_ties,
19862            percent,
19863            quantity,
19864        })
19865    }
19866
19867    /// Parse a row-locking clause.
19868    pub fn parse_lock(&mut self) -> Result<LockClause, ParserError> {
19869        let lock_type = match self.expect_one_of_keywords(&[
19870            Keyword::UPDATE,
19871            Keyword::SHARE,
19872            Keyword::NO,
19873            Keyword::KEY,
19874        ])? {
19875            Keyword::UPDATE => LockType::Update,
19876            Keyword::SHARE => LockType::Share,
19877            Keyword::NO => {
19878                self.expect_keywords(&[Keyword::KEY, Keyword::UPDATE])?;
19879                LockType::NoKeyUpdate
19880            }
19881            Keyword::KEY => {
19882                self.expect_keyword(Keyword::SHARE)?;
19883                LockType::KeyShare
19884            }
19885            unexpected_keyword => {
19886                return Err(ParserError::ParserError(format!(
19887                "Internal parser error: expected a row-lock strength, got {unexpected_keyword:?}"
19888            )))
19889            }
19890        };
19891        let of = if self.parse_keyword(Keyword::OF) {
19892            self.parse_comma_separated(|parser| parser.parse_object_name(false))?
19893        } else {
19894            Vec::new()
19895        };
19896        let nonblock = if self.parse_keyword(Keyword::NOWAIT) {
19897            Some(NonBlock::Nowait)
19898        } else if self.parse_keywords(&[Keyword::SKIP, Keyword::LOCKED]) {
19899            Some(NonBlock::SkipLocked)
19900        } else {
19901            None
19902        };
19903        Ok(LockClause {
19904            lock_type,
19905            of,
19906            nonblock,
19907        })
19908    }
19909
19910    /// Parse a PostgreSQL `LOCK` statement.
19911    pub fn parse_lock_statement(&mut self) -> Result<Lock, ParserError> {
19912        self.expect_keyword(Keyword::LOCK)?;
19913
19914        if self.peek_keyword(Keyword::TABLES) {
19915            return self.expected_ref("TABLE or a table name", self.peek_token_ref());
19916        }
19917
19918        let _ = self.parse_keyword(Keyword::TABLE);
19919        let tables = self.parse_comma_separated(Parser::parse_lock_table_target)?;
19920        let lock_mode = if self.parse_keyword(Keyword::IN) {
19921            let lock_mode = self.parse_lock_table_mode()?;
19922            self.expect_keyword(Keyword::MODE)?;
19923            Some(lock_mode)
19924        } else {
19925            None
19926        };
19927        let nowait = self.parse_keyword(Keyword::NOWAIT);
19928
19929        Ok(Lock {
19930            tables,
19931            lock_mode,
19932            nowait,
19933        })
19934    }
19935
19936    fn parse_lock_table_target(&mut self) -> Result<LockTableTarget, ParserError> {
19937        let only = self.parse_keyword(Keyword::ONLY);
19938        let name = self.parse_object_name(false)?;
19939        let has_asterisk = self.consume_token(&Token::Mul);
19940
19941        Ok(LockTableTarget {
19942            name,
19943            only,
19944            has_asterisk,
19945        })
19946    }
19947
19948    fn parse_lock_table_mode(&mut self) -> Result<LockTableMode, ParserError> {
19949        if self.parse_keywords(&[Keyword::ACCESS, Keyword::SHARE]) {
19950            Ok(LockTableMode::AccessShare)
19951        } else if self.parse_keywords(&[Keyword::ACCESS, Keyword::EXCLUSIVE]) {
19952            Ok(LockTableMode::AccessExclusive)
19953        } else if self.parse_keywords(&[Keyword::ROW, Keyword::SHARE]) {
19954            Ok(LockTableMode::RowShare)
19955        } else if self.parse_keywords(&[Keyword::ROW, Keyword::EXCLUSIVE]) {
19956            Ok(LockTableMode::RowExclusive)
19957        } else if self.parse_keywords(&[Keyword::SHARE, Keyword::UPDATE, Keyword::EXCLUSIVE]) {
19958            Ok(LockTableMode::ShareUpdateExclusive)
19959        } else if self.parse_keywords(&[Keyword::SHARE, Keyword::ROW, Keyword::EXCLUSIVE]) {
19960            Ok(LockTableMode::ShareRowExclusive)
19961        } else if self.parse_keyword(Keyword::SHARE) {
19962            Ok(LockTableMode::Share)
19963        } else if self.parse_keyword(Keyword::EXCLUSIVE) {
19964            Ok(LockTableMode::Exclusive)
19965        } else {
19966            self.expected_ref("a PostgreSQL LOCK TABLE mode", self.peek_token_ref())
19967        }
19968    }
19969
19970    /// Parse a VALUES clause
19971    pub fn parse_values(
19972        &mut self,
19973        allow_empty: bool,
19974        value_keyword: bool,
19975    ) -> Result<Values, ParserError> {
19976        let mut explicit_row = false;
19977
19978        let rows = self.parse_comma_separated(|parser| {
19979            if parser.parse_keyword(Keyword::ROW) {
19980                explicit_row = true;
19981            }
19982            Ok(Parens {
19983                opening_token: parser.expect_token(&Token::LParen)?.into(),
19984                content: if allow_empty && parser.peek_token_ref().token == Token::RParen {
19985                    vec![]
19986                } else {
19987                    parser.parse_comma_separated(Parser::parse_expr)?
19988                },
19989                closing_token: parser.expect_token(&Token::RParen)?.into(),
19990            })
19991        })?;
19992        Ok(Values {
19993            explicit_row,
19994            rows,
19995            value_keyword,
19996        })
19997    }
19998
19999    /// Parse a 'START TRANSACTION' statement
20000    pub fn parse_start_transaction(&mut self) -> Result<Statement, ParserError> {
20001        self.expect_keyword_is(Keyword::TRANSACTION)?;
20002        Ok(Statement::StartTransaction {
20003            modes: self.parse_transaction_modes()?,
20004            begin: false,
20005            transaction: Some(BeginTransactionKind::Transaction),
20006            modifier: None,
20007            statements: vec![],
20008            exception: None,
20009            has_end_keyword: false,
20010        })
20011    }
20012
20013    /// Parse a transaction modifier keyword that can follow a `BEGIN` statement.
20014    pub(crate) fn parse_transaction_modifier(&mut self) -> Option<TransactionModifier> {
20015        if !self.dialect.supports_start_transaction_modifier() {
20016            None
20017        } else if self.parse_keyword(Keyword::DEFERRED) {
20018            Some(TransactionModifier::Deferred)
20019        } else if self.parse_keyword(Keyword::IMMEDIATE) {
20020            Some(TransactionModifier::Immediate)
20021        } else if self.parse_keyword(Keyword::EXCLUSIVE) {
20022            Some(TransactionModifier::Exclusive)
20023        } else if self.parse_keyword(Keyword::TRY) {
20024            Some(TransactionModifier::Try)
20025        } else if self.parse_keyword(Keyword::CATCH) {
20026            Some(TransactionModifier::Catch)
20027        } else {
20028            None
20029        }
20030    }
20031
20032    /// Parse a 'BEGIN' statement
20033    pub fn parse_begin(&mut self) -> Result<Statement, ParserError> {
20034        let modifier = self.parse_transaction_modifier();
20035        let transaction =
20036            match self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK, Keyword::TRAN])
20037            {
20038                Some(Keyword::TRANSACTION) => Some(BeginTransactionKind::Transaction),
20039                Some(Keyword::WORK) => Some(BeginTransactionKind::Work),
20040                Some(Keyword::TRAN) => Some(BeginTransactionKind::Tran),
20041                _ => None,
20042            };
20043        Ok(Statement::StartTransaction {
20044            modes: self.parse_transaction_modes()?,
20045            begin: true,
20046            transaction,
20047            modifier,
20048            statements: vec![],
20049            exception: None,
20050            has_end_keyword: false,
20051        })
20052    }
20053
20054    /// Parse a 'BEGIN ... EXCEPTION ... END' block
20055    pub fn parse_begin_exception_end(&mut self) -> Result<Statement, ParserError> {
20056        let statements = self.parse_statement_list(&[Keyword::EXCEPTION, Keyword::END])?;
20057
20058        let exception = if self.parse_keyword(Keyword::EXCEPTION) {
20059            let mut when = Vec::new();
20060
20061            // We can have multiple `WHEN` arms so we consume all cases until `END`
20062            while !self.peek_keyword(Keyword::END) {
20063                self.expect_keyword(Keyword::WHEN)?;
20064
20065                // Each `WHEN` case can have one or more conditions, e.g.
20066                // WHEN EXCEPTION_1 [OR EXCEPTION_2] THEN
20067                // So we parse identifiers until the `THEN` keyword.
20068                let mut idents = Vec::new();
20069
20070                while !self.parse_keyword(Keyword::THEN) {
20071                    let ident = self.parse_identifier()?;
20072                    idents.push(ident);
20073
20074                    self.maybe_parse(|p| p.expect_keyword(Keyword::OR))?;
20075                }
20076
20077                let statements = self.parse_statement_list(&[Keyword::WHEN, Keyword::END])?;
20078
20079                when.push(ExceptionWhen { idents, statements });
20080            }
20081
20082            Some(when)
20083        } else {
20084            None
20085        };
20086
20087        self.expect_keyword(Keyword::END)?;
20088
20089        Ok(Statement::StartTransaction {
20090            begin: true,
20091            statements,
20092            exception,
20093            has_end_keyword: true,
20094            transaction: None,
20095            modifier: None,
20096            modes: Default::default(),
20097        })
20098    }
20099
20100    /// Parse an 'END' statement
20101    pub fn parse_end(&mut self) -> Result<Statement, ParserError> {
20102        let modifier = if !self.dialect.supports_end_transaction_modifier() {
20103            None
20104        } else if self.parse_keyword(Keyword::TRY) {
20105            Some(TransactionModifier::Try)
20106        } else if self.parse_keyword(Keyword::CATCH) {
20107            Some(TransactionModifier::Catch)
20108        } else {
20109            None
20110        };
20111        Ok(Statement::Commit {
20112            chain: self.parse_commit_rollback_chain()?,
20113            end: true,
20114            modifier,
20115        })
20116    }
20117
20118    /// Parse a list of transaction modes
20119    pub fn parse_transaction_modes(&mut self) -> Result<Vec<TransactionMode>, ParserError> {
20120        let mut modes = vec![];
20121        let mut required = false;
20122        loop {
20123            let mode = if self.parse_keywords(&[Keyword::ISOLATION, Keyword::LEVEL]) {
20124                let iso_level = if self.parse_keywords(&[Keyword::READ, Keyword::UNCOMMITTED]) {
20125                    TransactionIsolationLevel::ReadUncommitted
20126                } else if self.parse_keywords(&[Keyword::READ, Keyword::COMMITTED]) {
20127                    TransactionIsolationLevel::ReadCommitted
20128                } else if self.parse_keywords(&[Keyword::REPEATABLE, Keyword::READ]) {
20129                    TransactionIsolationLevel::RepeatableRead
20130                } else if self.parse_keyword(Keyword::SERIALIZABLE) {
20131                    TransactionIsolationLevel::Serializable
20132                } else if self.parse_keyword(Keyword::SNAPSHOT) {
20133                    TransactionIsolationLevel::Snapshot
20134                } else {
20135                    self.expected_ref("isolation level", self.peek_token_ref())?
20136                };
20137                TransactionMode::IsolationLevel(iso_level)
20138            } else if self.parse_keywords(&[Keyword::READ, Keyword::ONLY]) {
20139                TransactionMode::AccessMode(TransactionAccessMode::ReadOnly)
20140            } else if self.parse_keywords(&[Keyword::READ, Keyword::WRITE]) {
20141                TransactionMode::AccessMode(TransactionAccessMode::ReadWrite)
20142            } else if required {
20143                self.expected_ref("transaction mode", self.peek_token_ref())?
20144            } else {
20145                break;
20146            };
20147            modes.push(mode);
20148            // ANSI requires a comma after each transaction mode, but
20149            // PostgreSQL, for historical reasons, does not. We follow
20150            // PostgreSQL in making the comma optional, since that is strictly
20151            // more general.
20152            required = self.consume_token(&Token::Comma);
20153        }
20154        Ok(modes)
20155    }
20156
20157    /// Parse a 'COMMIT' statement
20158    pub fn parse_commit(&mut self) -> Result<Statement, ParserError> {
20159        Ok(Statement::Commit {
20160            chain: self.parse_commit_rollback_chain()?,
20161            end: false,
20162            modifier: None,
20163        })
20164    }
20165
20166    /// Parse a 'ROLLBACK' statement
20167    pub fn parse_rollback(&mut self) -> Result<Statement, ParserError> {
20168        let chain = self.parse_commit_rollback_chain()?;
20169        let savepoint = self.parse_rollback_savepoint()?;
20170
20171        Ok(Statement::Rollback { chain, savepoint })
20172    }
20173
20174    /// Parse an 'ABORT' statement
20175    ///
20176    /// ```sql
20177    /// ABORT [ TRANSACTION | WORK ] [ AND [ NO ] CHAIN ]
20178    /// ```
20179    pub fn parse_abort(&mut self) -> Result<Statement, ParserError> {
20180        let chain = self.parse_commit_rollback_chain()?;
20181
20182        Ok(Statement::Rollback {
20183            chain,
20184            savepoint: None,
20185        })
20186    }
20187
20188    /// Parse an optional `AND [NO] CHAIN` clause for `COMMIT` and `ROLLBACK` statements
20189    pub fn parse_commit_rollback_chain(&mut self) -> Result<bool, ParserError> {
20190        let _ = self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK, Keyword::TRAN]);
20191        if self.parse_keyword(Keyword::AND) {
20192            let chain = !self.parse_keyword(Keyword::NO);
20193            self.expect_keyword_is(Keyword::CHAIN)?;
20194            Ok(chain)
20195        } else {
20196            Ok(false)
20197        }
20198    }
20199
20200    /// Parse an optional 'TO SAVEPOINT savepoint_name' clause for ROLLBACK statements
20201    pub fn parse_rollback_savepoint(&mut self) -> Result<Option<Ident>, ParserError> {
20202        if self.parse_keyword(Keyword::TO) {
20203            let _ = self.parse_keyword(Keyword::SAVEPOINT);
20204            let savepoint = self.parse_identifier()?;
20205
20206            Ok(Some(savepoint))
20207        } else {
20208            Ok(None)
20209        }
20210    }
20211
20212    /// Parse a 'RAISERROR' statement
20213    pub fn parse_raiserror(&mut self) -> Result<Statement, ParserError> {
20214        self.expect_token(&Token::LParen)?;
20215        let message = Box::new(self.parse_expr()?);
20216        self.expect_token(&Token::Comma)?;
20217        let severity = Box::new(self.parse_expr()?);
20218        self.expect_token(&Token::Comma)?;
20219        let state = Box::new(self.parse_expr()?);
20220        let arguments = if self.consume_token(&Token::Comma) {
20221            self.parse_comma_separated(Parser::parse_expr)?
20222        } else {
20223            vec![]
20224        };
20225        self.expect_token(&Token::RParen)?;
20226        let options = if self.parse_keyword(Keyword::WITH) {
20227            self.parse_comma_separated(Parser::parse_raiserror_option)?
20228        } else {
20229            vec![]
20230        };
20231        Ok(Statement::RaisError {
20232            message,
20233            severity,
20234            state,
20235            arguments,
20236            options,
20237        })
20238    }
20239
20240    /// Parse a single `RAISERROR` option
20241    pub fn parse_raiserror_option(&mut self) -> Result<RaisErrorOption, ParserError> {
20242        match self.expect_one_of_keywords(&[Keyword::LOG, Keyword::NOWAIT, Keyword::SETERROR])? {
20243            Keyword::LOG => Ok(RaisErrorOption::Log),
20244            Keyword::NOWAIT => Ok(RaisErrorOption::NoWait),
20245            Keyword::SETERROR => Ok(RaisErrorOption::SetError),
20246            _ => self.expected_ref(
20247                "LOG, NOWAIT OR SETERROR raiserror option",
20248                self.peek_token_ref(),
20249            ),
20250        }
20251    }
20252
20253    /// Parse a MSSQL `THROW` statement.
20254    ///
20255    /// See [Statement::Throw]
20256    pub fn parse_throw(&mut self) -> Result<ThrowStatement, ParserError> {
20257        self.expect_keyword_is(Keyword::THROW)?;
20258
20259        let error_number = self.maybe_parse(|p| p.parse_expr().map(Box::new))?;
20260        let (message, state) = if error_number.is_some() {
20261            self.expect_token(&Token::Comma)?;
20262            let message = Box::new(self.parse_expr()?);
20263            self.expect_token(&Token::Comma)?;
20264            let state = Box::new(self.parse_expr()?);
20265            (Some(message), Some(state))
20266        } else {
20267            (None, None)
20268        };
20269
20270        Ok(ThrowStatement {
20271            error_number,
20272            message,
20273            state,
20274        })
20275    }
20276
20277    /// Parse a SQL `DEALLOCATE` statement
20278    pub fn parse_deallocate(&mut self) -> Result<Statement, ParserError> {
20279        let prepare = self.parse_keyword(Keyword::PREPARE);
20280        let name = self.parse_identifier()?;
20281        Ok(Statement::Deallocate { name, prepare })
20282    }
20283
20284    /// Parse a SQL `EXECUTE` statement
20285    pub fn parse_execute(&mut self) -> Result<Statement, ParserError> {
20286        let immediate =
20287            self.dialect.supports_execute_immediate() && self.parse_keyword(Keyword::IMMEDIATE);
20288
20289        // When `EXEC` is immediately followed by `(`, the content is a dynamic-SQL
20290        // expression — e.g. `EXEC (@sql)`, `EXEC ('SELECT ...')`, or
20291        // `EXEC ('SELECT ... FROM ' + @tbl + ' WHERE ...')`.
20292        // Skip name parsing; the expression ends up in `parameters` via the
20293        // `has_parentheses` path below, consistent with `EXECUTE IMMEDIATE <expr>`.
20294        let name = if immediate || matches!(self.peek_token_ref().token, Token::LParen) {
20295            None
20296        } else {
20297            Some(self.parse_object_name(false)?)
20298        };
20299
20300        let has_parentheses = self.consume_token(&Token::LParen);
20301
20302        let end_kws = &[Keyword::USING, Keyword::OUTPUT, Keyword::DEFAULT];
20303        let end_token = match (has_parentheses, self.peek_token().token) {
20304            (true, _) => Token::RParen,
20305            (false, Token::EOF) => Token::EOF,
20306            (false, Token::Word(w)) if end_kws.contains(&w.keyword) => Token::Word(w),
20307            (false, _) => Token::SemiColon,
20308        };
20309
20310        let parameters = self.parse_comma_separated0(Parser::parse_expr, end_token)?;
20311
20312        if has_parentheses {
20313            self.expect_token(&Token::RParen)?;
20314        }
20315
20316        let into = if self.parse_keyword(Keyword::INTO) {
20317            self.parse_comma_separated(Self::parse_identifier)?
20318        } else {
20319            vec![]
20320        };
20321
20322        let using = if self.parse_keyword(Keyword::USING) {
20323            self.parse_comma_separated(Self::parse_expr_with_alias)?
20324        } else {
20325            vec![]
20326        };
20327
20328        let output = self.parse_keyword(Keyword::OUTPUT);
20329
20330        let default = self.parse_keyword(Keyword::DEFAULT);
20331
20332        Ok(Statement::Execute {
20333            immediate,
20334            name,
20335            parameters,
20336            has_parentheses,
20337            into,
20338            using,
20339            output,
20340            default,
20341        })
20342    }
20343
20344    /// Parse a SQL `PREPARE` statement
20345    pub fn parse_prepare(&mut self) -> Result<Statement, ParserError> {
20346        let name = self.parse_identifier()?;
20347
20348        let mut data_types = vec![];
20349        if self.consume_token(&Token::LParen) {
20350            data_types = self.parse_comma_separated(Parser::parse_data_type)?;
20351            self.expect_token(&Token::RParen)?;
20352        }
20353
20354        self.expect_keyword_is(Keyword::AS)?;
20355        let statement = Box::new(self.parse_statement()?);
20356        Ok(Statement::Prepare {
20357            name,
20358            data_types,
20359            statement,
20360        })
20361    }
20362
20363    /// Parse a SQL `UNLOAD` statement
20364    pub fn parse_unload(&mut self) -> Result<Statement, ParserError> {
20365        self.expect_keyword(Keyword::UNLOAD)?;
20366        self.expect_token(&Token::LParen)?;
20367        let (query, query_text) =
20368            if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
20369                (None, Some(self.parse_literal_string()?))
20370            } else {
20371                (Some(self.parse_query()?), None)
20372            };
20373        self.expect_token(&Token::RParen)?;
20374
20375        self.expect_keyword_is(Keyword::TO)?;
20376        let to = self.parse_identifier()?;
20377        let auth = if self.parse_keyword(Keyword::IAM_ROLE) {
20378            Some(self.parse_iam_role_kind()?)
20379        } else {
20380            None
20381        };
20382        let with = self.parse_options(Keyword::WITH)?;
20383        let mut options = vec![];
20384        while let Some(opt) = self.maybe_parse(|parser| parser.parse_copy_legacy_option())? {
20385            options.push(opt);
20386        }
20387        Ok(Statement::Unload {
20388            query,
20389            query_text,
20390            to,
20391            auth,
20392            with,
20393            options,
20394        })
20395    }
20396
20397    fn parse_select_into(&mut self) -> Result<SelectInto, ParserError> {
20398        let temporary = self
20399            .parse_one_of_keywords(&[Keyword::TEMP, Keyword::TEMPORARY])
20400            .is_some();
20401        let unlogged = self.parse_keyword(Keyword::UNLOGGED);
20402        let table = self.parse_keyword(Keyword::TABLE);
20403        let targets = self.parse_comma_separated(Parser::parse_expr)?;
20404
20405        Ok(SelectInto {
20406            temporary,
20407            unlogged,
20408            table,
20409            targets,
20410        })
20411    }
20412
20413    fn parse_pragma_value(&mut self) -> Result<ValueWithSpan, ParserError> {
20414        let v = self.parse_value()?;
20415        match &v.value {
20416            Value::SingleQuotedString(_) => Ok(v),
20417            Value::DoubleQuotedString(_) => Ok(v),
20418            Value::Number(_, _) => Ok(v),
20419            Value::Placeholder(_) => Ok(v),
20420            _ => {
20421                self.prev_token();
20422                self.expected_ref("number or string or ? placeholder", self.peek_token_ref())
20423            }
20424        }
20425    }
20426
20427    /// PRAGMA [schema-name '.'] pragma-name [('=' pragma-value) | '(' pragma-value ')']
20428    pub fn parse_pragma(&mut self) -> Result<Statement, ParserError> {
20429        let name = self.parse_object_name(false)?;
20430        if self.consume_token(&Token::LParen) {
20431            let value = self.parse_pragma_value()?;
20432            self.expect_token(&Token::RParen)?;
20433            Ok(Statement::Pragma {
20434                name,
20435                value: Some(value),
20436                is_eq: false,
20437            })
20438        } else if self.consume_token(&Token::Eq) {
20439            Ok(Statement::Pragma {
20440                name,
20441                value: Some(self.parse_pragma_value()?),
20442                is_eq: true,
20443            })
20444        } else {
20445            Ok(Statement::Pragma {
20446                name,
20447                value: None,
20448                is_eq: false,
20449            })
20450        }
20451    }
20452
20453    /// `INSTALL [extension_name]`
20454    pub fn parse_install(&mut self) -> Result<Statement, ParserError> {
20455        let extension_name = self.parse_identifier()?;
20456
20457        Ok(Statement::Install { extension_name })
20458    }
20459
20460    /// Parse a SQL LOAD statement
20461    pub fn parse_load(&mut self) -> Result<Statement, ParserError> {
20462        if self.dialect.supports_load_extension() {
20463            let extension_name = self.parse_identifier()?;
20464            Ok(Statement::Load { extension_name })
20465        } else if self.parse_keyword(Keyword::DATA) && self.dialect.supports_load_data() {
20466            let local = self.parse_one_of_keywords(&[Keyword::LOCAL]).is_some();
20467            self.expect_keyword_is(Keyword::INPATH)?;
20468            let inpath = self.parse_literal_string()?;
20469            let overwrite = self.parse_one_of_keywords(&[Keyword::OVERWRITE]).is_some();
20470            self.expect_keyword_is(Keyword::INTO)?;
20471            self.expect_keyword_is(Keyword::TABLE)?;
20472            let table_name = self.parse_object_name(false)?;
20473            let partitioned = self.parse_insert_partition()?;
20474            let table_format = self.parse_load_data_table_format()?;
20475            Ok(Statement::LoadData {
20476                local,
20477                inpath,
20478                overwrite,
20479                table_name,
20480                partitioned,
20481                table_format,
20482            })
20483        } else {
20484            self.expected_ref(
20485                "`DATA` or an extension name after `LOAD`",
20486                self.peek_token_ref(),
20487            )
20488        }
20489    }
20490
20491    /// ClickHouse:
20492    /// ```sql
20493    /// OPTIMIZE TABLE [db.]name [ON CLUSTER cluster] [PARTITION partition | PARTITION ID 'partition_id'] [FINAL] [DEDUPLICATE [BY expression]]
20494    /// ```
20495    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/optimize)
20496    ///
20497    /// Databricks:
20498    /// ```sql
20499    /// OPTIMIZE table_name [WHERE predicate] [ZORDER BY (col_name1 [, ...])]
20500    /// ```
20501    /// [Databricks](https://docs.databricks.com/en/sql/language-manual/delta-optimize.html)
20502    pub fn parse_optimize_table(&mut self) -> Result<Statement, ParserError> {
20503        let has_table_keyword = self.parse_keyword(Keyword::TABLE);
20504
20505        let name = self.parse_object_name(false)?;
20506
20507        // ClickHouse-specific options
20508        let on_cluster = self.parse_optional_on_cluster()?;
20509
20510        let partition = if self.parse_keyword(Keyword::PARTITION) {
20511            if self.parse_keyword(Keyword::ID) {
20512                Some(Partition::Identifier(self.parse_identifier()?))
20513            } else {
20514                Some(Partition::Expr(self.parse_expr()?))
20515            }
20516        } else {
20517            None
20518        };
20519
20520        let include_final = self.parse_keyword(Keyword::FINAL);
20521
20522        let deduplicate = if self.parse_keyword(Keyword::DEDUPLICATE) {
20523            if self.parse_keyword(Keyword::BY) {
20524                Some(Deduplicate::ByExpression(self.parse_expr()?))
20525            } else {
20526                Some(Deduplicate::All)
20527            }
20528        } else {
20529            None
20530        };
20531
20532        // Databricks-specific options
20533        let predicate = if self.parse_keyword(Keyword::WHERE) {
20534            Some(self.parse_expr()?)
20535        } else {
20536            None
20537        };
20538
20539        let zorder = if self.parse_keywords(&[Keyword::ZORDER, Keyword::BY]) {
20540            self.expect_token(&Token::LParen)?;
20541            let columns = self.parse_comma_separated(|p| p.parse_expr())?;
20542            self.expect_token(&Token::RParen)?;
20543            Some(columns)
20544        } else {
20545            None
20546        };
20547
20548        Ok(Statement::OptimizeTable {
20549            name,
20550            has_table_keyword,
20551            on_cluster,
20552            partition,
20553            include_final,
20554            deduplicate,
20555            predicate,
20556            zorder,
20557        })
20558    }
20559
20560    /// ```sql
20561    /// CREATE [ { TEMPORARY | TEMP } ] SEQUENCE [ IF NOT EXISTS ] <sequence_name>
20562    /// ```
20563    ///
20564    /// See [Postgres docs](https://www.postgresql.org/docs/current/sql-createsequence.html) for more details.
20565    pub fn parse_create_sequence(&mut self, temporary: bool) -> Result<Statement, ParserError> {
20566        //[ IF NOT EXISTS ]
20567        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
20568        //name
20569        let name = self.parse_object_name(false)?;
20570        //[ AS data_type ]
20571        let mut data_type: Option<DataType> = None;
20572        if self.parse_keywords(&[Keyword::AS]) {
20573            data_type = Some(self.parse_data_type()?)
20574        }
20575        let sequence_options = self.parse_create_sequence_options()?;
20576        // [ OWNED BY { table_name.column_name | NONE } ]
20577        let owned_by = if self.parse_keywords(&[Keyword::OWNED, Keyword::BY]) {
20578            if self.parse_keywords(&[Keyword::NONE]) {
20579                Some(ObjectName::from(vec![Ident::new("NONE")]))
20580            } else {
20581                Some(self.parse_object_name(false)?)
20582            }
20583        } else {
20584            None
20585        };
20586        Ok(Statement::CreateSequence {
20587            temporary,
20588            if_not_exists,
20589            name,
20590            data_type,
20591            sequence_options,
20592            owned_by,
20593        })
20594    }
20595
20596    fn parse_create_sequence_options(&mut self) -> Result<Vec<SequenceOptions>, ParserError> {
20597        let mut sequence_options = vec![];
20598        //[ INCREMENT [ BY ] increment ]
20599        if self.parse_keywords(&[Keyword::INCREMENT]) {
20600            if self.parse_keywords(&[Keyword::BY]) {
20601                sequence_options.push(SequenceOptions::IncrementBy(self.parse_number()?, true));
20602            } else {
20603                sequence_options.push(SequenceOptions::IncrementBy(self.parse_number()?, false));
20604            }
20605        }
20606        //[ MINVALUE minvalue | NO MINVALUE ]
20607        if self.parse_keyword(Keyword::MINVALUE) {
20608            sequence_options.push(SequenceOptions::MinValue(Some(self.parse_number()?)));
20609        } else if self.parse_keywords(&[Keyword::NO, Keyword::MINVALUE]) {
20610            sequence_options.push(SequenceOptions::MinValue(None));
20611        }
20612        //[ MAXVALUE maxvalue | NO MAXVALUE ]
20613        if self.parse_keywords(&[Keyword::MAXVALUE]) {
20614            sequence_options.push(SequenceOptions::MaxValue(Some(self.parse_number()?)));
20615        } else if self.parse_keywords(&[Keyword::NO, Keyword::MAXVALUE]) {
20616            sequence_options.push(SequenceOptions::MaxValue(None));
20617        }
20618
20619        //[ START [ WITH ] start ]
20620        if self.parse_keywords(&[Keyword::START]) {
20621            if self.parse_keywords(&[Keyword::WITH]) {
20622                sequence_options.push(SequenceOptions::StartWith(self.parse_number()?, true));
20623            } else {
20624                sequence_options.push(SequenceOptions::StartWith(self.parse_number()?, false));
20625            }
20626        }
20627        //[ CACHE cache ]
20628        if self.parse_keywords(&[Keyword::CACHE]) {
20629            sequence_options.push(SequenceOptions::Cache(self.parse_number()?));
20630        }
20631        // [ [ NO ] CYCLE ]
20632        if self.parse_keywords(&[Keyword::NO, Keyword::CYCLE]) {
20633            sequence_options.push(SequenceOptions::Cycle(true));
20634        } else if self.parse_keywords(&[Keyword::CYCLE]) {
20635            sequence_options.push(SequenceOptions::Cycle(false));
20636        }
20637
20638        Ok(sequence_options)
20639    }
20640
20641    ///   Parse a `CREATE SERVER` statement.
20642    ///
20643    ///  See [Statement::CreateServer]
20644    pub fn parse_pg_create_server(&mut self) -> Result<Statement, ParserError> {
20645        let ine = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
20646        let name = self.parse_object_name(false)?;
20647
20648        let server_type = if self.parse_keyword(Keyword::TYPE) {
20649            Some(self.parse_identifier()?)
20650        } else {
20651            None
20652        };
20653
20654        let version = if self.parse_keyword(Keyword::VERSION) {
20655            Some(self.parse_identifier()?)
20656        } else {
20657            None
20658        };
20659
20660        self.expect_keywords(&[Keyword::FOREIGN, Keyword::DATA, Keyword::WRAPPER])?;
20661        let foreign_data_wrapper = self.parse_object_name(false)?;
20662
20663        let options = self.parse_pg_options_clause()?;
20664
20665        Ok(Statement::CreateServer(CreateServerStatement {
20666            name,
20667            if_not_exists: ine,
20668            server_type,
20669            version,
20670            foreign_data_wrapper,
20671            options,
20672        }))
20673    }
20674
20675    /// Parse an optional Postgres `OPTIONS ( key value [, ...] )` clause.
20676    fn parse_pg_options_clause(&mut self) -> Result<Option<Vec<CreateServerOption>>, ParserError> {
20677        if !self.parse_keyword(Keyword::OPTIONS) {
20678            return Ok(None);
20679        }
20680        self.expect_token(&Token::LParen)?;
20681        let options = self.parse_comma_separated(|p| {
20682            let key = p.parse_identifier()?;
20683            let value = p.parse_identifier()?;
20684            Ok(CreateServerOption { key, value })
20685        })?;
20686        self.expect_token(&Token::RParen)?;
20687        Ok(Some(options))
20688    }
20689
20690    /// Parse a `CREATE FOREIGN TABLE` statement.
20691    ///
20692    /// Per-column `OPTIONS ( ... )`, `INHERITS`, and the `PARTITION OF` form are
20693    /// not parsed yet.
20694    ///
20695    /// See <https://www.postgresql.org/docs/current/sql-createforeigntable.html>
20696    pub fn parse_create_foreign_table(&mut self) -> Result<CreateForeignTable, ParserError> {
20697        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
20698        let name = self.parse_object_name(false)?;
20699        if self.peek_token_ref().token != Token::LParen {
20700            return self.expected_ref(
20701                "'(' before the column list of CREATE FOREIGN TABLE",
20702                self.peek_token_ref(),
20703            );
20704        }
20705        let (columns, constraints) = self.parse_columns()?;
20706        self.expect_keyword_is(Keyword::SERVER)?;
20707        let server_name = self.parse_identifier()?;
20708        let options = self.parse_pg_options_clause()?;
20709
20710        Ok(CreateForeignTable {
20711            name,
20712            if_not_exists,
20713            columns,
20714            constraints,
20715            server_name,
20716            options,
20717        })
20718    }
20719
20720    /// The index of the first unprocessed token.
20721    pub fn index(&self) -> usize {
20722        self.index
20723    }
20724
20725    /// Parse a named window definition.
20726    pub fn parse_named_window(&mut self) -> Result<NamedWindowDefinition, ParserError> {
20727        let ident = self.parse_identifier()?;
20728        self.expect_keyword_is(Keyword::AS)?;
20729
20730        let window_expr = if self.consume_token(&Token::LParen) {
20731            NamedWindowExpr::WindowSpec(self.parse_window_spec()?)
20732        } else if self.dialect.supports_window_clause_named_window_reference() {
20733            NamedWindowExpr::NamedWindow(self.parse_identifier()?)
20734        } else {
20735            return self.expected_ref("(", self.peek_token_ref());
20736        };
20737
20738        Ok(NamedWindowDefinition(ident, window_expr))
20739    }
20740
20741    /// Parse `CREATE PROCEDURE` statement.
20742    pub fn parse_create_procedure(&mut self, or_alter: bool) -> Result<Statement, ParserError> {
20743        let name = self.parse_object_name(false)?;
20744        let params = self.parse_optional_procedure_parameters()?;
20745
20746        let language = if self.parse_keyword(Keyword::LANGUAGE) {
20747            Some(self.parse_identifier()?)
20748        } else {
20749            None
20750        };
20751
20752        self.expect_keyword_is(Keyword::AS)?;
20753
20754        let body = self.parse_conditional_statements(&[Keyword::END])?;
20755
20756        Ok(Statement::CreateProcedure {
20757            name,
20758            or_alter,
20759            params,
20760            language,
20761            body,
20762        })
20763    }
20764
20765    /// Parse a window specification.
20766    pub fn parse_window_spec(&mut self) -> Result<WindowSpec, ParserError> {
20767        let window_name = match &self.peek_token_ref().token {
20768            Token::Word(word) if word.keyword == Keyword::NoKeyword => {
20769                self.parse_optional_ident()?
20770            }
20771            _ => None,
20772        };
20773
20774        let partition_by = if self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
20775            self.parse_comma_separated(Parser::parse_expr)?
20776        } else {
20777            vec![]
20778        };
20779        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
20780            self.parse_comma_separated(Parser::parse_order_by_expr)?
20781        } else {
20782            vec![]
20783        };
20784
20785        let window_frame = if !self.consume_token(&Token::RParen) {
20786            let window_frame = self.parse_window_frame()?;
20787            self.expect_token(&Token::RParen)?;
20788            Some(window_frame)
20789        } else {
20790            None
20791        };
20792        Ok(WindowSpec {
20793            window_name,
20794            partition_by,
20795            order_by,
20796            window_frame,
20797        })
20798    }
20799
20800    /// Parse `CREATE TYPE` statement.
20801    pub fn parse_create_type(&mut self) -> Result<Statement, ParserError> {
20802        let name = self.parse_object_name(false)?;
20803
20804        // Check if we have AS keyword
20805        let has_as = self.parse_keyword(Keyword::AS);
20806
20807        if !has_as {
20808            // Two cases: CREATE TYPE name; or CREATE TYPE name (options);
20809            if self.consume_token(&Token::LParen) {
20810                // CREATE TYPE name (options) - SQL definition without AS
20811                let options = self.parse_create_type_sql_definition_options()?;
20812                self.expect_token(&Token::RParen)?;
20813                return Ok(Statement::CreateType {
20814                    name,
20815                    representation: Some(UserDefinedTypeRepresentation::SqlDefinition { options }),
20816                });
20817            }
20818
20819            // CREATE TYPE name; - no representation
20820            return Ok(Statement::CreateType {
20821                name,
20822                representation: None,
20823            });
20824        }
20825
20826        // We have AS keyword
20827        if self.parse_keyword(Keyword::ENUM) {
20828            // CREATE TYPE name AS ENUM (labels)
20829            self.parse_create_type_enum(name)
20830        } else if self.parse_keyword(Keyword::RANGE) {
20831            // CREATE TYPE name AS RANGE (options)
20832            self.parse_create_type_range(name)
20833        } else if self.consume_token(&Token::LParen) {
20834            // CREATE TYPE name AS (attributes) - Composite
20835            self.parse_create_type_composite(name)
20836        } else {
20837            self.expected_ref("ENUM, RANGE, or '(' after AS", self.peek_token_ref())
20838        }
20839    }
20840
20841    /// Parse remainder of `CREATE TYPE AS (attributes)` statement (composite type)
20842    ///
20843    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtype.html)
20844    fn parse_create_type_composite(&mut self, name: ObjectName) -> Result<Statement, ParserError> {
20845        if self.consume_token(&Token::RParen) {
20846            // Empty composite type
20847            return Ok(Statement::CreateType {
20848                name,
20849                representation: Some(UserDefinedTypeRepresentation::Composite {
20850                    attributes: vec![],
20851                }),
20852            });
20853        }
20854
20855        let mut attributes = vec![];
20856        loop {
20857            let attr_name = self.parse_identifier()?;
20858            let attr_data_type = self.parse_data_type()?;
20859            let attr_collation = if self.parse_keyword(Keyword::COLLATE) {
20860                Some(self.parse_object_name(false)?)
20861            } else {
20862                None
20863            };
20864            attributes.push(UserDefinedTypeCompositeAttributeDef {
20865                name: attr_name,
20866                data_type: attr_data_type,
20867                collation: attr_collation,
20868            });
20869
20870            if !self.consume_token(&Token::Comma) {
20871                break;
20872            }
20873        }
20874        self.expect_token(&Token::RParen)?;
20875
20876        Ok(Statement::CreateType {
20877            name,
20878            representation: Some(UserDefinedTypeRepresentation::Composite { attributes }),
20879        })
20880    }
20881
20882    /// Parse remainder of `CREATE TYPE AS ENUM` statement (see [Statement::CreateType] and [Self::parse_create_type])
20883    ///
20884    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtype.html)
20885    pub fn parse_create_type_enum(&mut self, name: ObjectName) -> Result<Statement, ParserError> {
20886        self.expect_token(&Token::LParen)?;
20887        let labels = self.parse_comma_separated0(|p| p.parse_identifier(), Token::RParen)?;
20888        self.expect_token(&Token::RParen)?;
20889
20890        Ok(Statement::CreateType {
20891            name,
20892            representation: Some(UserDefinedTypeRepresentation::Enum { labels }),
20893        })
20894    }
20895
20896    /// Parse remainder of `CREATE TYPE AS RANGE` statement
20897    ///
20898    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtype.html)
20899    fn parse_create_type_range(&mut self, name: ObjectName) -> Result<Statement, ParserError> {
20900        self.expect_token(&Token::LParen)?;
20901        let options = self.parse_comma_separated0(|p| p.parse_range_option(), Token::RParen)?;
20902        self.expect_token(&Token::RParen)?;
20903
20904        Ok(Statement::CreateType {
20905            name,
20906            representation: Some(UserDefinedTypeRepresentation::Range { options }),
20907        })
20908    }
20909
20910    /// Parse a single range option for a `CREATE TYPE AS RANGE` statement
20911    fn parse_range_option(&mut self) -> Result<UserDefinedTypeRangeOption, ParserError> {
20912        let keyword = self.parse_one_of_keywords(&[
20913            Keyword::SUBTYPE,
20914            Keyword::SUBTYPE_OPCLASS,
20915            Keyword::COLLATION,
20916            Keyword::CANONICAL,
20917            Keyword::SUBTYPE_DIFF,
20918            Keyword::MULTIRANGE_TYPE_NAME,
20919        ]);
20920
20921        match keyword {
20922            Some(Keyword::SUBTYPE) => {
20923                self.expect_token(&Token::Eq)?;
20924                let data_type = self.parse_data_type()?;
20925                Ok(UserDefinedTypeRangeOption::Subtype(data_type))
20926            }
20927            Some(Keyword::SUBTYPE_OPCLASS) => {
20928                self.expect_token(&Token::Eq)?;
20929                let name = self.parse_object_name(false)?;
20930                Ok(UserDefinedTypeRangeOption::SubtypeOpClass(name))
20931            }
20932            Some(Keyword::COLLATION) => {
20933                self.expect_token(&Token::Eq)?;
20934                let name = self.parse_object_name(false)?;
20935                Ok(UserDefinedTypeRangeOption::Collation(name))
20936            }
20937            Some(Keyword::CANONICAL) => {
20938                self.expect_token(&Token::Eq)?;
20939                let name = self.parse_object_name(false)?;
20940                Ok(UserDefinedTypeRangeOption::Canonical(name))
20941            }
20942            Some(Keyword::SUBTYPE_DIFF) => {
20943                self.expect_token(&Token::Eq)?;
20944                let name = self.parse_object_name(false)?;
20945                Ok(UserDefinedTypeRangeOption::SubtypeDiff(name))
20946            }
20947            Some(Keyword::MULTIRANGE_TYPE_NAME) => {
20948                self.expect_token(&Token::Eq)?;
20949                let name = self.parse_object_name(false)?;
20950                Ok(UserDefinedTypeRangeOption::MultirangeTypeName(name))
20951            }
20952            _ => self.expected_ref("range option keyword", self.peek_token_ref()),
20953        }
20954    }
20955
20956    /// Parse SQL definition options for CREATE TYPE (options)
20957    fn parse_create_type_sql_definition_options(
20958        &mut self,
20959    ) -> Result<Vec<UserDefinedTypeSqlDefinitionOption>, ParserError> {
20960        self.parse_comma_separated0(|p| p.parse_sql_definition_option(), Token::RParen)
20961    }
20962
20963    /// Parse a single SQL definition option for CREATE TYPE (options)
20964    fn parse_sql_definition_option(
20965        &mut self,
20966    ) -> Result<UserDefinedTypeSqlDefinitionOption, ParserError> {
20967        let keyword = self.parse_one_of_keywords(&[
20968            Keyword::INPUT,
20969            Keyword::OUTPUT,
20970            Keyword::RECEIVE,
20971            Keyword::SEND,
20972            Keyword::TYPMOD_IN,
20973            Keyword::TYPMOD_OUT,
20974            Keyword::ANALYZE,
20975            Keyword::SUBSCRIPT,
20976            Keyword::INTERNALLENGTH,
20977            Keyword::PASSEDBYVALUE,
20978            Keyword::ALIGNMENT,
20979            Keyword::STORAGE,
20980            Keyword::LIKE,
20981            Keyword::CATEGORY,
20982            Keyword::PREFERRED,
20983            Keyword::DEFAULT,
20984            Keyword::ELEMENT,
20985            Keyword::DELIMITER,
20986            Keyword::COLLATABLE,
20987        ]);
20988
20989        match keyword {
20990            Some(Keyword::INPUT) => {
20991                self.expect_token(&Token::Eq)?;
20992                let name = self.parse_object_name(false)?;
20993                Ok(UserDefinedTypeSqlDefinitionOption::Input(name))
20994            }
20995            Some(Keyword::OUTPUT) => {
20996                self.expect_token(&Token::Eq)?;
20997                let name = self.parse_object_name(false)?;
20998                Ok(UserDefinedTypeSqlDefinitionOption::Output(name))
20999            }
21000            Some(Keyword::RECEIVE) => {
21001                self.expect_token(&Token::Eq)?;
21002                let name = self.parse_object_name(false)?;
21003                Ok(UserDefinedTypeSqlDefinitionOption::Receive(name))
21004            }
21005            Some(Keyword::SEND) => {
21006                self.expect_token(&Token::Eq)?;
21007                let name = self.parse_object_name(false)?;
21008                Ok(UserDefinedTypeSqlDefinitionOption::Send(name))
21009            }
21010            Some(Keyword::TYPMOD_IN) => {
21011                self.expect_token(&Token::Eq)?;
21012                let name = self.parse_object_name(false)?;
21013                Ok(UserDefinedTypeSqlDefinitionOption::TypmodIn(name))
21014            }
21015            Some(Keyword::TYPMOD_OUT) => {
21016                self.expect_token(&Token::Eq)?;
21017                let name = self.parse_object_name(false)?;
21018                Ok(UserDefinedTypeSqlDefinitionOption::TypmodOut(name))
21019            }
21020            Some(Keyword::ANALYZE) => {
21021                self.expect_token(&Token::Eq)?;
21022                let name = self.parse_object_name(false)?;
21023                Ok(UserDefinedTypeSqlDefinitionOption::Analyze(name))
21024            }
21025            Some(Keyword::SUBSCRIPT) => {
21026                self.expect_token(&Token::Eq)?;
21027                let name = self.parse_object_name(false)?;
21028                Ok(UserDefinedTypeSqlDefinitionOption::Subscript(name))
21029            }
21030            Some(Keyword::INTERNALLENGTH) => {
21031                self.expect_token(&Token::Eq)?;
21032                if self.parse_keyword(Keyword::VARIABLE) {
21033                    Ok(UserDefinedTypeSqlDefinitionOption::InternalLength(
21034                        UserDefinedTypeInternalLength::Variable,
21035                    ))
21036                } else {
21037                    let value = self.parse_literal_uint()?;
21038                    Ok(UserDefinedTypeSqlDefinitionOption::InternalLength(
21039                        UserDefinedTypeInternalLength::Fixed(value),
21040                    ))
21041                }
21042            }
21043            Some(Keyword::PASSEDBYVALUE) => Ok(UserDefinedTypeSqlDefinitionOption::PassedByValue),
21044            Some(Keyword::ALIGNMENT) => {
21045                self.expect_token(&Token::Eq)?;
21046                let align_keyword = self.parse_one_of_keywords(&[
21047                    Keyword::CHAR,
21048                    Keyword::INT2,
21049                    Keyword::INT4,
21050                    Keyword::DOUBLE,
21051                ]);
21052                match align_keyword {
21053                    Some(Keyword::CHAR) => Ok(UserDefinedTypeSqlDefinitionOption::Alignment(
21054                        Alignment::Char,
21055                    )),
21056                    Some(Keyword::INT2) => Ok(UserDefinedTypeSqlDefinitionOption::Alignment(
21057                        Alignment::Int2,
21058                    )),
21059                    Some(Keyword::INT4) => Ok(UserDefinedTypeSqlDefinitionOption::Alignment(
21060                        Alignment::Int4,
21061                    )),
21062                    Some(Keyword::DOUBLE) => Ok(UserDefinedTypeSqlDefinitionOption::Alignment(
21063                        Alignment::Double,
21064                    )),
21065                    _ => self.expected_ref(
21066                        "alignment value (char, int2, int4, or double)",
21067                        self.peek_token_ref(),
21068                    ),
21069                }
21070            }
21071            Some(Keyword::STORAGE) => {
21072                self.expect_token(&Token::Eq)?;
21073                let storage_keyword = self.parse_one_of_keywords(&[
21074                    Keyword::PLAIN,
21075                    Keyword::EXTERNAL,
21076                    Keyword::EXTENDED,
21077                    Keyword::MAIN,
21078                ]);
21079                match storage_keyword {
21080                    Some(Keyword::PLAIN) => Ok(UserDefinedTypeSqlDefinitionOption::Storage(
21081                        UserDefinedTypeStorage::Plain,
21082                    )),
21083                    Some(Keyword::EXTERNAL) => Ok(UserDefinedTypeSqlDefinitionOption::Storage(
21084                        UserDefinedTypeStorage::External,
21085                    )),
21086                    Some(Keyword::EXTENDED) => Ok(UserDefinedTypeSqlDefinitionOption::Storage(
21087                        UserDefinedTypeStorage::Extended,
21088                    )),
21089                    Some(Keyword::MAIN) => Ok(UserDefinedTypeSqlDefinitionOption::Storage(
21090                        UserDefinedTypeStorage::Main,
21091                    )),
21092                    _ => self.expected_ref(
21093                        "storage value (plain, external, extended, or main)",
21094                        self.peek_token_ref(),
21095                    ),
21096                }
21097            }
21098            Some(Keyword::LIKE) => {
21099                self.expect_token(&Token::Eq)?;
21100                let name = self.parse_object_name(false)?;
21101                Ok(UserDefinedTypeSqlDefinitionOption::Like(name))
21102            }
21103            Some(Keyword::CATEGORY) => {
21104                self.expect_token(&Token::Eq)?;
21105                let category_str = self.parse_literal_string()?;
21106                let category_char = category_str.chars().next().ok_or_else(|| {
21107                    ParserError::ParserError(
21108                        "CATEGORY value must be a single character".to_string(),
21109                    )
21110                })?;
21111                Ok(UserDefinedTypeSqlDefinitionOption::Category(category_char))
21112            }
21113            Some(Keyword::PREFERRED) => {
21114                self.expect_token(&Token::Eq)?;
21115                let value =
21116                    self.parse_keyword(Keyword::TRUE) || !self.parse_keyword(Keyword::FALSE);
21117                Ok(UserDefinedTypeSqlDefinitionOption::Preferred(value))
21118            }
21119            Some(Keyword::DEFAULT) => {
21120                self.expect_token(&Token::Eq)?;
21121                let expr = self.parse_expr()?;
21122                Ok(UserDefinedTypeSqlDefinitionOption::Default(expr))
21123            }
21124            Some(Keyword::ELEMENT) => {
21125                self.expect_token(&Token::Eq)?;
21126                let data_type = self.parse_data_type()?;
21127                Ok(UserDefinedTypeSqlDefinitionOption::Element(data_type))
21128            }
21129            Some(Keyword::DELIMITER) => {
21130                self.expect_token(&Token::Eq)?;
21131                let delimiter = self.parse_literal_string()?;
21132                Ok(UserDefinedTypeSqlDefinitionOption::Delimiter(delimiter))
21133            }
21134            Some(Keyword::COLLATABLE) => {
21135                self.expect_token(&Token::Eq)?;
21136                let value =
21137                    self.parse_keyword(Keyword::TRUE) || !self.parse_keyword(Keyword::FALSE);
21138                Ok(UserDefinedTypeSqlDefinitionOption::Collatable(value))
21139            }
21140            _ => self.expected_ref("SQL definition option keyword", self.peek_token_ref()),
21141        }
21142    }
21143
21144    fn parse_parenthesized_identifiers(&mut self) -> Result<Vec<Ident>, ParserError> {
21145        self.expect_token(&Token::LParen)?;
21146        let idents = self.parse_comma_separated0(|p| p.parse_identifier(), Token::RParen)?;
21147        self.expect_token(&Token::RParen)?;
21148        Ok(idents)
21149    }
21150
21151    fn parse_column_position(&mut self) -> Result<Option<MySQLColumnPosition>, ParserError> {
21152        if self.dialect.supports_alter_column_position() {
21153            if self.parse_keyword(Keyword::FIRST) {
21154                Ok(Some(MySQLColumnPosition::First))
21155            } else if self.parse_keyword(Keyword::AFTER) {
21156                let ident = self.parse_identifier()?;
21157                Ok(Some(MySQLColumnPosition::After(ident)))
21158            } else {
21159                Ok(None)
21160            }
21161        } else {
21162            Ok(None)
21163        }
21164    }
21165
21166    /// Parse [Statement::Print]
21167    fn parse_print(&mut self) -> Result<Statement, ParserError> {
21168        Ok(Statement::Print(PrintStatement {
21169            message: Box::new(self.parse_expr()?),
21170        }))
21171    }
21172
21173    /// Parse [Statement::WaitFor]
21174    ///
21175    /// See: <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/waitfor-transact-sql>
21176    fn parse_waitfor(&mut self) -> Result<Statement, ParserError> {
21177        let wait_type = if self.parse_keyword(Keyword::DELAY) {
21178            WaitForType::Delay
21179        } else if self.parse_keyword(Keyword::TIME) {
21180            WaitForType::Time
21181        } else {
21182            return self.expected_ref("DELAY or TIME", self.peek_token_ref());
21183        };
21184        let expr = self.parse_expr()?;
21185        Ok(Statement::WaitFor(WaitForStatement { wait_type, expr }))
21186    }
21187
21188    /// Parse [Statement::Return]
21189    fn parse_return(&mut self) -> Result<Statement, ParserError> {
21190        match self.maybe_parse(|p| p.parse_expr())? {
21191            Some(expr) => Ok(Statement::Return(ReturnStatement {
21192                value: Some(ReturnStatementValue::Expr(expr)),
21193            })),
21194            None => Ok(Statement::Return(ReturnStatement { value: None })),
21195        }
21196    }
21197
21198    /// /// Parse a `EXPORT DATA` statement.
21199    ///
21200    /// See [Statement::ExportData]
21201    fn parse_export_data(&mut self) -> Result<Statement, ParserError> {
21202        self.expect_keywords(&[Keyword::EXPORT, Keyword::DATA])?;
21203
21204        let connection = if self.parse_keywords(&[Keyword::WITH, Keyword::CONNECTION]) {
21205            Some(self.parse_object_name(false)?)
21206        } else {
21207            None
21208        };
21209        self.expect_keyword(Keyword::OPTIONS)?;
21210        self.expect_token(&Token::LParen)?;
21211        let options = self.parse_comma_separated(|p| p.parse_sql_option())?;
21212        self.expect_token(&Token::RParen)?;
21213        self.expect_keyword(Keyword::AS)?;
21214        let query = self.parse_query()?;
21215        Ok(Statement::ExportData(ExportData {
21216            options,
21217            query,
21218            connection,
21219        }))
21220    }
21221
21222    fn parse_vacuum(&mut self) -> Result<Statement, ParserError> {
21223        self.expect_keyword(Keyword::VACUUM)?;
21224        let full = self.parse_keyword(Keyword::FULL);
21225        let sort_only = self.parse_keywords(&[Keyword::SORT, Keyword::ONLY]);
21226        let delete_only = self.parse_keywords(&[Keyword::DELETE, Keyword::ONLY]);
21227        let reindex = self.parse_keyword(Keyword::REINDEX);
21228        let recluster = self.parse_keyword(Keyword::RECLUSTER);
21229        let (table_name, threshold, boost) =
21230            match self.maybe_parse(|p| p.parse_object_name(false))? {
21231                Some(table_name) => {
21232                    let threshold = if self.parse_keyword(Keyword::TO) {
21233                        let value = self.parse_value()?;
21234                        self.expect_keyword(Keyword::PERCENT)?;
21235                        Some(value)
21236                    } else {
21237                        None
21238                    };
21239                    let boost = self.parse_keyword(Keyword::BOOST);
21240                    (Some(table_name), threshold, boost)
21241                }
21242                _ => (None, None, false),
21243            };
21244        Ok(Statement::Vacuum(VacuumStatement {
21245            full,
21246            sort_only,
21247            delete_only,
21248            reindex,
21249            recluster,
21250            table_name,
21251            threshold,
21252            boost,
21253        }))
21254    }
21255
21256    /// Consume the parser and return its underlying token buffer
21257    pub fn into_tokens(self) -> Vec<TokenWithSpan> {
21258        self.tokens
21259    }
21260
21261    /// Returns true if the next keyword indicates a sub query, i.e. SELECT or WITH
21262    fn peek_sub_query(&mut self) -> bool {
21263        self.peek_one_of_keywords(&[Keyword::SELECT, Keyword::WITH])
21264            .is_some()
21265    }
21266
21267    pub(crate) fn parse_show_stmt_options(&mut self) -> Result<ShowStatementOptions, ParserError> {
21268        let show_in;
21269        let mut filter_position = None;
21270        if self.dialect.supports_show_like_before_in() {
21271            if let Some(filter) = self.parse_show_statement_filter()? {
21272                filter_position = Some(ShowStatementFilterPosition::Infix(filter));
21273            }
21274            show_in = self.maybe_parse_show_stmt_in()?;
21275        } else {
21276            show_in = self.maybe_parse_show_stmt_in()?;
21277            if let Some(filter) = self.parse_show_statement_filter()? {
21278                filter_position = Some(ShowStatementFilterPosition::Suffix(filter));
21279            }
21280        }
21281        let starts_with = self.maybe_parse_show_stmt_starts_with()?;
21282        let limit = self.maybe_parse_show_stmt_limit()?;
21283        let from = self.maybe_parse_show_stmt_from()?;
21284        Ok(ShowStatementOptions {
21285            filter_position,
21286            show_in,
21287            starts_with,
21288            limit,
21289            limit_from: from,
21290        })
21291    }
21292
21293    fn maybe_parse_show_stmt_in(&mut self) -> Result<Option<ShowStatementIn>, ParserError> {
21294        let clause = match self.parse_one_of_keywords(&[Keyword::FROM, Keyword::IN]) {
21295            Some(Keyword::FROM) => ShowStatementInClause::FROM,
21296            Some(Keyword::IN) => ShowStatementInClause::IN,
21297            None => return Ok(None),
21298            _ => return self.expected_ref("FROM or IN", self.peek_token_ref()),
21299        };
21300
21301        let (parent_type, parent_name) = match self.parse_one_of_keywords(&[
21302            Keyword::ACCOUNT,
21303            Keyword::DATABASE,
21304            Keyword::SCHEMA,
21305            Keyword::TABLE,
21306            Keyword::VIEW,
21307        ]) {
21308            // If we see these next keywords it means we don't have a parent name
21309            Some(Keyword::DATABASE)
21310                if self.peek_keywords(&[Keyword::STARTS, Keyword::WITH])
21311                    | self.peek_keyword(Keyword::LIMIT) =>
21312            {
21313                (Some(ShowStatementInParentType::Database), None)
21314            }
21315            Some(Keyword::SCHEMA)
21316                if self.peek_keywords(&[Keyword::STARTS, Keyword::WITH])
21317                    | self.peek_keyword(Keyword::LIMIT) =>
21318            {
21319                (Some(ShowStatementInParentType::Schema), None)
21320            }
21321            Some(parent_kw) => {
21322                // The parent name here is still optional, for example:
21323                // SHOW TABLES IN ACCOUNT, so parsing the object name
21324                // may fail because the statement ends.
21325                let parent_name = self.maybe_parse(|p| p.parse_object_name(false))?;
21326                match parent_kw {
21327                    Keyword::ACCOUNT => (Some(ShowStatementInParentType::Account), parent_name),
21328                    Keyword::DATABASE => (Some(ShowStatementInParentType::Database), parent_name),
21329                    Keyword::SCHEMA => (Some(ShowStatementInParentType::Schema), parent_name),
21330                    Keyword::TABLE => (Some(ShowStatementInParentType::Table), parent_name),
21331                    Keyword::VIEW => (Some(ShowStatementInParentType::View), parent_name),
21332                    _ => {
21333                        return self.expected_ref(
21334                            "one of ACCOUNT, DATABASE, SCHEMA, TABLE or VIEW",
21335                            self.peek_token_ref(),
21336                        )
21337                    }
21338                }
21339            }
21340            None => {
21341                // Parsing MySQL style FROM tbl_name FROM db_name
21342                // which is equivalent to FROM tbl_name.db_name
21343                let mut parent_name = self.parse_object_name(false)?;
21344                if self
21345                    .parse_one_of_keywords(&[Keyword::FROM, Keyword::IN])
21346                    .is_some()
21347                {
21348                    parent_name
21349                        .0
21350                        .insert(0, ObjectNamePart::Identifier(self.parse_identifier()?));
21351                }
21352                (None, Some(parent_name))
21353            }
21354        };
21355
21356        Ok(Some(ShowStatementIn {
21357            clause,
21358            parent_type,
21359            parent_name,
21360        }))
21361    }
21362
21363    fn maybe_parse_show_stmt_starts_with(&mut self) -> Result<Option<ValueWithSpan>, ParserError> {
21364        if self.parse_keywords(&[Keyword::STARTS, Keyword::WITH]) {
21365            Ok(Some(self.parse_value()?))
21366        } else {
21367            Ok(None)
21368        }
21369    }
21370
21371    fn maybe_parse_show_stmt_limit(&mut self) -> Result<Option<Expr>, ParserError> {
21372        if self.parse_keyword(Keyword::LIMIT) {
21373            Ok(self.parse_limit()?)
21374        } else {
21375            Ok(None)
21376        }
21377    }
21378
21379    fn maybe_parse_show_stmt_from(&mut self) -> Result<Option<ValueWithSpan>, ParserError> {
21380        if self.parse_keyword(Keyword::FROM) {
21381            Ok(Some(self.parse_value()?))
21382        } else {
21383            Ok(None)
21384        }
21385    }
21386
21387    pub(crate) fn in_column_definition_state(&self) -> bool {
21388        matches!(self.state, ColumnDefinition)
21389    }
21390
21391    /// Parses options provided in key-value format.
21392    ///
21393    /// * `parenthesized` - true if the options are enclosed in parenthesis
21394    /// * `end_words` - a list of keywords that any of them indicates the end of the options section
21395    pub(crate) fn parse_key_value_options(
21396        &mut self,
21397        parenthesized: bool,
21398        end_words: &[Keyword],
21399    ) -> Result<KeyValueOptions, ParserError> {
21400        let mut options: Vec<KeyValueOption> = Vec::new();
21401        let mut delimiter = KeyValueOptionsDelimiter::Space;
21402        if parenthesized {
21403            self.expect_token(&Token::LParen)?;
21404        }
21405        loop {
21406            match self.next_token().token {
21407                Token::RParen => {
21408                    if parenthesized {
21409                        break;
21410                    } else {
21411                        return self.expected_ref(" another option or EOF", self.peek_token_ref());
21412                    }
21413                }
21414                Token::EOF => break,
21415                Token::SemiColon => {
21416                    self.prev_token();
21417                    break;
21418                }
21419                Token::Comma => {
21420                    delimiter = KeyValueOptionsDelimiter::Comma;
21421                    continue;
21422                }
21423                Token::Word(w) if !end_words.contains(&w.keyword) => {
21424                    options.push(self.parse_key_value_option(&w)?)
21425                }
21426                Token::Word(w) if end_words.contains(&w.keyword) => {
21427                    self.prev_token();
21428                    break;
21429                }
21430                _ => {
21431                    return self.expected_ref(
21432                        "another option, EOF, SemiColon, Comma or ')'",
21433                        self.peek_token_ref(),
21434                    )
21435                }
21436            };
21437        }
21438
21439        Ok(KeyValueOptions { delimiter, options })
21440    }
21441
21442    /// Parses a `KEY = VALUE` construct based on the specified key
21443    pub(crate) fn parse_key_value_option(
21444        &mut self,
21445        key: &Word,
21446    ) -> Result<KeyValueOption, ParserError> {
21447        self.expect_token(&Token::Eq)?;
21448        let peeked_token = self.peek_token();
21449        match peeked_token.token {
21450            Token::SingleQuotedString(_) => Ok(KeyValueOption {
21451                option_name: key.value.clone(),
21452                option_value: KeyValueOptionKind::Single(self.parse_value()?),
21453            }),
21454            Token::Word(word)
21455                if word.keyword == Keyword::TRUE || word.keyword == Keyword::FALSE =>
21456            {
21457                Ok(KeyValueOption {
21458                    option_name: key.value.clone(),
21459                    option_value: KeyValueOptionKind::Single(self.parse_value()?),
21460                })
21461            }
21462            Token::Number(..) => Ok(KeyValueOption {
21463                option_name: key.value.clone(),
21464                option_value: KeyValueOptionKind::Single(self.parse_value()?),
21465            }),
21466            Token::Word(word) => {
21467                self.next_token();
21468                Ok(KeyValueOption {
21469                    option_name: key.value.clone(),
21470                    option_value: KeyValueOptionKind::Single(
21471                        Value::Placeholder(word.value.clone()).with_span(peeked_token.span),
21472                    ),
21473                })
21474            }
21475            Token::LParen => {
21476                // Can be a list of values or a list of key value properties.
21477                // Try to parse a list of values and if that fails, try to parse
21478                // a list of key-value properties.
21479                match self.maybe_parse(|parser| {
21480                    parser.expect_token(&Token::LParen)?;
21481                    let values = parser.parse_comma_separated0(|p| p.parse_value(), Token::RParen);
21482                    parser.expect_token(&Token::RParen)?;
21483                    values
21484                })? {
21485                    Some(values) => Ok(KeyValueOption {
21486                        option_name: key.value.clone(),
21487                        option_value: KeyValueOptionKind::Multi(values),
21488                    }),
21489                    None => Ok(KeyValueOption {
21490                        option_name: key.value.clone(),
21491                        option_value: KeyValueOptionKind::KeyValueOptions(Box::new(
21492                            self.parse_key_value_options(true, &[])?,
21493                        )),
21494                    }),
21495                }
21496            }
21497            _ => self.expected_ref("expected option value", self.peek_token_ref()),
21498        }
21499    }
21500
21501    /// Parses a RESET statement
21502    fn parse_reset(&mut self) -> Result<ResetStatement, ParserError> {
21503        if self.parse_keyword(Keyword::ALL) {
21504            return Ok(ResetStatement { reset: Reset::ALL });
21505        }
21506
21507        if self.parse_keywords(&[Keyword::SESSION, Keyword::AUTHORIZATION]) {
21508            return Ok(ResetStatement {
21509                reset: Reset::SessionAuthorization,
21510            });
21511        }
21512
21513        if self.dialect.supports_reset_time_zone()
21514            && self.parse_keywords(&[Keyword::TIME, Keyword::ZONE])
21515        {
21516            return Ok(ResetStatement {
21517                reset: Reset::ConfigurationParameter(ObjectName::from(vec!["TimeZone".into()])),
21518            });
21519        }
21520        let obj = self.parse_object_name(false)?;
21521        Ok(ResetStatement {
21522            reset: Reset::ConfigurationParameter(obj),
21523        })
21524    }
21525}
21526
21527fn maybe_prefixed_expr(expr: Expr, prefix: Option<Ident>) -> Expr {
21528    if let Some(prefix) = prefix {
21529        Expr::Prefixed {
21530            prefix,
21531            value: Box::new(expr),
21532        }
21533    } else {
21534        expr
21535    }
21536}
21537
21538impl Word {
21539    /// Convert a reference to this word into an [`Ident`] by cloning the value.
21540    ///
21541    /// Use this method when you need to keep the original `Word` around.
21542    /// If you can consume the `Word`, prefer [`into_ident`](Self::into_ident) instead
21543    /// to avoid cloning.
21544    #[inline]
21545    pub fn to_ident(&self, span: Span) -> Ident {
21546        Ident {
21547            value: self.value.clone(),
21548            quote_style: self.quote_style,
21549            span,
21550        }
21551    }
21552
21553    /// Convert this word into an [`Ident`] identifier, consuming the `Word`.
21554    ///
21555    /// This avoids cloning the string value. If you need to keep the original
21556    /// `Word`, use [`to_ident`](Self::to_ident) instead.
21557    pub fn into_ident(self, span: Span) -> Ident {
21558        Ident {
21559            value: self.value,
21560            quote_style: self.quote_style,
21561            span,
21562        }
21563    }
21564}
21565
21566#[cfg(test)]
21567mod tests {
21568    use crate::test_utils::{all_dialects, TestedDialects};
21569
21570    use super::*;
21571
21572    #[test]
21573    fn test_prev_index() {
21574        let sql = "SELECT version";
21575        all_dialects().run_parser_method(sql, |parser| {
21576            assert_eq!(parser.peek_token(), Token::make_keyword("SELECT"));
21577            assert_eq!(parser.next_token(), Token::make_keyword("SELECT"));
21578            parser.prev_token();
21579            assert_eq!(parser.next_token(), Token::make_keyword("SELECT"));
21580            assert_eq!(parser.next_token(), Token::make_word("version", None));
21581            parser.prev_token();
21582            assert_eq!(parser.peek_token(), Token::make_word("version", None));
21583            assert_eq!(parser.next_token(), Token::make_word("version", None));
21584            assert_eq!(parser.peek_token(), Token::EOF);
21585            parser.prev_token();
21586            assert_eq!(parser.next_token(), Token::make_word("version", None));
21587            assert_eq!(parser.next_token(), Token::EOF);
21588            assert_eq!(parser.next_token(), Token::EOF);
21589            parser.prev_token();
21590        });
21591    }
21592
21593    #[test]
21594    fn test_peek_tokens() {
21595        all_dialects().run_parser_method("SELECT foo AS bar FROM baz", |parser| {
21596            assert!(matches!(
21597                parser.peek_tokens(),
21598                [Token::Word(Word {
21599                    keyword: Keyword::SELECT,
21600                    ..
21601                })]
21602            ));
21603
21604            assert!(matches!(
21605                parser.peek_tokens(),
21606                [
21607                    Token::Word(Word {
21608                        keyword: Keyword::SELECT,
21609                        ..
21610                    }),
21611                    Token::Word(_),
21612                    Token::Word(Word {
21613                        keyword: Keyword::AS,
21614                        ..
21615                    }),
21616                ]
21617            ));
21618
21619            for _ in 0..4 {
21620                parser.next_token();
21621            }
21622
21623            assert!(matches!(
21624                parser.peek_tokens(),
21625                [
21626                    Token::Word(Word {
21627                        keyword: Keyword::FROM,
21628                        ..
21629                    }),
21630                    Token::Word(_),
21631                    Token::EOF,
21632                    Token::EOF,
21633                ]
21634            ))
21635        })
21636    }
21637
21638    #[cfg(test)]
21639    mod test_parse_data_type {
21640        use crate::ast::{
21641            CharLengthUnits, CharacterLength, DataType, ExactNumberInfo, ObjectName, TimezoneInfo,
21642        };
21643        use crate::dialect::{AnsiDialect, GenericDialect, PostgreSqlDialect};
21644        use crate::test_utils::TestedDialects;
21645
21646        macro_rules! test_parse_data_type {
21647            ($dialect:expr, $input:expr, $expected_type:expr $(,)?) => {{
21648                $dialect.run_parser_method(&*$input, |parser| {
21649                    let data_type = parser.parse_data_type().unwrap();
21650                    assert_eq!($expected_type, data_type);
21651                    assert_eq!($input.to_string(), data_type.to_string());
21652                });
21653            }};
21654        }
21655
21656        #[test]
21657        fn test_ansii_character_string_types() {
21658            // Character string types: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#character-string-type>
21659            let dialect =
21660                TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(AnsiDialect {})]);
21661
21662            test_parse_data_type!(dialect, "CHARACTER", DataType::Character(None));
21663
21664            test_parse_data_type!(
21665                dialect,
21666                "CHARACTER(20)",
21667                DataType::Character(Some(CharacterLength::IntegerLength {
21668                    length: 20,
21669                    unit: None
21670                }))
21671            );
21672
21673            test_parse_data_type!(
21674                dialect,
21675                "CHARACTER(20 CHARACTERS)",
21676                DataType::Character(Some(CharacterLength::IntegerLength {
21677                    length: 20,
21678                    unit: Some(CharLengthUnits::Characters)
21679                }))
21680            );
21681
21682            test_parse_data_type!(
21683                dialect,
21684                "CHARACTER(20 OCTETS)",
21685                DataType::Character(Some(CharacterLength::IntegerLength {
21686                    length: 20,
21687                    unit: Some(CharLengthUnits::Octets)
21688                }))
21689            );
21690
21691            test_parse_data_type!(dialect, "CHAR", DataType::Char(None));
21692
21693            test_parse_data_type!(
21694                dialect,
21695                "CHAR(20)",
21696                DataType::Char(Some(CharacterLength::IntegerLength {
21697                    length: 20,
21698                    unit: None
21699                }))
21700            );
21701
21702            test_parse_data_type!(
21703                dialect,
21704                "CHAR(20 CHARACTERS)",
21705                DataType::Char(Some(CharacterLength::IntegerLength {
21706                    length: 20,
21707                    unit: Some(CharLengthUnits::Characters)
21708                }))
21709            );
21710
21711            test_parse_data_type!(
21712                dialect,
21713                "CHAR(20 OCTETS)",
21714                DataType::Char(Some(CharacterLength::IntegerLength {
21715                    length: 20,
21716                    unit: Some(CharLengthUnits::Octets)
21717                }))
21718            );
21719
21720            test_parse_data_type!(
21721                dialect,
21722                "CHARACTER VARYING(20)",
21723                DataType::CharacterVarying(Some(CharacterLength::IntegerLength {
21724                    length: 20,
21725                    unit: None
21726                }))
21727            );
21728
21729            test_parse_data_type!(
21730                dialect,
21731                "CHARACTER VARYING(20 CHARACTERS)",
21732                DataType::CharacterVarying(Some(CharacterLength::IntegerLength {
21733                    length: 20,
21734                    unit: Some(CharLengthUnits::Characters)
21735                }))
21736            );
21737
21738            test_parse_data_type!(
21739                dialect,
21740                "CHARACTER VARYING(20 OCTETS)",
21741                DataType::CharacterVarying(Some(CharacterLength::IntegerLength {
21742                    length: 20,
21743                    unit: Some(CharLengthUnits::Octets)
21744                }))
21745            );
21746
21747            test_parse_data_type!(
21748                dialect,
21749                "CHAR VARYING(20)",
21750                DataType::CharVarying(Some(CharacterLength::IntegerLength {
21751                    length: 20,
21752                    unit: None
21753                }))
21754            );
21755
21756            test_parse_data_type!(
21757                dialect,
21758                "CHAR VARYING(20 CHARACTERS)",
21759                DataType::CharVarying(Some(CharacterLength::IntegerLength {
21760                    length: 20,
21761                    unit: Some(CharLengthUnits::Characters)
21762                }))
21763            );
21764
21765            test_parse_data_type!(
21766                dialect,
21767                "CHAR VARYING(20 OCTETS)",
21768                DataType::CharVarying(Some(CharacterLength::IntegerLength {
21769                    length: 20,
21770                    unit: Some(CharLengthUnits::Octets)
21771                }))
21772            );
21773
21774            test_parse_data_type!(
21775                dialect,
21776                "VARCHAR(20)",
21777                DataType::Varchar(Some(CharacterLength::IntegerLength {
21778                    length: 20,
21779                    unit: None
21780                }))
21781            );
21782        }
21783
21784        #[test]
21785        fn test_ansii_character_large_object_types() {
21786            // Character large object types: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#character-large-object-length>
21787            let dialect =
21788                TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(AnsiDialect {})]);
21789
21790            test_parse_data_type!(
21791                dialect,
21792                "CHARACTER LARGE OBJECT",
21793                DataType::CharacterLargeObject(None)
21794            );
21795            test_parse_data_type!(
21796                dialect,
21797                "CHARACTER LARGE OBJECT(20)",
21798                DataType::CharacterLargeObject(Some(20))
21799            );
21800
21801            test_parse_data_type!(
21802                dialect,
21803                "CHAR LARGE OBJECT",
21804                DataType::CharLargeObject(None)
21805            );
21806            test_parse_data_type!(
21807                dialect,
21808                "CHAR LARGE OBJECT(20)",
21809                DataType::CharLargeObject(Some(20))
21810            );
21811
21812            test_parse_data_type!(dialect, "CLOB", DataType::Clob(None));
21813            test_parse_data_type!(dialect, "CLOB(20)", DataType::Clob(Some(20)));
21814        }
21815
21816        #[test]
21817        fn test_parse_custom_types() {
21818            let dialect =
21819                TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(AnsiDialect {})]);
21820
21821            test_parse_data_type!(
21822                dialect,
21823                "GEOMETRY",
21824                DataType::Custom(ObjectName::from(vec!["GEOMETRY".into()]), vec![])
21825            );
21826
21827            test_parse_data_type!(
21828                dialect,
21829                "GEOMETRY(POINT)",
21830                DataType::Custom(
21831                    ObjectName::from(vec!["GEOMETRY".into()]),
21832                    vec!["POINT".to_string()]
21833                )
21834            );
21835
21836            test_parse_data_type!(
21837                dialect,
21838                "GEOMETRY(POINT, 4326)",
21839                DataType::Custom(
21840                    ObjectName::from(vec!["GEOMETRY".into()]),
21841                    vec!["POINT".to_string(), "4326".to_string()]
21842                )
21843            );
21844        }
21845
21846        #[test]
21847        fn test_ansii_exact_numeric_types() {
21848            // Exact numeric types: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#exact-numeric-type>
21849            let dialect = TestedDialects::new(vec![
21850                Box::new(GenericDialect {}),
21851                Box::new(AnsiDialect {}),
21852                Box::new(PostgreSqlDialect {}),
21853            ]);
21854
21855            test_parse_data_type!(dialect, "NUMERIC", DataType::Numeric(ExactNumberInfo::None));
21856
21857            test_parse_data_type!(
21858                dialect,
21859                "NUMERIC(2)",
21860                DataType::Numeric(ExactNumberInfo::Precision(2))
21861            );
21862
21863            test_parse_data_type!(
21864                dialect,
21865                "NUMERIC(2,10)",
21866                DataType::Numeric(ExactNumberInfo::PrecisionAndScale(2, 10))
21867            );
21868
21869            test_parse_data_type!(dialect, "DECIMAL", DataType::Decimal(ExactNumberInfo::None));
21870
21871            test_parse_data_type!(
21872                dialect,
21873                "DECIMAL(2)",
21874                DataType::Decimal(ExactNumberInfo::Precision(2))
21875            );
21876
21877            test_parse_data_type!(
21878                dialect,
21879                "DECIMAL(2,10)",
21880                DataType::Decimal(ExactNumberInfo::PrecisionAndScale(2, 10))
21881            );
21882
21883            test_parse_data_type!(dialect, "DEC", DataType::Dec(ExactNumberInfo::None));
21884
21885            test_parse_data_type!(
21886                dialect,
21887                "DEC(2)",
21888                DataType::Dec(ExactNumberInfo::Precision(2))
21889            );
21890
21891            test_parse_data_type!(
21892                dialect,
21893                "DEC(2,10)",
21894                DataType::Dec(ExactNumberInfo::PrecisionAndScale(2, 10))
21895            );
21896
21897            // Test negative scale values.
21898            test_parse_data_type!(
21899                dialect,
21900                "NUMERIC(10,-2)",
21901                DataType::Numeric(ExactNumberInfo::PrecisionAndScale(10, -2))
21902            );
21903
21904            test_parse_data_type!(
21905                dialect,
21906                "DECIMAL(1000,-10)",
21907                DataType::Decimal(ExactNumberInfo::PrecisionAndScale(1000, -10))
21908            );
21909
21910            test_parse_data_type!(
21911                dialect,
21912                "DEC(5,-1000)",
21913                DataType::Dec(ExactNumberInfo::PrecisionAndScale(5, -1000))
21914            );
21915
21916            test_parse_data_type!(
21917                dialect,
21918                "NUMERIC(10,-5)",
21919                DataType::Numeric(ExactNumberInfo::PrecisionAndScale(10, -5))
21920            );
21921
21922            test_parse_data_type!(
21923                dialect,
21924                "DECIMAL(20,-10)",
21925                DataType::Decimal(ExactNumberInfo::PrecisionAndScale(20, -10))
21926            );
21927
21928            test_parse_data_type!(
21929                dialect,
21930                "DEC(5,-2)",
21931                DataType::Dec(ExactNumberInfo::PrecisionAndScale(5, -2))
21932            );
21933
21934            dialect.run_parser_method("NUMERIC(10,+5)", |parser| {
21935                let data_type = parser.parse_data_type().unwrap();
21936                assert_eq!(
21937                    DataType::Numeric(ExactNumberInfo::PrecisionAndScale(10, 5)),
21938                    data_type
21939                );
21940                // Note: Explicit '+' sign is not preserved in output, which is correct
21941                assert_eq!("NUMERIC(10,5)", data_type.to_string());
21942            });
21943        }
21944
21945        #[test]
21946        fn test_ansii_date_type() {
21947            // Datetime types: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#datetime-type>
21948            let dialect =
21949                TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(AnsiDialect {})]);
21950
21951            test_parse_data_type!(dialect, "DATE", DataType::Date);
21952
21953            test_parse_data_type!(dialect, "TIME", DataType::Time(None, TimezoneInfo::None));
21954
21955            test_parse_data_type!(
21956                dialect,
21957                "TIME(6)",
21958                DataType::Time(Some(6), TimezoneInfo::None)
21959            );
21960
21961            test_parse_data_type!(
21962                dialect,
21963                "TIME WITH TIME ZONE",
21964                DataType::Time(None, TimezoneInfo::WithTimeZone)
21965            );
21966
21967            test_parse_data_type!(
21968                dialect,
21969                "TIME(6) WITH TIME ZONE",
21970                DataType::Time(Some(6), TimezoneInfo::WithTimeZone)
21971            );
21972
21973            test_parse_data_type!(
21974                dialect,
21975                "TIME WITHOUT TIME ZONE",
21976                DataType::Time(None, TimezoneInfo::WithoutTimeZone)
21977            );
21978
21979            test_parse_data_type!(
21980                dialect,
21981                "TIME(6) WITHOUT TIME ZONE",
21982                DataType::Time(Some(6), TimezoneInfo::WithoutTimeZone)
21983            );
21984
21985            test_parse_data_type!(
21986                dialect,
21987                "TIMESTAMP",
21988                DataType::Timestamp(None, TimezoneInfo::None)
21989            );
21990
21991            test_parse_data_type!(
21992                dialect,
21993                "TIMESTAMP(22)",
21994                DataType::Timestamp(Some(22), TimezoneInfo::None)
21995            );
21996
21997            test_parse_data_type!(
21998                dialect,
21999                "TIMESTAMP(22) WITH TIME ZONE",
22000                DataType::Timestamp(Some(22), TimezoneInfo::WithTimeZone)
22001            );
22002
22003            test_parse_data_type!(
22004                dialect,
22005                "TIMESTAMP(33) WITHOUT TIME ZONE",
22006                DataType::Timestamp(Some(33), TimezoneInfo::WithoutTimeZone)
22007            );
22008        }
22009    }
22010
22011    #[test]
22012    fn test_parse_schema_name() {
22013        // The expected name should be identical as the input name, that's why I don't receive both
22014        macro_rules! test_parse_schema_name {
22015            ($input:expr, $expected_name:expr $(,)?) => {{
22016                all_dialects().run_parser_method(&*$input, |parser| {
22017                    let schema_name = parser.parse_schema_name().unwrap();
22018                    // Validate that the structure is the same as expected
22019                    assert_eq!(schema_name, $expected_name);
22020                    // Validate that the input and the expected structure serialization are the same
22021                    assert_eq!(schema_name.to_string(), $input.to_string());
22022                });
22023            }};
22024        }
22025
22026        let dummy_name = ObjectName::from(vec![Ident::new("dummy_name")]);
22027        let dummy_authorization = Ident::new("dummy_authorization");
22028
22029        test_parse_schema_name!(
22030            format!("{dummy_name}"),
22031            SchemaName::Simple(dummy_name.clone())
22032        );
22033
22034        test_parse_schema_name!(
22035            format!("AUTHORIZATION {dummy_authorization}"),
22036            SchemaName::UnnamedAuthorization(dummy_authorization.clone()),
22037        );
22038        test_parse_schema_name!(
22039            format!("{dummy_name} AUTHORIZATION {dummy_authorization}"),
22040            SchemaName::NamedAuthorization(dummy_name.clone(), dummy_authorization.clone()),
22041        );
22042    }
22043
22044    #[test]
22045    fn mysql_parse_index_table_constraint() {
22046        macro_rules! test_parse_table_constraint {
22047            ($dialect:expr, $input:expr, $expected:expr $(,)?) => {{
22048                $dialect.run_parser_method(&*$input, |parser| {
22049                    let constraint = parser.parse_optional_table_constraint().unwrap().unwrap();
22050                    // Validate that the structure is the same as expected
22051                    assert_eq!(constraint, $expected);
22052                    // Validate that the input and the expected structure serialization are the same
22053                    assert_eq!(constraint.to_string(), $input.to_string());
22054                });
22055            }};
22056        }
22057
22058        fn mk_expected_col(name: &str) -> IndexColumn {
22059            IndexColumn {
22060                column: OrderByExpr {
22061                    expr: Expr::Identifier(name.into()),
22062                    options: OrderByOptions {
22063                        sort: None,
22064                        nulls_first: None,
22065                    },
22066                    with_fill: None,
22067                },
22068                operator_class: None,
22069            }
22070        }
22071
22072        let dialect =
22073            TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(MySqlDialect {})]);
22074
22075        test_parse_table_constraint!(
22076            dialect,
22077            "INDEX (c1)",
22078            IndexConstraint {
22079                display_as_key: false,
22080                name: None,
22081                index_type: None,
22082                columns: vec![mk_expected_col("c1")],
22083                index_options: vec![],
22084            }
22085            .into()
22086        );
22087
22088        test_parse_table_constraint!(
22089            dialect,
22090            "KEY (c1)",
22091            IndexConstraint {
22092                display_as_key: true,
22093                name: None,
22094                index_type: None,
22095                columns: vec![mk_expected_col("c1")],
22096                index_options: vec![],
22097            }
22098            .into()
22099        );
22100
22101        test_parse_table_constraint!(
22102            dialect,
22103            "INDEX 'index' (c1, c2)",
22104            TableConstraint::Index(IndexConstraint {
22105                display_as_key: false,
22106                name: Some(Ident::with_quote('\'', "index")),
22107                index_type: None,
22108                columns: vec![mk_expected_col("c1"), mk_expected_col("c2")],
22109                index_options: vec![],
22110            })
22111        );
22112
22113        test_parse_table_constraint!(
22114            dialect,
22115            "INDEX USING BTREE (c1)",
22116            IndexConstraint {
22117                display_as_key: false,
22118                name: None,
22119                index_type: Some(IndexType::BTree),
22120                columns: vec![mk_expected_col("c1")],
22121                index_options: vec![],
22122            }
22123            .into()
22124        );
22125
22126        test_parse_table_constraint!(
22127            dialect,
22128            "INDEX USING HASH (c1)",
22129            IndexConstraint {
22130                display_as_key: false,
22131                name: None,
22132                index_type: Some(IndexType::Hash),
22133                columns: vec![mk_expected_col("c1")],
22134                index_options: vec![],
22135            }
22136            .into()
22137        );
22138
22139        test_parse_table_constraint!(
22140            dialect,
22141            "INDEX idx_name USING BTREE (c1)",
22142            IndexConstraint {
22143                display_as_key: false,
22144                name: Some(Ident::new("idx_name")),
22145                index_type: Some(IndexType::BTree),
22146                columns: vec![mk_expected_col("c1")],
22147                index_options: vec![],
22148            }
22149            .into()
22150        );
22151
22152        test_parse_table_constraint!(
22153            dialect,
22154            "INDEX idx_name USING HASH (c1)",
22155            IndexConstraint {
22156                display_as_key: false,
22157                name: Some(Ident::new("idx_name")),
22158                index_type: Some(IndexType::Hash),
22159                columns: vec![mk_expected_col("c1")],
22160                index_options: vec![],
22161            }
22162            .into()
22163        );
22164    }
22165
22166    #[test]
22167    fn test_tokenizer_error_loc() {
22168        let sql = "foo '";
22169        let ast = Parser::parse_sql(&GenericDialect, sql);
22170        assert_eq!(
22171            ast,
22172            Err(ParserError::TokenizerError(
22173                "Unterminated string literal at Line: 1, Column: 5".to_string()
22174            ))
22175        );
22176    }
22177
22178    #[test]
22179    fn test_parser_error_loc() {
22180        let sql = "SELECT this is a syntax error";
22181        let ParserError::ParserError(msg) = Parser::parse_sql(&GenericDialect, sql).unwrap_err()
22182        else {
22183            panic!("expected ParserError::ParserError");
22184        };
22185        assert!(
22186            msg.ends_with("found: a at Line: 1, Column: 16"),
22187            "unexpected error message: {msg}"
22188        );
22189    }
22190
22191    #[test]
22192    fn test_nested_explain_error() {
22193        let sql = "EXPLAIN EXPLAIN SELECT 1";
22194        let ast = Parser::parse_sql(&GenericDialect, sql);
22195        assert_eq!(
22196            ast,
22197            Err(ParserError::ParserError(
22198                "Explain must be root of the plan".to_string()
22199            ))
22200        );
22201    }
22202
22203    #[test]
22204    fn test_parse_multipart_identifier_positive() {
22205        let dialect = TestedDialects::new(vec![Box::new(GenericDialect {})]);
22206
22207        // parse multipart with quotes
22208        let expected = vec![
22209            Ident {
22210                value: "CATALOG".to_string(),
22211                quote_style: None,
22212                span: Span::empty(),
22213            },
22214            Ident {
22215                value: "F(o)o. \"bar".to_string(),
22216                quote_style: Some('"'),
22217                span: Span::empty(),
22218            },
22219            Ident {
22220                value: "table".to_string(),
22221                quote_style: None,
22222                span: Span::empty(),
22223            },
22224        ];
22225        dialect.run_parser_method(r#"CATALOG."F(o)o. ""bar".table"#, |parser| {
22226            let actual = parser.parse_multipart_identifier().unwrap();
22227            assert_eq!(expected, actual);
22228        });
22229
22230        // allow whitespace between ident parts
22231        let expected = vec![
22232            Ident {
22233                value: "CATALOG".to_string(),
22234                quote_style: None,
22235                span: Span::empty(),
22236            },
22237            Ident {
22238                value: "table".to_string(),
22239                quote_style: None,
22240                span: Span::empty(),
22241            },
22242        ];
22243        dialect.run_parser_method("CATALOG . table", |parser| {
22244            let actual = parser.parse_multipart_identifier().unwrap();
22245            assert_eq!(expected, actual);
22246        });
22247    }
22248
22249    #[test]
22250    fn test_parse_multipart_identifier_negative() {
22251        macro_rules! test_parse_multipart_identifier_error {
22252            ($input:expr, $expected_err:expr $(,)?) => {{
22253                all_dialects().run_parser_method(&*$input, |parser| {
22254                    let actual_err = parser.parse_multipart_identifier().unwrap_err();
22255                    assert_eq!(actual_err.to_string(), $expected_err);
22256                });
22257            }};
22258        }
22259
22260        test_parse_multipart_identifier_error!(
22261            "",
22262            "sql parser error: Empty input when parsing identifier",
22263        );
22264
22265        test_parse_multipart_identifier_error!(
22266            "*schema.table",
22267            "sql parser error: Unexpected token in identifier: *",
22268        );
22269
22270        test_parse_multipart_identifier_error!(
22271            "schema.table*",
22272            "sql parser error: Unexpected token in identifier: *",
22273        );
22274
22275        test_parse_multipart_identifier_error!(
22276            "schema.table.",
22277            "sql parser error: Trailing period in identifier",
22278        );
22279
22280        test_parse_multipart_identifier_error!(
22281            "schema.*",
22282            "sql parser error: Unexpected token following period in identifier: *",
22283        );
22284    }
22285
22286    #[test]
22287    fn test_mysql_partition_selection() {
22288        let sql = "SELECT * FROM employees PARTITION (p0, p2)";
22289        let expected = vec!["p0", "p2"];
22290
22291        let ast: Vec<Statement> = Parser::parse_sql(&MySqlDialect {}, sql).unwrap();
22292        assert_eq!(ast.len(), 1);
22293        if let Statement::Query(v) = &ast[0] {
22294            if let SetExpr::Select(select) = &*v.body {
22295                assert_eq!(select.from.len(), 1);
22296                let from: &TableWithJoins = &select.from[0];
22297                let table_factor = &from.relation;
22298                if let TableFactor::Table { partitions, .. } = table_factor {
22299                    let actual: Vec<&str> = partitions
22300                        .iter()
22301                        .map(|ident| ident.value.as_str())
22302                        .collect();
22303                    assert_eq!(expected, actual);
22304                }
22305            }
22306        } else {
22307            panic!("fail to parse mysql partition selection");
22308        }
22309    }
22310
22311    #[test]
22312    fn test_replace_into_placeholders() {
22313        let sql = "REPLACE INTO t (a) VALUES (&a)";
22314
22315        assert!(Parser::parse_sql(&GenericDialect {}, sql).is_err());
22316    }
22317
22318    #[test]
22319    fn test_replace_into_set_placeholder() {
22320        let sql = "REPLACE INTO t SET ?";
22321
22322        assert!(Parser::parse_sql(&GenericDialect {}, sql).is_err());
22323    }
22324
22325    #[test]
22326    fn test_replace_incomplete() {
22327        let sql = r#"REPLACE"#;
22328
22329        assert!(Parser::parse_sql(&MySqlDialect {}, sql).is_err());
22330    }
22331
22332    #[test]
22333    fn test_placeholder_invalid_whitespace() {
22334        for w in ["  ", "/*invalid*/"] {
22335            let sql = format!("\nSELECT\n  :{w}fooBar");
22336            assert!(Parser::parse_sql(&GenericDialect, &sql).is_err());
22337        }
22338    }
22339}